diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index a8f4c4de2..fd9f3b11c 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -4,13 +4,13 @@ contact_links: about: Please report security vulnerabilities to security@tiangolo.com - name: Question or Problem about: Ask a question or ask about a problem in GitHub Discussions. - url: https://github.com/tiangolo/fastapi/discussions/categories/questions + url: https://github.com/fastapi/fastapi/discussions/categories/questions - name: Feature Request about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already. - url: https://github.com/tiangolo/fastapi/discussions/categories/questions + url: https://github.com/fastapi/fastapi/discussions/categories/questions - name: Show and tell about: Show what you built with FastAPI or to be used with FastAPI. - url: https://github.com/tiangolo/fastapi/discussions/categories/show-and-tell + url: https://github.com/fastapi/fastapi/discussions/categories/show-and-tell - name: Translations about: Coordinate translations in GitHub Discussions. - url: https://github.com/tiangolo/fastapi/discussions/categories/translations + url: https://github.com/fastapi/fastapi/discussions/categories/translations diff --git a/.github/ISSUE_TEMPLATE/privileged.yml b/.github/ISSUE_TEMPLATE/privileged.yml index c01e34b6d..2b85eb310 100644 --- a/.github/ISSUE_TEMPLATE/privileged.yml +++ b/.github/ISSUE_TEMPLATE/privileged.yml @@ -6,7 +6,7 @@ body: value: | Thanks for your interest in FastAPI! 🚀 - If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/fastapi/discussions/categories/questions) instead. + If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/fastapi/fastapi/discussions/categories/questions) instead. - type: checkboxes id: privileged attributes: diff --git a/.github/actions/comment-docs-preview-in-pr/Dockerfile b/.github/actions/comment-docs-preview-in-pr/Dockerfile deleted file mode 100644 index 42627fe19..000000000 --- a/.github/actions/comment-docs-preview-in-pr/Dockerfile +++ /dev/null @@ -1,9 +0,0 @@ -FROM python:3.10 - -COPY ./requirements.txt /app/requirements.txt - -RUN pip install -r /app/requirements.txt - -COPY ./app /app - -CMD ["python", "/app/main.py"] diff --git a/.github/actions/comment-docs-preview-in-pr/action.yml b/.github/actions/comment-docs-preview-in-pr/action.yml deleted file mode 100644 index 0eb64402d..000000000 --- a/.github/actions/comment-docs-preview-in-pr/action.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Comment Docs Preview in PR -description: Comment with the docs URL preview in the PR -author: Sebastián Ramírez -inputs: - token: - description: Token for the repo. Can be passed in using {{ secrets.GITHUB_TOKEN }} - required: true - deploy_url: - description: The deployment URL to comment in the PR - required: true -runs: - using: docker - image: Dockerfile diff --git a/.github/actions/comment-docs-preview-in-pr/app/main.py b/.github/actions/comment-docs-preview-in-pr/app/main.py deleted file mode 100644 index 8cc119fe0..000000000 --- a/.github/actions/comment-docs-preview-in-pr/app/main.py +++ /dev/null @@ -1,69 +0,0 @@ -import logging -import sys -from pathlib import Path -from typing import Union - -import httpx -from github import Github -from github.PullRequest import PullRequest -from pydantic import BaseModel, SecretStr, ValidationError -from pydantic_settings import BaseSettings - -github_api = "https://api.github.com" - - -class Settings(BaseSettings): - github_repository: str - github_event_path: Path - github_event_name: Union[str, None] = None - input_token: SecretStr - input_deploy_url: str - - -class PartialGithubEventHeadCommit(BaseModel): - id: str - - -class PartialGithubEventWorkflowRun(BaseModel): - head_commit: PartialGithubEventHeadCommit - - -class PartialGithubEvent(BaseModel): - workflow_run: PartialGithubEventWorkflowRun - - -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - settings = Settings() - logging.info(f"Using config: {settings.json()}") - g = Github(settings.input_token.get_secret_value()) - repo = g.get_repo(settings.github_repository) - try: - event = PartialGithubEvent.parse_file(settings.github_event_path) - except ValidationError as e: - logging.error(f"Error parsing event file: {e.errors()}") - sys.exit(0) - use_pr: Union[PullRequest, None] = None - for pr in repo.get_pulls(): - if pr.head.sha == event.workflow_run.head_commit.id: - use_pr = pr - break - if not use_pr: - logging.error(f"No PR found for hash: {event.workflow_run.head_commit.id}") - sys.exit(0) - github_headers = { - "Authorization": f"token {settings.input_token.get_secret_value()}" - } - url = f"{github_api}/repos/{settings.github_repository}/issues/{use_pr.number}/comments" - logging.info(f"Using comments URL: {url}") - response = httpx.post( - url, - headers=github_headers, - json={ - "body": f"📝 Docs preview for commit {use_pr.head.sha} at: {settings.input_deploy_url}" - }, - ) - if not (200 <= response.status_code <= 300): - logging.error(f"Error posting comment: {response.text}") - sys.exit(1) - logging.info("Finished") diff --git a/.github/actions/notify-translations/app/main.py b/.github/actions/notify-translations/app/main.py index 8ac1f233d..716232d49 100644 --- a/.github/actions/notify-translations/app/main.py +++ b/.github/actions/notify-translations/app/main.py @@ -11,7 +11,7 @@ from pydantic import BaseModel, BaseSettings, SecretStr awaiting_label = "awaiting-review" lang_all_label = "lang-all" -approved_label = "approved-2" +approved_label = "approved-1" translations_path = Path(__file__).parent / "translations.yml" github_graphql_url = "https://api.github.com/graphql" @@ -19,7 +19,7 @@ questions_translations_category_id = "DIC_kwDOCZduT84CT5P9" all_discussions_query = """ query Q($category_id: ID) { - repository(name: "fastapi", owner: "tiangolo") { + repository(name: "fastapi", owner: "fastapi") { discussions(categoryId: $category_id, first: 100) { nodes { title @@ -41,7 +41,7 @@ query Q($category_id: ID) { translation_discussion_query = """ query Q($after: String, $discussion_number: Int!) { - repository(name: "fastapi", owner: "tiangolo") { + repository(name: "fastapi", owner: "fastapi") { discussion(number: $discussion_number) { comments(first: 100, after: $after) { edges { diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py index 9f2b9369d..b752d9d2b 100644 --- a/.github/actions/people/app/main.py +++ b/.github/actions/people/app/main.py @@ -17,7 +17,7 @@ questions_category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMDAxNDM0" discussions_query = """ query Q($after: String, $category_id: ID) { - repository(name: "fastapi", owner: "tiangolo") { + repository(name: "fastapi", owner: "fastapi") { discussions(first: 100, after: $after, categoryId: $category_id) { edges { cursor @@ -61,7 +61,7 @@ query Q($after: String, $category_id: ID) { prs_query = """ query Q($after: String) { - repository(name: "fastapi", owner: "tiangolo") { + repository(name: "fastapi", owner: "fastapi") { pullRequests(first: 100, after: $after) { edges { cursor @@ -109,7 +109,7 @@ query Q($after: String) { sponsors_query = """ query Q($after: String) { - user(login: "tiangolo") { + user(login: "fastapi") { sponsorshipsAsMaintainer(first: 100, after: $after) { edges { cursor @@ -515,9 +515,9 @@ def get_individual_sponsors(settings: Settings): tiers: DefaultDict[float, Dict[str, SponsorEntity]] = defaultdict(dict) for node in nodes: - tiers[node.tier.monthlyPriceInDollars][ - node.sponsorEntity.login - ] = node.sponsorEntity + tiers[node.tier.monthlyPriceInDollars][node.sponsorEntity.login] = ( + node.sponsorEntity + ) return tiers diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0a59adbd6..8979aabf8 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,9 +12,5 @@ updates: directory: "/" schedule: interval: "monthly" - groups: - python-packages: - patterns: - - "*" commit-message: prefix: ⬆ diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 000000000..c5b1f84f3 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,38 @@ +docs: + - all: + - changed-files: + - any-glob-to-any-file: + - docs/en/docs/** + - docs_src/** + - all-globs-to-all-files: + - '!fastapi/**' + - '!pyproject.toml' + - '!docs/en/data/sponsors.yml' + - '!docs/en/overrides/main.html' + +lang-all: + - all: + - changed-files: + - any-glob-to-any-file: + - docs/*/docs/** + - all-globs-to-all-files: + - '!docs/en/docs/**' + - '!fastapi/**' + - '!pyproject.toml' + +internal: + - all: + - changed-files: + - any-glob-to-any-file: + - .github/** + - scripts/** + - .gitignore + - .pre-commit-config.yaml + - pdm_build.py + - requirements*.txt + - docs/en/data/sponsors.yml + - docs/en/overrides/main.html + - all-globs-to-all-files: + - '!docs/*/docs/**' + - '!fastapi/**' + - '!pyproject.toml' diff --git a/.github/workflows/add-to-project.yml b/.github/workflows/add-to-project.yml new file mode 100644 index 000000000..dccea83f3 --- /dev/null +++ b/.github/workflows/add-to-project.yml @@ -0,0 +1,18 @@ +name: Add to Project + +on: + pull_request_target: + issues: + types: + - opened + - reopened + +jobs: + add-to-project: + name: Add to project + runs-on: ubuntu-latest + steps: + - uses: actions/add-to-project@v1.0.2 + with: + project-url: https://github.com/orgs/fastapi/projects/2 + github-token: ${{ secrets.PROJECTS_TOKEN }} diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 9b167ee66..dd11727c7 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -7,6 +7,10 @@ on: types: - opened - synchronize + +env: + UV_SYSTEM_PYTHON: 1 + jobs: changes: runs-on: ubuntu-latest @@ -18,7 +22,7 @@ jobs: docs: ${{ steps.filter.outputs.docs }} steps: - uses: actions/checkout@v4 - # For pull requests it's not necessary to checkout the code but for master it is + # For pull requests it's not necessary to checkout the code but for the main branch it is - uses: dorny/paths-filter@v3 id: filter with: @@ -28,9 +32,12 @@ jobs: - docs/** - docs_src/** - requirements-docs.txt + - requirements-docs-insiders.txt - pyproject.toml - mkdocs.yml - mkdocs.insiders.yml + - mkdocs.maybe-insiders.yml + - mkdocs.no-insiders.yml - .github/workflows/build-docs.yml - .github/workflows/deploy-docs.yml langs: @@ -45,21 +52,22 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - - uses: actions/cache@v3 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v3 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v07 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install docs extras - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-docs.txt + run: uv pip install -r requirements-docs.txt # Install MkDocs Material Insiders here just to put it in the cache for the rest of the steps - name: Install Material for MkDocs Insiders - if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' - run: | - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git + if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) + run: uv pip install -r requirements-docs-insiders.txt + env: + TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }} - name: Verify Docs run: python ./scripts/docs.py verify-docs - name: Export Language Codes @@ -86,32 +94,34 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - - uses: actions/cache@v3 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v3 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v08 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install docs extras - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-docs.txt + run: uv pip install -r requirements-docs.txt - name: Install Material for MkDocs Insiders - if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' - run: | - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git + if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) + run: uv pip install -r requirements-docs-insiders.txt + env: + TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }} - name: Update Languages run: python ./scripts/docs.py update-languages - - uses: actions/cache@v3 + - uses: actions/cache@v4 with: key: mkdocs-cards-${{ matrix.lang }}-${{ github.ref }} path: docs/${{ matrix.lang }}/.cache - name: Build Docs run: python ./scripts/docs.py build-lang ${{ matrix.lang }} - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: - name: docs-site + name: docs-site-${{ matrix.lang }} path: ./site/** + include-hidden-files: true # https://github.com/marketplace/actions/alls-green#why docs-all-green: # This job does nothing and is only used for the branch protection diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index b8dbb7dc5..387063f12 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -6,6 +6,15 @@ on: types: - completed +permissions: + deployments: write + issues: write + pull-requests: write + statuses: write + +env: + UV_SYSTEM_PYTHON: 1 + jobs: deploy-docs: runs-on: ubuntu-latest @@ -15,34 +24,57 @@ jobs: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v3 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install GitHub Actions dependencies + run: uv pip install -r requirements-github-actions.txt + - name: Deploy Docs Status Pending + run: python ./scripts/deploy_docs_status.py + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.run_id }} - name: Clean site run: | rm -rf ./site mkdir ./site - - name: Download Artifact Docs - id: download - uses: dawidd6/action-download-artifact@v3.1.4 + - uses: actions/download-artifact@v4 with: - if_no_artifact_found: ignore - github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} - workflow: build-docs.yml - run_id: ${{ github.event.workflow_run.id }} - name: docs-site path: ./site/ + pattern: docs-site-* + merge-multiple: true + github-token: ${{ secrets.GITHUB_TOKEN }} + run-id: ${{ github.event.workflow_run.id }} - name: Deploy to Cloudflare Pages - if: steps.download.outputs.found_artifact == 'true' + # hashFiles returns an empty string if there are no files + if: hashFiles('./site/*') id: deploy - uses: cloudflare/pages-action@v1 + env: + PROJECT_NAME: fastapitiangolo + BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} + # TODO: Use v3 when it's fixed, probably in v3.11 + # https://github.com/cloudflare/wrangler-action/issues/307 + uses: cloudflare/wrangler-action@v3.12 + # uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - projectName: fastapitiangolo - directory: './site' - gitHubToken: ${{ secrets.GITHUB_TOKEN }} - branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} + command: pages deploy ./site --project-name=${{ env.PROJECT_NAME }} --branch=${{ env.BRANCH }} - name: Comment Deploy - if: steps.deploy.outputs.url != '' - uses: ./.github/actions/comment-docs-preview-in-pr - with: - token: ${{ secrets.FASTAPI_PREVIEW_DOCS_COMMENT_DEPLOY }} - deploy_url: "${{ steps.deploy.outputs.url }}" + run: python ./scripts/deploy_docs_status.py + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + DEPLOY_URL: ${{ steps.deploy.outputs.deployment-url }} + COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.run_id }} + IS_DONE: "true" diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index 0f564d721..6a7e6143e 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -2,7 +2,7 @@ name: Issue Manager on: schedule: - - cron: "10 3 * * *" + - cron: "13 22 * * *" issue_comment: types: - created @@ -14,26 +14,34 @@ on: - labeled workflow_dispatch: +permissions: + issues: write + pull-requests: write + jobs: issue-manager: - if: github.repository_owner == 'tiangolo' + if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: tiangolo/issue-manager@0.5.0 + - uses: tiangolo/issue-manager@0.5.1 with: - token: ${{ secrets.FASTAPI_ISSUE_MANAGER }} + token: ${{ secrets.GITHUB_TOKEN }} config: > { "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": { + "waiting": { "delay": 2628000, - "message": "As this PR had requested changes to be applied but has been inactive for a while, it's now going to be closed. But if there's anyone interested, feel free to create a new PR." + "message": "As this PR has been waiting for the original user for a while but seems to be inactive, it's now going to be closed. But if there's anyone interested, feel free to create a new PR." + }, + "invalid": { + "delay": 0, + "message": "This was marked as invalid and will be closed now. If this is an error, please provide additional details." } } diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 51be2413d..11176bed8 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -5,19 +5,41 @@ on: - cron: "0 12 * * *" workflow_dispatch: +permissions: + pull-requests: write + +env: + UV_SYSTEM_PYTHON: 1 + jobs: label-approved: - if: github.repository_owner == 'tiangolo' + if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: docker://tiangolo/label-approved:0.0.4 + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 with: - token: ${{ secrets.FASTAPI_LABEL_APPROVED }} - config: > + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v3 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install GitHub Actions dependencies + run: uv pip install -r requirements-github-actions.txt + - name: Label Approved + run: python ./scripts/label_approved.py + env: + TOKEN: ${{ secrets.GITHUB_TOKEN }} + CONFIG: > { "approved-1": { diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 000000000..e8e58015a --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,33 @@ +name: Labels +on: + pull_request_target: + types: + - opened + - synchronize + - reopened + # For label-checker + - labeled + - unlabeled + +jobs: + labeler: + permissions: + contents: read + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@v5 + if: ${{ github.event.action != 'labeled' && github.event.action != 'unlabeled' }} + - run: echo "Done adding labels" + # Run this after labeler applied labels + check-labels: + needs: + - labeler + permissions: + pull-requests: read + runs-on: ubuntu-latest + steps: + - uses: docker://agilepathway/pull-request-label-checker:latest + with: + one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal + repo_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index 27e062d09..b8b5c42ee 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -34,8 +34,7 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: docker://tiangolo/latest-changes:0.3.0 - # - uses: tiangolo/latest-changes@main + - uses: tiangolo/latest-changes@0.3.2 with: token: ${{ secrets.GITHUB_TOKEN }} latest_changes_file: docs/en/docs/release-notes.md diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index c0904ce48..98aa41e5a 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -15,6 +15,12 @@ on: required: false default: 'false' +permissions: + discussions: write + +env: + UV_SYSTEM_PYTHON: 1 + jobs: notify-translations: runs-on: ubuntu-latest @@ -24,6 +30,19 @@ jobs: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v3 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml # Allow debugging with tmate - name: Setup tmate session uses: mxschmitt/action-tmate@v3 @@ -32,4 +51,4 @@ jobs: limit-access-to-actor: true - uses: ./.github/actions/notify-translations with: - token: ${{ secrets.FASTAPI_NOTIFY_TRANSLATIONS }} + token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml index b0868771d..c60c63d1b 100644 --- a/.github/workflows/people.yml +++ b/.github/workflows/people.yml @@ -12,7 +12,7 @@ on: jobs: fastapi-people: - if: github.repository_owner == 'tiangolo' + if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest steps: - name: Dump GitHub context diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 899e49057..fc61c3fca 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -8,6 +8,13 @@ on: jobs: publish: runs-on: ubuntu-latest + strategy: + matrix: + package: + - fastapi + - fastapi-slim + permissions: + id-token: write steps: - name: Dump GitHub context env: @@ -24,11 +31,11 @@ jobs: - name: Install build dependencies run: pip install build - name: Build distribution + env: + TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.8.11 - with: - password: ${{ secrets.PYPI_API_TOKEN }} + uses: pypa/gh-action-pypi-publish@v1.12.2 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index c4043cc6a..daff8e244 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -8,6 +8,9 @@ on: permissions: statuses: write +env: + UV_SYSTEM_PYTHON: 1 + jobs: smokeshow: if: ${{ github.event.workflow_run.conclusion == 'success' }} @@ -18,23 +21,30 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.9' - - - run: pip install smokeshow - - - uses: dawidd6/action-download-artifact@v3.1.4 + - name: Setup uv + uses: astral-sh/setup-uv@v3 with: - github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} - workflow: test.yml - commit: ${{ github.event.workflow_run.head_sha }} - - - run: smokeshow upload coverage-html + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - run: uv pip install -r requirements-github-actions.txt + - uses: actions/download-artifact@v4 + with: + name: coverage-html + path: htmlcov + github-token: ${{ secrets.GITHUB_TOKEN }} + run-id: ${{ github.event.workflow_run.id }} + - run: smokeshow upload htmlcov env: SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 100 SMOKESHOW_GITHUB_CONTEXT: coverage - SMOKESHOW_GITHUB_TOKEN: ${{ secrets.FASTAPI_SMOKESHOW_UPLOAD }} + SMOKESHOW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SMOKESHOW_GITHUB_PR_HEAD_SHA: ${{ github.event.workflow_run.head_sha }} SMOKESHOW_AUTH_KEY: ${{ secrets.SMOKESHOW_AUTH_KEY }} diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml index c2e05013b..693f0c603 100644 --- a/.github/workflows/test-redistribute.yml +++ b/.github/workflows/test-redistribute.yml @@ -12,6 +12,11 @@ on: jobs: test-redistribute: runs-on: ubuntu-latest + strategy: + matrix: + package: + - fastapi + - fastapi-slim steps: - name: Dump GitHub context env: @@ -22,12 +27,11 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.10" - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml - name: Install build dependencies run: pip install build - name: Build source distribution + env: + TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build --sdist - name: Decompress source distribution run: | @@ -35,17 +39,31 @@ jobs: tar xvf fastapi*.tar.gz - name: Install test dependencies run: | - cd dist/fastapi-*/ + cd dist/fastapi*/ pip install -r requirements-tests.txt + env: + TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} - name: Run source distribution tests run: | - cd dist/fastapi-*/ + cd dist/fastapi*/ bash scripts/test.sh - name: Build wheel distribution run: | cd dist - pip wheel --no-deps fastapi-*.tar.gz + pip wheel --no-deps fastapi*.tar.gz - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" + + # https://github.com/marketplace/actions/alls-green#why + test-redistribute-alls-green: # This job does nothing and is only used for the branch protection + if: always() + needs: + - test-redistribute + runs-on: ubuntu-latest + steps: + - name: Decide whether the needed jobs succeeded or failed + uses: re-actors/alls-green@release/v1 + with: + jobs: ${{ toJSON(needs) }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b6b173685..643037a12 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,6 +8,12 @@ on: types: - opened - synchronize + schedule: + # cron every week on monday + - cron: "0 0 * * 1" + +env: + UV_SYSTEM_PYTHON: 1 jobs: lint: @@ -22,19 +28,18 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml - - uses: actions/cache@v3 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v3 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install Dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-tests.txt + run: uv pip install -r requirements-tests.txt - name: Install Pydantic v2 - run: pip install "pydantic>=2.0.2,<3.0.0" + run: uv pip install --upgrade "pydantic>=2.0.2,<3.0.0" - name: Lint run: bash scripts/lint.sh @@ -60,23 +65,22 @@ jobs: uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml - - uses: actions/cache@v3 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v3 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install Dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-tests.txt + run: uv pip install -r requirements-tests.txt - name: Install Pydantic v1 if: matrix.pydantic-version == 'pydantic-v1' - run: pip install "pydantic>=1.10.0,<2.0.0" + run: uv pip install "pydantic>=1.10.0,<2.0.0" - name: Install Pydantic v2 if: matrix.pydantic-version == 'pydantic-v2' - run: pip install "pydantic>=2.0.2,<3.0.0" + run: uv pip install --upgrade "pydantic>=2.0.2,<3.0.0" - run: mkdir coverage - name: Test run: bash scripts/test.sh @@ -84,10 +88,11 @@ jobs: COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }} CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }} - name: Store coverage files - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: - name: coverage + name: coverage-${{ matrix.python-version }}-${{ matrix.pydantic-version }} path: coverage + include-hidden-files: true coverage-combine: needs: [test] @@ -101,24 +106,32 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.8' - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml + - name: Setup uv + uses: astral-sh/setup-uv@v3 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-tests.txt - name: Get coverage files - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: - name: coverage + pattern: coverage-* path: coverage - - run: pip install coverage[toml] + merge-multiple: true - run: ls -la coverage - run: coverage combine coverage - run: coverage report - - run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}" + - run: coverage html --title "Coverage for ${{ github.sha }}" - name: Store coverage HTML - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: coverage-html path: htmlcov + include-hidden-files: true # https://github.com/marketplace/actions/alls-green#why check: # This job does nothing and is only used for the branch protection diff --git a/.gitignore b/.gitignore index 9be494cec..ef6364a9a 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,7 @@ __pycache__ htmlcov dist site -.coverage +.coverage* coverage.xml .netlify test.db diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4d49845d6..d90e7281e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ default_language_version: python: python3.10 repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v5.0.0 hooks: - id: check-added-large-files - id: check-toml @@ -13,8 +13,8 @@ repos: - --unsafe - id: end-of-file-fixer - id: trailing-whitespace -- repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.2.0 +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.7.2 hooks: - id: ruff args: diff --git a/CITATION.cff b/CITATION.cff index 9028248b1..f14700349 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -12,7 +12,7 @@ authors: family-names: Ramírez email: tiangolo@gmail.com identifiers: -repository-code: 'https://github.com/tiangolo/fastapi' +repository-code: 'https://github.com/fastapi/fastapi' url: 'https://fastapi.tiangolo.com' abstract: >- FastAPI framework, high performance, easy to learn, fast to code, diff --git a/README.md b/README.md index 67275d29d..62eeda03b 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,11 @@ FastAPI framework, high performance, easy to learn, fast to code, ready for production

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +23,11 @@ **Documentation**: https://fastapi.tiangolo.com -**Source Code**: https://github.com/tiangolo/fastapi +**Source Code**: https://github.com/fastapi/fastapi --- -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints. +FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints. The key features are: @@ -50,17 +50,19 @@ The key features are: - - + - + + + - + + @@ -70,7 +72,7 @@ The key features are: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -94,7 +96,7 @@ The key features are: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -122,8 +124,6 @@ If you are building a CLI app to be ## Requirements -Python 3.8+ - FastAPI stands on the shoulders of giants: * Starlette for the web parts. @@ -131,28 +131,20 @@ FastAPI stands on the shoulders of giants: ## Installation -
- -```console -$ pip install fastapi - ----> 100% -``` - -
- -You will also need an ASGI server, for production such as Uvicorn or Hypercorn. +Create and activate a virtual environment and then install FastAPI:
```console -$ pip install "uvicorn[standard]" +$ pip install "fastapi[standard]" ---> 100% ```
+**Note**: Make sure you put `"fastapi[standard]"` in quotes to ensure it works in all terminals. + ## Example ### Create it @@ -213,11 +205,24 @@ Run the server with:
```console -$ uvicorn main:app --reload - +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete. ``` @@ -225,13 +230,13 @@ INFO: Application startup complete.
-About the command uvicorn main:app --reload... +About the command fastapi dev main.py... -The command `uvicorn main:app` refers to: +The command `fastapi dev` reads your `main.py` file, detects the **FastAPI** app in it, and starts a server using Uvicorn. -* `main`: the file `main.py` (the Python "module"). -* `app`: the object created inside of `main.py` with the line `app = FastAPI()`. -* `--reload`: make the server restart after code changes. Only do this for development. +By default, `fastapi dev` will start with auto-reload enabled for local development. + +You can read more about it in the FastAPI CLI docs.
@@ -304,7 +309,7 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -The server should reload automatically (because you added `--reload` to the `uvicorn` command above). +The `fastapi dev` server should reload automatically. ### Interactive API docs upgrade @@ -338,7 +343,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.8+**. +Just standard **Python**. For example, for an `int`: @@ -388,7 +393,7 @@ Coming back to the previous code example, **FastAPI** will: * Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. * As the `q` parameter is declared with `= None`, it is optional. * Without the `None` it would be required (as is the body in the case with `PUT`). -* For `PUT` requests to `/items/{item_id}`, Read the body as JSON: +* For `PUT` requests to `/items/{item_id}`, read the body as JSON: * Check that it has a required attribute `name` that should be a `str`. * Check that it has a required attribute `price` that has to be a `float`. * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. @@ -448,29 +453,46 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under U To understand more about it, see the section Benchmarks. -## Optional Dependencies +## Dependencies + +FastAPI depends on Pydantic and Starlette. + +### `standard` Dependencies + +When you install FastAPI with `pip install "fastapi[standard]"` it comes the `standard` group of optional dependencies: Used by Pydantic: -* email_validator - for email validation. -* pydantic-settings - for settings management. -* pydantic-extra-types - for extra types to be used with Pydantic. +* email-validator - for email validation. Used by Starlette: * httpx - Required if you want to use the `TestClient`. * jinja2 - Required if you want to use the default template configuration. * python-multipart - Required if you want to support form "parsing", with `request.form()`. -* itsdangerous - Required for `SessionMiddleware` support. -* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI). -* ujson - Required if you want to use `UJSONResponse`. Used by FastAPI / Starlette: -* uvicorn - for the server that loads and serves your application. -* orjson - Required if you want to use `ORJSONResponse`. +* uvicorn - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving. +* `fastapi-cli` - to provide the `fastapi` command. + +### Without `standard` Dependencies + +If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`. + +### Additional Optional Dependencies + +There are some additional dependencies you might want to install. -You can install all of these with `pip install "fastapi[all]"`. +Additional optional Pydantic dependencies: + +* pydantic-settings - for settings management. +* pydantic-extra-types - for extra types to be used with Pydantic. + +Additional optional FastAPI dependencies: + +* orjson - Required if you want to use `ORJSONResponse`. +* ujson - Required if you want to use `UJSONResponse`. ## License diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md deleted file mode 100644 index 2ca8e109e..000000000 --- a/docs/az/docs/fastapi-people.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI İnsanlar - -FastAPI-ın bütün mənşəli insanları qəbul edən heyrətamiz icması var. - - - -## Yaradıcı - İcraçı - -Salam! 👋 - -Bu mənəm: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Cavablar: {{ user.answers }}
Pull Request-lər: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Mən **FastAPI**-ın yaradıcısı və icraçısıyam. Əlavə məlumat almaq üçün [Yardım FastAPI - Yardım alın - Müəlliflə əlaqə qurun](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} səhifəsinə baxa bilərsiniz. - -...Burada isə sizə icmanı göstərmək istəyirəm. - ---- - -**FastAPI** icmadan çoxlu dəstək alır və mən onların əməyini vurğulamaq istəyirəm. - -Bu insanlar: - -* [GitHub-da başqalarının suallarına kömək edirlər](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Pull Request-lər yaradırlar](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Pull Request-ləri ([xüsusilə tərcümələr üçün vacib olan](contributing.md#translations){.internal-link target=_blank}.) nəzərdən keçirirlər. - -Bu insanlara təşəkkür edirəm. 👏 🙇 - -## Keçən ayın ən fəal istifadəçiləri - -Bu istifadəçilər keçən ay [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Cavablandırılmış suallar: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Mütəxəssislər - -Burada **FastAPI Mütəxəssisləri** var. 🤓 - -Bu istifadəçilər indiyə qədər [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. - -Onlar bir çox insanlara kömək edərək mütəxəssis olduqlarını sübut ediblər. ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Cavablandırılmış suallar: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Ən yaxşı əməkdaşlar - -Burada **Ən yaxşı əməkdaşlar** var. 👷 - -Bu istifadəçilərin ən çox *birləşdirilmiş* [Pull Request-ləri var](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. - -Onlar mənbə kodu, sənədləmə, tərcümələr və s. barədə əmək göstərmişlər. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Request-lər: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Bundan başqa bir neçə (yüzdən çox) əməkdaş var ki, onları FastAPI GitHub Əməkdaşlar səhifəsində görə bilərsiniz. 👷 - -## Ən çox rəy verənlər - -Bu istifadəçilər **ən çox rəy verənlər**dir. - -### Tərcümələr üçün rəylər - -Mən yalnız bir neçə dildə danışıram (və çox da yaxşı deyil 😅). Bu səbəbdən, rəy verənlər sənədlərin [**tərcümələrini təsdiqləmək üçün gücə malik olanlar**](contributing.md#translations){.internal-link target=_blank}dır. Onlar olmadan, bir çox dilə tərcümə olunmuş sənədlər olmazdı. - ---- - -Başqalarının Pull Request-lərinə **Ən çox rəy verənlər** 🕵️ kodun, sənədlərin və xüsusilə də **tərcümələrin** keyfiyyətini təmin edirlər. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Rəylər: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsorlar - -Bunlar **Sponsorlar**dır. 😎 - -Onlar mənim **FastAPI** (və digər) işlərimi əsasən GitHub Sponsorlar vasitəsilə dəstəkləyirlər. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Qızıl Sponsorlar - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Gümüş Sponsorlar - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bürünc Sponsorlar - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Fərdi Sponsorlar - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## Məlumatlar haqqında - texniki detallar - -Bu səhifənin əsas məqsədi, icmanın başqalarına kömək etmək üçün göstərdiyi əməyi vurğulamaqdır. - -Xüsusilə də normalda daha az görünən və bir çox hallarda daha çətin olan, başqalarının suallarına kömək etmək və tərcümələrlə bağlı Pull Request-lərə rəy vermək kimi səy göstərmək. - -Bu səhifənin məlumatları hər ay hesablanır və siz buradan mənbə kodunu oxuya bilərsiniz. - -Burada sponsorların əməyini də vurğulamaq istəyirəm. - -Mən həmçinin alqoritmi, bölmələri, eşikləri və s. yeniləmək hüququnu da qoruyuram (hər ehtimala qarşı 🤷). diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index 33bcc1556..ad78d7d06 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -5,11 +5,11 @@ FastAPI framework, yüksək məshuldarlı, öyrənməsi asan, çevik kodlama, istifadəyə hazırdır

- - Test + + Test - - Əhatə + + Əhatə Paket versiyası @@ -23,11 +23,11 @@ **Sənədlər**: https://fastapi.tiangolo.com -**Qaynaq Kodu**: https://github.com/tiangolo/fastapi +**Qaynaq Kodu**: https://github.com/fastapi/fastapi --- -FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python tip məsləhətlərinə əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür. +FastAPI Python ilə API yaratmaq üçün standart Python tip məsləhətlərinə əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür. Əsas xüsusiyyətləri bunlardır: @@ -63,7 +63,7 @@ FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python Kabir Khan - Microsoft (ref) +

Kabir Khan - Microsoft (ref)
--- @@ -87,7 +87,7 @@ FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python Timothy Crosley - Hug creator (ref) +
Timothy Crosley - Hug creator (ref)
--- @@ -115,8 +115,6 @@ FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python Starlette. @@ -330,7 +328,7 @@ Bunu standart müasir Python tipləri ilə edirsiniz. Yeni sintaksis, müəyyən bir kitabxananın metodlarını və ya siniflərini və s. öyrənmək məcburiyyətində deyilsiniz. -Sadəcə standart **Python 3.8+**. +Sadəcə standart **Python**. Məsələn, `int` üçün: @@ -444,7 +442,7 @@ Müstəqil TechEmpower meyarları göstərir ki, Uvicorn üzərində işləyən Pydantic tərəfindən istifadə olunanlar: -* email_validator - e-poçtun yoxlanılması üçün. +* email-validator - e-poçtun yoxlanılması üçün. * pydantic-settings - parametrlərin idarə edilməsi üçün. * pydantic-extra-types - Pydantic ilə istifadə edilə bilən əlavə tiplər üçün. diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index 688f3f95a..678ac9ca9 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -5,11 +5,11 @@ FastAPI উচ্চক্ষমতা সম্পন্ন, সহজে শেখার এবং দ্রুত কোড করে প্রোডাকশনের জন্য ফ্রামওয়ার্ক।

- - Test + + Test - - Coverage + + Coverage Package version @@ -20,7 +20,7 @@ **নির্দেশিকা নথি**: https://fastapi.tiangolo.com -**সোর্স কোড**: https://github.com/tiangolo/fastapi +**সোর্স কোড**: https://github.com/fastapi/fastapi --- @@ -61,7 +61,7 @@ FastAPI একটি আধুনিক, দ্রুত ( বেশি ক্ "_আমি আজকাল **FastAPI** ব্যবহার করছি। [...] আমরা ভাবছি মাইক্রোসফ্টে **ML সার্ভিস** এ সকল দলের জন্য এটি ব্যবহার করব। যার মধ্যে কিছু পণ্য **Windows** এ সংযোযন হয় এবং কিছু **Office** এর সাথে সংযোযন হচ্ছে।_" -

কবির খান - মাইক্রোসফ্টে (ref)
+
কবির খান - মাইক্রোসফ্টে (ref)
--- @@ -85,7 +85,7 @@ FastAPI একটি আধুনিক, দ্রুত ( বেশি ক্ "\_সত্যিই, আপনি যা তৈরি করেছেন তা খুব মজবুত এবং পরিপূর্ন৷ অনেক উপায়ে, আমি যা **Hug** এ করতে চেয়েছিলাম - তা কাউকে তৈরি করতে দেখে আমি সত্যিই অনুপ্রানিত৷\_" -
টিমোথি ক্রসলে - Hug স্রষ্টা (ref)
+
টিমোথি ক্রসলে - Hug স্রষ্টা (ref)
--- @@ -126,7 +126,7 @@ $ pip install fastapi -আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য Uvicorn অথবা Hypercorn. +আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য Uvicorn অথবা Hypercorn.
@@ -439,8 +439,7 @@ item: Item Pydantic দ্বারা ব্যবহৃত: -- ujson - দ্রুত JSON এর জন্য "parsing". -- email_validator - ইমেল যাচাইকরণের জন্য। +- email-validator - ইমেল যাচাইকরণের জন্য। স্টারলেট দ্বারা ব্যবহৃত: @@ -450,12 +449,12 @@ Pydantic দ্বারা ব্যবহৃত: - itsdangerous - `SessionMiddleware` সহায়তার জন্য প্রয়োজন। - pyyaml - স্টারলেটের SchemaGenerator সাপোর্ট এর জন্য প্রয়োজন (আপনার সম্ভাবত FastAPI প্রয়োজন নেই)। - graphene - `GraphQLApp` সহায়তার জন্য প্রয়োজন। -- ujson - আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। FastAPI / Starlette দ্বারা ব্যবহৃত: - uvicorn - সার্ভারের জন্য যা আপনার অ্যাপ্লিকেশন লোড করে এবং পরিবেশন করে। - orjson - আপনি `ORJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। +- ujson - আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। আপনি এই সব ইনস্টল করতে পারেন `pip install fastapi[all]` দিয়ে. diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md new file mode 100644 index 000000000..4a602b679 --- /dev/null +++ b/docs/bn/docs/python-types.md @@ -0,0 +1,596 @@ +# পাইথন এর টাইপ্স পরিচিতি + +Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাইপ অ্যানোটেশন" নামেও পরিচিত) এর জন্য সাপোর্ট রয়েছে। + +এই **"টাইপ হিন্ট"** বা অ্যানোটেশনগুলি এক ধরণের বিশেষ সিনট্যাক্স যা একটি ভেরিয়েবলের টাইপ ঘোষণা করতে দেয়। + +ভেরিয়েবলগুলির জন্য টাইপ ঘোষণা করলে, এডিটর এবং টুলগুলি আপনাকে আরও ভালো সাপোর্ট দিতে পারে। + +এটি পাইথন টাইপ হিন্ট সম্পর্কে একটি দ্রুত **টিউটোরিয়াল / রিফ্রেশার** মাত্র। এটি **FastAPI** এর সাথে ব্যবহার করার জন্য শুধুমাত্র ন্যূনতম প্রয়োজনীয়তা কভার করে... যা আসলে খুব একটা বেশি না। + +**FastAPI** এই টাইপ হিন্টগুলির উপর ভিত্তি করে নির্মিত, যা এটিকে অনেক সুবিধা এবং লাভ প্রদান করে। + +তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে। + +/// note + +যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান। + +/// + +## প্রেরণা + +চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি: + +```Python +{!../../docs_src/python_types/tutorial001.py!} +``` + +এই প্রোগ্রামটি কল করলে আউটপুট হয়: + +``` +John Doe +``` + +ফাংশনটি নিম্নলিখিত কাজ করে: + +* `first_name` এবং `last_name` নেয়। +* প্রতিটির প্রথম অক্ষরকে `title()` ব্যবহার করে বড় হাতের অক্ষরে রূপান্তর করে। +* তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে। + +```Python hl_lines="2" +{!../../docs_src/python_types/tutorial001.py!} +``` + +### এটি সম্পাদনা করুন + +এটি একটি খুব সাধারণ প্রোগ্রাম। + +কিন্তু এখন কল্পনা করুন যে আপনি এটি শুরু থেকে লিখছিলেন। + +এক পর্যায়ে আপনি ফাংশনের সংজ্ঞা শুরু করেছিলেন, আপনার প্যারামিটারগুলি প্রস্তুত ছিল... + +কিন্তু তারপর আপনাকে "সেই method কল করতে হবে যা প্রথম অক্ষরকে বড় হাতের অক্ষরে রূপান্তর করে"। + +এটা কি `upper` ছিল? নাকি `uppercase`? `first_uppercase`? `capitalize`? + +তারপর, আপনি পুরোনো প্রোগ্রামারের বন্ধু, এডিটর অটোকমপ্লিশনের সাহায্যে নেওয়ার চেষ্টা করেন। + +আপনি ফাংশনের প্রথম প্যারামিটার `first_name` টাইপ করেন, তারপর একটি ডট (`.`) টাইপ করেন এবং `Ctrl+Space` চাপেন অটোকমপ্লিশন ট্রিগার করার জন্য। + +কিন্তু, দুর্ভাগ্যবশত, আপনি কিছুই উপযোগী পান না: + + + +### টাইপ যোগ করুন + +আসুন আগের সংস্করণ থেকে একটি লাইন পরিবর্তন করি। + +আমরা ঠিক এই অংশটি পরিবর্তন করব অর্থাৎ ফাংশনের প্যারামিটারগুলি, এইগুলি: + +```Python + first_name, last_name +``` + +থেকে এইগুলি: + +```Python + first_name: str, last_name: str +``` + +ব্যাস। + +এগুলিই "টাইপ হিন্ট": + +```Python hl_lines="1" +{!../../docs_src/python_types/tutorial002.py!} +``` + +এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন: + +```Python + first_name="john", last_name="doe" +``` + +এটি একটি ভিন্ন জিনিস। + +আমরা সমান (`=`) নয়, কোলন (`:`) ব্যবহার করছি। + +এবং টাইপ হিন্ট যোগ করা সাধারণত তেমন কিছু পরিবর্তন করে না যা টাইপ হিন্ট ছাড়াই ঘটত। + +কিন্তু এখন, কল্পনা করুন আপনি আবার সেই ফাংশন তৈরির মাঝখানে আছেন, কিন্তু টাইপ হিন্ট সহ। + +একই পর্যায়ে, আপনি অটোকমপ্লিট ট্রিগার করতে `Ctrl+Space` চাপেন এবং আপনি দেখতে পান: + + + +এর সাথে, আপনি অপশনগুলি দেখে, স্ক্রল করতে পারেন, যতক্ষণ না আপনি এমন একটি অপশন খুঁজে পান যা কিছু মনে পরিয়ে দেয়: + + + +## আরও প্রেরণা + +এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে: + +```Python hl_lines="1" +{!../../docs_src/python_types/tutorial003.py!} +``` + +এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান: + + + +এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে: + +```Python hl_lines="2" +{!../../docs_src/python_types/tutorial004.py!} +``` + +## টাইপ ঘোষণা + +আপনি এতক্ষন টাইপ হিন্ট ঘোষণা করার মূল স্থানটি দেখে ফেলেছেন-- ফাংশন প্যারামিটার হিসেবে। + +সাধারণত এটি **FastAPI** এর ক্ষেত্রেও একই। + +### সিম্পল টাইপ + +আপনি `str` ছাড়াও সমস্ত স্ট্যান্ডার্ড পাইথন টাইপ ঘোষণা করতে পারেন। + +উদাহরণস্বরূপ, আপনি এগুলো ব্যবহার করতে পারেন: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../docs_src/python_types/tutorial005.py!} +``` + +### টাইপ প্যারামিটার সহ জেনেরিক টাইপ + +কিছু ডাটা স্ট্রাকচার অন্যান্য মান ধারণ করতে পারে, যেমন `dict`, `list`, `set` এবং `tuple`। এবং অভ্যন্তরীণ মানগুলোরও নিজেদের টাইপ থাকতে পারে। + +এই ধরনের টাইপগুলিকে বলা হয় "**জেনেরিক**" টাইপ এবং এগুলিকে তাদের অভ্যন্তরীণ টাইপগুলি সহ ঘোষণা করা সম্ভব। + +এই টাইপগুলি এবং অভ্যন্তরীণ টাইপগুলি ঘোষণা করতে, আপনি Python মডিউল `typing` ব্যবহার করতে পারেন। এটি বিশেষভাবে এই টাইপ হিন্টগুলি সমর্থন করার জন্য রয়েছে। + +#### Python এর নতুন সংস্করণ + +`typing` ব্যবহার করা সিনট্যাক্সটি Python 3.6 থেকে সর্বশেষ সংস্করণগুলি পর্যন্ত, অর্থাৎ Python 3.9, Python 3.10 ইত্যাদি সহ সকল সংস্করণের সাথে **সামঞ্জস্যপূর্ণ**। + +Python যত এগিয়ে যাচ্ছে, **নতুন সংস্করণগুলি** এই টাইপ অ্যানোটেশনগুলির জন্য তত উন্নত সাপোর্ট নিয়ে আসছে এবং অনেক ক্ষেত্রে আপনাকে টাইপ অ্যানোটেশন ঘোষণা করতে `typing` মডিউল ইম্পোর্ট এবং ব্যবহার করার প্রয়োজন হবে না। + +যদি আপনি আপনার প্রজেক্টের জন্য Python-এর আরও সাম্প্রতিক সংস্করণ নির্বাচন করতে পারেন, তাহলে আপনি সেই অতিরিক্ত সরলতা থেকে সুবিধা নিতে পারবেন। + +ডক্সে রয়েছে Python-এর প্রতিটি সংস্করণের সাথে সামঞ্জস্যপূর্ণ উদাহরণগুলি (যখন পার্থক্য আছে)। + +উদাহরণস্বরূপ, "**Python 3.6+**" মানে এটি Python 3.6 বা তার উপরে সামঞ্জস্যপূর্ণ (যার মধ্যে 3.7, 3.8, 3.9, 3.10, ইত্যাদি অন্তর্ভুক্ত)। এবং "**Python 3.9+**" মানে এটি Python 3.9 বা তার উপরে সামঞ্জস্যপূর্ণ (যার মধ্যে 3.10, ইত্যাদি অন্তর্ভুক্ত)। + +যদি আপনি Python-এর **সর্বশেষ সংস্করণগুলি ব্যবহার করতে পারেন**, তাহলে সর্বশেষ সংস্করণের জন্য উদাহরণগুলি ব্যবহার করুন, সেগুলি আপনাকে **সর্বোত্তম এবং সহজতম সিনট্যাক্স** প্রদান করবে, যেমন, "**Python 3.10+**"। + +#### লিস্ট + +উদাহরণস্বরূপ, একটি ভেরিয়েবলকে `str`-এর একটি `list` হিসেবে সংজ্ঞায়িত করা যাক। + +//// tab | Python 3.9+ + +ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। + +টাইপ হিসেবে, `list` ব্যবহার করুন। + +যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন: + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +`typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন: + +``` Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। + +টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন। + +যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন: + +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +//// + +/// info + +স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে। + +এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার। + +/// + +এর অর্থ হচ্ছে: "ভেরিয়েবল `items` একটি `list`, এবং এই লিস্টের প্রতিটি আইটেম একটি `str`।" + +/// tip + +যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন। + +/// + +এর মাধ্যমে, আপনার এডিটর লিস্ট থেকে আইটেম প্রসেস করার সময় সাপোর্ট প্রদান করতে পারবে: + + + +টাইপগুলি ছাড়া, এটি করা প্রায় অসম্ভব। + +লক্ষ্য করুন যে ভেরিয়েবল `item` হল `items` লিস্টের একটি এলিমেন্ট। + +তবুও, এডিটর জানে যে এটি একটি `str`, এবং তার জন্য সাপোর্ট প্রদান করে। + +#### টাপল এবং সেট + +আপনি `tuple` এবং `set` ঘোষণা করার জন্য একই প্রক্রিয়া অনুসরণ করবেন: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` + +//// + +এর মানে হল: + +* ভেরিয়েবল `items_t` হল একটি `tuple` যা ৩টি আইটেম ধারণ করে, একটি `int`, অন্য একটি `int`, এবং একটি `str`। +* ভেরিয়েবল `items_s` হল একটি `set`, এবং এর প্রতিটি আইটেম হল `bytes` টাইপের। + +#### ডিক্ট + +একটি `dict` সংজ্ঞায়িত করতে, আপনি ২টি টাইপ প্যারামিটার কমা দ্বারা পৃথক করে দেবেন। + +প্রথম টাইপ প্যারামিটারটি হল `dict`-এর কীগুলির জন্য। + +দ্বিতীয় টাইপ প্যারামিটারটি হল `dict`-এর মানগুলির জন্য: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// + +এর মানে হল: + +* ভেরিয়েবল `prices` হল একটি `dict`: + * এই `dict`-এর কীগুলি হল `str` টাইপের (ধরা যাক, প্রতিটি আইটেমের নাম)। + * এই `dict`-এর মানগুলি হল `float` টাইপের (ধরা যাক, প্রতিটি আইটেমের দাম)। + +#### ইউনিয়ন + +আপনি একটি ভেরিয়েবলকে এমনভাবে ঘোষণা করতে পারেন যেন তা **একাধিক টাইপের** হয়, উদাহরণস্বরূপ, একটি `int` অথবা `str`। + +Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অন্তর্ভুক্ত) আপনি `typing` থেকে `Union` টাইপ ব্যবহার করতে পারেন এবং স্কোয়ার ব্র্যাকেটের মধ্যে গ্রহণযোগ্য টাইপগুলি রাখতে পারেন। + +Python 3.10-এ একটি **নতুন সিনট্যাক্স** আছে যেখানে আপনি সম্ভাব্য টাইপগুলিকে একটি ভার্টিকাল বার (`|`) দ্বারা পৃথক করতে পারেন। + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +উভয় ক্ষেত্রেই এর মানে হল যে `item` হতে পারে একটি `int` অথবা `str`। + +#### সম্ভবত `None` + +আপনি এমনভাবে ঘোষণা করতে পারেন যে একটি মান হতে পারে এক টাইপের, যেমন `str`, আবার এটি `None`-ও হতে পারে। + +Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অনতর্ভুক্ত) আপনি `typing` মডিউল থেকে `Optional` ইমপোর্ট করে এটি ঘোষণা এবং ব্যবহার করতে পারেন। + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009.py!} +``` + +`Optional[str]` ব্যবহার করা মানে হল শুধু `str` নয়, এটি হতে পারে `None`-ও, যা আপনার এডিটরকে সেই ত্রুটিগুলি শনাক্ত করতে সাহায্য করবে যেখানে আপনি ধরে নিচ্ছেন যে একটি মান সবসময় `str` হবে, অথচ এটি `None`-ও হতে পারেও। + +`Optional[Something]` মূলত `Union[Something, None]`-এর একটি শর্টকাট, এবং তারা সমতুল্য। + +এর মানে হল, Python 3.10-এ, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে `Something | None` ব্যবহার করতে পারেন: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ বিকল্প + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### `Union` বা `Optional` ব্যবহার + +যদি আপনি Python 3.10-এর নীচের সংস্করণ ব্যবহার করেন, তবে এখানে আমার খুবই **ব্যক্তিগত** দৃষ্টিভঙ্গি থেকে একটি টিপস: + +* 🚨 `Optional[SomeType]` ব্যবহার এড়িয়ে চলুন। +* এর পরিবর্তে ✨ **`Union[SomeType, None]` ব্যবহার করুন** ✨। + +উভয়ই সমতুল্য এবং মূলে একই, কিন্তু আমি `Union`-এর পক্ষে সুপারিশ করব কারণ "**অপশনাল**" শব্দটি মনে হতে পারে যে মানটি ঐচ্ছিক,অথচ এটি আসলে মানে "এটি হতে পারে `None`", এমনকি যদি এটি ঐচ্ছিক না হয়েও আবশ্যিক হয়। + +আমি মনে করি `Union[SomeType, None]` এর অর্থ আরও স্পষ্টভাবে প্রকাশ করে। + +এটি কেবল শব্দ এবং নামের ব্যাপার। কিন্তু সেই শব্দগুলি আপনি এবং আপনার সহকর্মীরা কোড সম্পর্কে কীভাবে চিন্তা করেন তা প্রভাবিত করতে পারে। + +একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন: + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009c.py!} +``` + +`name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না: + +```Python +say_hi() # ওহ না, এটি একটি ত্রুটি নিক্ষেপ করবে! 😱 +``` + +`name` প্যারামিটারটি **এখনও আবশ্যিক** (নন-অপশনাল) কারণ এটির কোনো ডিফল্ট মান নেই। তবুও, `name` এর মান হিসেবে `None` গ্রহণযোগ্য: + +```Python +say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 +``` + +সুখবর হল, একবার আপনি Python 3.10 ব্যবহার করা শুরু করলে, আপনাকে এগুলোর ব্যাপারে আর চিন্তা করতে হবে না, যেহুতু আপনি | ব্যবহার করেই ইউনিয়ন ঘোষণা করতে পারবেন: + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009c_py310.py!} +``` + +এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎 + +#### জেনেরিক টাইপস + +স্কোয়ার ব্র্যাকেটে টাইপ প্যারামিটার নেওয়া এই টাইপগুলিকে **জেনেরিক টাইপ** বা **জেনেরিকস** বলা হয়, যেমন: + +//// tab | Python 3.10+ + +আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): + +* `list` +* `tuple` +* `set` +* `dict` + +এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: + +* `Union` +* `Optional` (Python 3.8 এর মতোই) +* ...এবং অন্যান্য। + +Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে ভার্টিকাল বার (`|`) ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ। + +//// + +//// tab | Python 3.9+ + +আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): + +* `list` +* `tuple` +* `set` +* `dict` + +এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: + +* `Union` +* `Optional` +* ...এবং অন্যান্য। + +//// + +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...এবং অন্যান্য। + +//// + +### ক্লাস হিসেবে টাইপস + +আপনি একটি ভেরিয়েবলের টাইপ হিসেবে একটি ক্লাস ঘোষণা করতে পারেন। + +ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে: + +```Python hl_lines="1-3" +{!../../docs_src/python_types/tutorial010.py!} +``` + +তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন: + +```Python hl_lines="6" +{!../../docs_src/python_types/tutorial010.py!} +``` + +এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন: + + + +লক্ষ্য করুন যে এর মানে হল "`one_person` হল ক্লাস `Person`-এর একটি **ইন্সট্যান্স**।" + +এর মানে এটি নয় যে "`one_person` হল **ক্লাস** যাকে বলা হয় `Person`।" + +## Pydantic মডেল + +[Pydantic](https://docs.pydantic.dev/) হল একটি Python লাইব্রেরি যা ডাটা ভ্যালিডেশন সম্পাদন করে। + +আপনি ডাটার "আকার" এট্রিবিউট সহ ক্লাস হিসেবে ঘোষণা করেন। + +এবং প্রতিটি এট্রিবিউট এর একটি টাইপ থাকে। + +তারপর আপনি যদি কিছু মান দিয়ে সেই ক্লাসের একটি ইন্সট্যান্স তৈরি করেন-- এটি মানগুলিকে ভ্যালিডেট করবে, প্রয়োজন অনুযায়ী তাদেরকে উপযুক্ত টাইপে রূপান্তর করবে এবং আপনাকে সমস্ত ডাটা সহ একটি অবজেক্ট প্রদান করবে। + +এবং আপনি সেই ফলাফল অবজেক্টের সাথে এডিটর সাপোর্ট পাবেন। + +অফিসিয়াল Pydantic ডক্স থেকে একটি উদাহরণ: + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info + +[Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)। + +/// + +**FastAPI** মূলত Pydantic-এর উপর নির্মিত। + +আপনি এই সমস্ত কিছুর অনেক বাস্তবসম্মত উদাহরণ পাবেন [টিউটোরিয়াল - ইউজার গাইডে](https://fastapi.tiangolo.com/tutorial/)। + +/// tip + +যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন। + +/// + +## মেটাডাটা অ্যানোটেশন সহ টাইপ হিন্টস + +Python-এ এমন একটি ফিচার আছে যা `Annotated` ব্যবহার করে এই টাইপ হিন্টগুলিতে **অতিরিক্ত মেটাডাটা** রাখতে দেয়। + +//// tab | Python 3.9+ + +Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন। + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন। + +এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে। + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` + +//// + +Python নিজে এই `Annotated` দিয়ে কিছুই করে না। এবং এডিটর এবং অন্যান্য টুলগুলির জন্য, টাইপটি এখনও `str`। + +কিন্তু আপনি এই `Annotated` এর মধ্যকার জায়গাটির মধ্যে **FastAPI**-এ কীভাবে আপনার অ্যাপ্লিকেশন আচরণ করুক তা সম্পর্কে অতিরিক্ত মেটাডাটা প্রদান করার জন্য ব্যবহার করতে পারেন। + +মনে রাখার গুরুত্বপূর্ণ বিষয় হল যে **প্রথম *টাইপ প্যারামিটার*** আপনি `Annotated`-এ পাস করেন সেটি হল **আসল টাইপ**। বাকি শুধুমাত্র অন্যান্য টুলগুলির জন্য মেটাডাটা। + +এখন আপনার কেবল জানা প্রয়োজন যে `Annotated` বিদ্যমান, এবং এটি স্ট্যান্ডার্ড Python। 😎 + +পরবর্তীতে আপনি দেখবেন এটি কতটা **শক্তিশালী** হতে পারে। + +/// tip + +এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨ + +এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀 + +/// + +## **FastAPI**-এ টাইপ হিন্টস + +**FastAPI** এই টাইপ হিন্টগুলি ব্যবহার করে বেশ কিছু জিনিস করে। + +**FastAPI**-এ আপনি টাইপ হিন্টগুলি সহ প্যারামিটার ঘোষণা করেন এবং আপনি পান: + +* **এডিটর সাপোর্ট**। +* **টাইপচেক**। + +...এবং **FastAPI** একই ঘোষণাগুলি ব্যবহার করে: + +* **রিকুইরেমেন্টস সংজ্ঞায়িত করে**: রিকোয়েস্ট পাথ প্যারামিটার, কুয়েরি প্যারামিটার, হেডার, বডি, ডিপেন্ডেন্সিস, ইত্যাদি থেকে। +* **ডেটা রূপান্তর করে**: রিকোয়েস্ট থেকে প্রয়োজনীয় টাইপে ডেটা। +* **ডেটা যাচাই করে**: প্রতিটি রিকোয়েস্ট থেকে আসা ডেটা: + * যখন ডেটা অবৈধ হয় তখন **স্বয়ংক্রিয় ত্রুটি** গ্রাহকের কাছে ফেরত পাঠানো। +* **API ডকুমেন্টেশন তৈরি করে**: OpenAPI ব্যবহার করে: + * যা স্বয়ংক্রিয় ইন্টার‌্যাক্টিভ ডকুমেন্টেশন ইউজার ইন্টারফেস দ্বারা ব্যবহৃত হয়। + +এই সব কিছু আপনার কাছে অস্পষ্ট মনে হতে পারে। চিন্তা করবেন না। আপনি [টিউটোরিয়াল - ইউজার গাইড](https://fastapi.tiangolo.com/tutorial/) এ এই সব কিছু প্র্যাকটিসে দেখতে পাবেন। + +গুরুত্বপূর্ণ বিষয় হল, আপনি যদি স্ট্যান্ডার্ড Python টাইপগুলি ব্যবহার করেন, তবে আরও বেশি ক্লাস, ডেকোরেটর ইত্যাদি যোগ না করেই একই স্থানে **FastAPI** আপনার অনেক কাজ করে দিবে। + +/// info + +যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে। + +/// diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md index 2bfcfab33..bf38d9795 100644 --- a/docs/de/docs/advanced/additional-responses.md +++ b/docs/de/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Zusätzliche Responses in OpenAPI -!!! warning "Achtung" - Dies ist ein eher fortgeschrittenes Thema. +/// warning | Achtung - Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht. +Dies ist ein eher fortgeschrittenes Thema. + +Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht. + +/// Sie können zusätzliche Responses mit zusätzlichen Statuscodes, Medientypen, Beschreibungen, usw. deklarieren. @@ -23,24 +26,28 @@ Jedes dieser Response-`dict`s kann einen Schlüssel `model` haben, welcher ein P Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydantic-Modell `Message` zu deklarieren, können Sie schreiben: -```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note | Hinweis + +Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. + +/// + +/// info -!!! note "Hinweis" - Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. +Der `model`-Schlüssel ist nicht Teil von OpenAPI. -!!! info - Der `model`-Schlüssel ist nicht Teil von OpenAPI. +**FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein. - **FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein. +Die richtige Stelle ist: - Die richtige Stelle ist: +* Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält: + * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält: + * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle. + * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw. - * Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält: - * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält: - * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle. - * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw. +/// Die generierten Responses in der OpenAPI für diese *Pfadoperation* lauten: @@ -168,17 +175,21 @@ Sie können denselben `responses`-Parameter verwenden, um verschiedene Medientyp Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen und damit deklarieren, dass Ihre *Pfadoperation* ein JSON-Objekt (mit dem Medientyp `application/json`) oder ein PNG-Bild zurückgeben kann: -```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note | Hinweis + +Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. + +/// -!!! note "Hinweis" - Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. +/// info -!!! info - Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`). +Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`). - Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt. +Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt. + +/// ## Informationen kombinieren @@ -192,9 +203,7 @@ Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, d Und eine Response mit dem Statuscode `200`, die Ihr `response_model` verwendet, aber ein benutzerdefiniertes Beispiel (`example`) enthält: -```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt: @@ -228,9 +237,7 @@ Mit dieser Technik können Sie einige vordefinierte Responses in Ihren *Pfadoper Zum Beispiel: -```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## Weitere Informationen zu OpenAPI-Responses diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md index e9de267cf..50702e7e6 100644 --- a/docs/de/docs/advanced/additional-status-codes.md +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -14,53 +14,75 @@ Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4 25" +{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4 25" +{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4 26" - {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 26" +{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} +``` - ```Python hl_lines="2 23" - {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | Tipp - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -!!! warning "Achtung" - Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben. +/// - Sie wird nicht mit einem Modell usw. serialisiert. +```Python hl_lines="2 23" +{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} +``` - Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden). +//// -!!! note "Technische Details" - Sie können auch `from starlette.responses import JSONResponse` verwenden. +//// tab | Python 3.8+ nicht annotiert - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`. +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="4 25" +{!> ../../docs_src/additional_status_codes/tutorial001.py!} +``` + +//// + +/// warning | Achtung + +Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben. + +Sie wird nicht mit einem Modell usw. serialisiert. + +Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden). + +/// + +/// note | Technische Details + +Sie können auch `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`. + +/// ## OpenAPI- und API-Dokumentation diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md index 33b93b332..80cbf1fd3 100644 --- a/docs/de/docs/advanced/advanced-dependencies.md +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -18,26 +18,35 @@ Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser Dazu deklarieren wir eine Methode `__call__`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | Tipp - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben. @@ -45,26 +54,35 @@ In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zus Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="8" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden. @@ -72,26 +90,35 @@ In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmer Wir könnten eine Instanz dieser Klasse erstellen mit: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | Tipp - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`. @@ -107,32 +134,44 @@ checker(q="somequery") ... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="22" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="21" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` +```Python hl_lines="21" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="20" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` -=== "Python 3.8+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | Tipp - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. -!!! tip "Tipp" - Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. +Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert. - Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert. +In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden. - In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden. +Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren. - Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren. +/// diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index 2e2c22210..c118e588f 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -33,13 +33,13 @@ Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größ Die Datei `main.py` hätte als Inhalt: ```Python -{!../../../docs_src/async_tests/main.py!} +{!../../docs_src/async_tests/main.py!} ``` Die Datei `test_main.py` hätte die Tests für `main.py`, das könnte jetzt so aussehen: ```Python -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` ## Es ausführen @@ -60,18 +60,17 @@ $ pytest Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynchron aufgerufen werden soll: -```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip | Tipp + +Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. -!!! tip "Tipp" - Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. +/// Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. -```Python hl_lines="9-10" -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} Das ist das Äquivalent zu: @@ -81,15 +80,24 @@ response = client.get('/') ... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen. -!!! tip "Tipp" - Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. +/// tip | Tipp + +Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. -!!! warning "Achtung" - Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan. +/// + +/// warning | Achtung + +Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan. + +/// ## Andere asynchrone Funktionsaufrufe Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden. -!!! tip "Tipp" - Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback. +/// tip | Tipp + +Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback. + +/// diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md index ad0a92e28..9da18a626 100644 --- a/docs/de/docs/advanced/behind-a-proxy.md +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -19,7 +19,7 @@ In diesem Fall würde der ursprüngliche Pfad `/app` tatsächlich unter `/api/v1 Auch wenn Ihr gesamter Code unter der Annahme geschrieben ist, dass es nur `/app` gibt. ```Python hl_lines="6" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` Und der Proxy würde das **Pfadpräfix** on-the-fly **"entfernen**", bevor er die Anfrage an Uvicorn übermittelt, dafür sorgend, dass Ihre Anwendung davon überzeugt ist, dass sie unter `/app` bereitgestellt wird, sodass Sie nicht Ihren gesamten Code dahingehend aktualisieren müssen, das Präfix `/api/v1` zu verwenden. @@ -43,8 +43,11 @@ browser --> proxy proxy --> server ``` -!!! tip "Tipp" - Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. +/// tip | Tipp + +Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. + +/// Die Benutzeroberfläche der Dokumentation würde benötigen, dass das OpenAPI-Schema deklariert, dass sich dieser API-`server` unter `/api/v1` (hinter dem Proxy) befindet. Zum Beispiel: @@ -81,10 +84,13 @@ $ uvicorn main:app --root-path /api/v1 Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`. -!!! note "Technische Details" - Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. +/// note | Technische Details + +Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. + +Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit. - Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit. +/// ### Überprüfen des aktuellen `root_path` @@ -93,7 +99,7 @@ Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein. ```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` Wenn Sie Uvicorn dann starten mit: @@ -122,7 +128,7 @@ wäre die Response etwa: Falls Sie keine Möglichkeit haben, eine Kommandozeilenoption wie `--root-path` oder ähnlich zu übergeben, können Sie als Alternative beim Erstellen Ihrer FastAPI-Anwendung den Parameter `root_path` setzen: ```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} +{!../../docs_src/behind_a_proxy/tutorial002.py!} ``` Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn. @@ -172,8 +178,11 @@ Dann erstellen Sie eine Datei `traefik.toml` mit: Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden. -!!! tip "Tipp" - Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. +/// tip | Tipp + +Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. + +/// Erstellen Sie nun die andere Datei `routes.toml`: @@ -239,8 +248,11 @@ Wenn Sie nun zur URL mit dem Port für Uvicorn gehen: http://127.0.0.1:9999/api/v1/app. @@ -283,8 +295,11 @@ Dies liegt daran, dass FastAPI diesen `root_path` verwendet, um den Default-`ser ## Zusätzliche Server -!!! warning "Achtung" - Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne. +/// warning | Achtung + +Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne. + +/// Standardmäßig erstellt **FastAPI** einen `server` im OpenAPI-Schema mit der URL für den `root_path`. @@ -295,7 +310,7 @@ Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es Zum Beispiel: ```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} +{!../../docs_src/behind_a_proxy/tutorial003.py!} ``` Erzeugt ein OpenAPI-Schema, wie: @@ -323,22 +338,28 @@ Erzeugt ein OpenAPI-Schema, wie: } ``` -!!! tip "Tipp" - Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt. +/// tip | Tipp + +Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt. + +/// In der Dokumentationsoberfläche unter http://127.0.0.1:9999/api/v1/docs würde es so aussehen: -!!! tip "Tipp" - Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. +/// tip | Tipp + +Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. + +/// ### Den automatischen Server von `root_path` deaktivieren Wenn Sie nicht möchten, dass **FastAPI** einen automatischen Server inkludiert, welcher `root_path` verwendet, können Sie den Parameter `root_path_in_servers=False` verwenden: ```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} +{!../../docs_src/behind_a_proxy/tutorial004.py!} ``` Dann wird er nicht in das OpenAPI-Schema aufgenommen. diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md index 68c037ad7..7738bfca4 100644 --- a/docs/de/docs/advanced/custom-response.md +++ b/docs/de/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in die Und wenn diese `Response` einen JSON-Medientyp (`application/json`) hat, wie es bei `JSONResponse` und `UJSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic `response_model` konvertiert (und gefiltert), das Sie im *Pfadoperation-Dekorator* deklariert haben. -!!! note "Hinweis" - Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation. +/// note | Hinweis + +Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation. + +/// ## `ORJSONResponse` verwenden @@ -28,18 +31,24 @@ Das liegt daran, dass FastAPI standardmäßig jedes enthaltene Element überprü Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSON serialisierbar** ist, können Sie ihn direkt an die Response-Klasse übergeben und die zusätzliche Arbeit vermeiden, die FastAPI hätte, indem es Ihren zurückgegebenen Inhalt durch den `jsonable_encoder` leitet, bevor es ihn an die Response-Klasse übergibt. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info - Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. +/// info + +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. + +/// - In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt. +/// tip | Tipp - Und er wird als solcher in OpenAPI dokumentiert. +Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette. -!!! tip "Tipp" - Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette. +/// ## HTML-Response @@ -49,15 +58,18 @@ Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie ` * Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` -!!! info - Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. +/// info - In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt. +Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. - Und er wird als solcher in OpenAPI dokumentiert. +In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt. + +Und er wird als solcher in OpenAPI dokumentiert. + +/// ### Eine `Response` zurückgeben @@ -66,14 +78,20 @@ Wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so aussehen: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning "Achtung" - Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar. +/// warning | Achtung + +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 -!!! info - Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben. +Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben. + +/// ### In OpenAPI dokumentieren und `Response` überschreiben @@ -86,7 +104,7 @@ Die `response_class` wird dann nur zur Dokumentation der OpenAPI-Pfadoperation* Es könnte zum Beispiel so etwas sein: ```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` In diesem Beispiel generiert die Funktion `generate_html_response()` bereits eine `Response` und gibt sie zurück, anstatt das HTML in einem `str` zurückzugeben. @@ -103,10 +121,13 @@ Hier sind einige der verfügbaren Responses. Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen. -!!! note "Technische Details" - Sie können auch `from starlette.responses import HTMLResponse` verwenden. +/// note | Technische Details + +Sie können auch `from starlette.responses import HTMLResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +/// ### `Response` @@ -124,7 +145,7 @@ Sie akzeptiert die folgenden Parameter: FastAPI (eigentlich Starlette) fügt automatisch einen Content-Length-Header ein. Außerdem wird es einen Content-Type-Header einfügen, der auf dem media_type basiert, und für Texttypen einen Zeichensatz (charset) anfügen. ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -136,7 +157,7 @@ Nimmt Text oder Bytes entgegen und gibt eine HTML-Response zurück, wie Sie oben Nimmt Text oder Bytes entgegen und gibt eine Plain-Text-Response zurück. ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -153,15 +174,21 @@ Eine schnelle alternative JSON-Response mit `ujson`. -!!! warning "Achtung" - `ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung. +/// warning | Achtung + +`ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung. + +/// ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} +{!../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip "Tipp" - Möglicherweise ist `ORJSONResponse` eine schnellere Alternative. +/// tip | Tipp + +Möglicherweise ist `ORJSONResponse` eine schnellere Alternative. + +/// ### `RedirectResponse` @@ -170,7 +197,7 @@ Gibt eine HTTP-Weiterleitung (HTTP-Redirect) zurück. Verwendet standardmäßig Sie können eine `RedirectResponse` direkt zurückgeben: ```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} +{!../../docs_src/custom_response/tutorial006.py!} ``` --- @@ -179,7 +206,7 @@ Oder Sie können sie im Parameter `response_class` verwenden: ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006b.py!} +{!../../docs_src/custom_response/tutorial006b.py!} ``` Wenn Sie das tun, können Sie die URL direkt von Ihrer *Pfadoperation*-Funktion zurückgeben. @@ -191,7 +218,7 @@ In diesem Fall ist der verwendete `status_code` der Standardcode für die `Redir Sie können den Parameter `status_code` auch in Kombination mit dem Parameter `response_class` verwenden: ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006c.py!} +{!../../docs_src/custom_response/tutorial006c.py!} ``` ### `StreamingResponse` @@ -199,7 +226,7 @@ Sie können den Parameter `status_code` auch in Kombination mit dem Parameter `r Nimmt einen asynchronen Generator oder einen normalen Generator/Iterator und streamt den Responsebody. ```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} +{!../../docs_src/custom_response/tutorial007.py!} ``` #### Verwendung von `StreamingResponse` mit dateiähnlichen Objekten @@ -211,7 +238,7 @@ Auf diese Weise müssen Sie nicht alles zuerst in den Arbeitsspeicher lesen und Das umfasst viele Bibliotheken zur Interaktion mit Cloud-Speicher, Videoverarbeitung und anderen. ```{ .python .annotate hl_lines="2 10-12 14" } -{!../../../docs_src/custom_response/tutorial008.py!} +{!../../docs_src/custom_response/tutorial008.py!} ``` 1. Das ist die Generatorfunktion. Es handelt sich um eine „Generatorfunktion“, da sie `yield`-Anweisungen enthält. @@ -222,8 +249,11 @@ Das umfasst viele Bibliotheken zur Interaktion mit Cloud-Speicher, Videoverarbei Auf diese Weise können wir das Ganze in einen `with`-Block einfügen und so sicherstellen, dass das dateiartige Objekt nach Abschluss geschlossen wird. -!!! tip "Tipp" - Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren. +/// tip | Tipp + +Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren. + +/// ### `FileResponse` @@ -239,13 +269,13 @@ Nimmt zur Instanziierung einen anderen Satz von Argumenten entgegen als die ande Datei-Responses enthalten die entsprechenden `Content-Length`-, `Last-Modified`- und `ETag`-Header. ```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} +{!../../docs_src/custom_response/tutorial009.py!} ``` Sie können auch den Parameter `response_class` verwenden: ```Python hl_lines="2 8 10" -{!../../../docs_src/custom_response/tutorial009b.py!} +{!../../docs_src/custom_response/tutorial009b.py!} ``` In diesem Fall können Sie den Dateipfad direkt von Ihrer *Pfadoperation*-Funktion zurückgeben. @@ -261,7 +291,7 @@ Sie möchten etwa, dass Ihre Response eingerücktes und formatiertes JSON zurüc Sie könnten eine `CustomORJSONResponse` erstellen. Das Wichtigste, was Sie tun müssen, ist, eine `Response.render(content)`-Methode zu erstellen, die den Inhalt als `bytes` zurückgibt: ```Python hl_lines="9-14 17" -{!../../../docs_src/custom_response/tutorial009c.py!} +{!../../docs_src/custom_response/tutorial009c.py!} ``` Statt: @@ -289,11 +319,14 @@ Der Parameter, der das definiert, ist `default_response_class`. Im folgenden Beispiel verwendet **FastAPI** standardmäßig `ORJSONResponse` in allen *Pfadoperationen*, anstelle von `JSONResponse`. ```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} +{!../../docs_src/custom_response/tutorial010.py!} ``` -!!! tip "Tipp" - Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher. +/// tip | Tipp + +Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher. + +/// ## Zusätzliche Dokumentation diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md index c78a6d3dd..8e537c639 100644 --- a/docs/de/docs/advanced/dataclasses.md +++ b/docs/de/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI basiert auf **Pydantic** und ich habe Ihnen gezeigt, wie Sie Pydantic-Mo Aber FastAPI unterstützt auf die gleiche Weise auch die Verwendung von `dataclasses`: -```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} Das ist dank **Pydantic** ebenfalls möglich, da es `dataclasses` intern unterstützt. @@ -20,20 +18,21 @@ Und natürlich wird das gleiche unterstützt: Das funktioniert genauso wie mit Pydantic-Modellen. Und tatsächlich wird es unter der Haube mittels Pydantic auf die gleiche Weise bewerkstelligt. -!!! info - Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können. +/// info - Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden. +Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können. - Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓 +Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden. + +Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓 + +/// ## Datenklassen als `response_model` Sie können `dataclasses` auch im Parameter `response_model` verwenden: -```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert. @@ -49,9 +48,7 @@ In einigen Fällen müssen Sie möglicherweise immer noch Pydantics Version von In diesem Fall können Sie einfach die Standard-`dataclasses` durch `pydantic.dataclasses` ersetzen, was einen direkten Ersatz darstellt: -```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} -``` +{* ../../docs_src/dataclasses/tutorial003.py hl[1,5,8:11,14:17,23:25,28] *} 1. Wir importieren `field` weiterhin von Standard-`dataclasses`. diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md index e29f61ab9..cae53091c 100644 --- a/docs/de/docs/advanced/events.md +++ b/docs/de/docs/advanced/events.md @@ -31,24 +31,27 @@ Beginnen wir mit einem Beispiel und sehen es uns dann im Detail an. Wir erstellen eine asynchrone Funktion `lifespan()` mit `yield` wie folgt: ```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Hier simulieren wir das langsame *Hochfahren*, das Laden des Modells, indem wir die (Fake-)Modellfunktion vor dem `yield` in das Dictionary mit Modellen für maschinelles Lernen einfügen. Dieser Code wird ausgeführt, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**, während des *Hochfahrens*. Und dann, direkt nach dem `yield`, entladen wir das Modell. Dieser Code wird unmittelbar vor dem *Herunterfahren* ausgeführt, **nachdem** die Anwendung **die Bearbeitung von Requests abgeschlossen hat**. Dadurch könnten beispielsweise Ressourcen wie Arbeitsspeicher oder eine GPU freigegeben werden. -!!! tip "Tipp" - Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**. +/// tip | Tipp - Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷 +Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**. + +Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷 + +/// ### Lifespan-Funktion Das Erste, was auffällt, ist, dass wir eine asynchrone Funktion mit `yield` definieren. Das ist sehr ähnlich zu Abhängigkeiten mit `yield`. ```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Der erste Teil der Funktion, vor dem `yield`, wird ausgeführt **bevor** die Anwendung startet. @@ -62,7 +65,7 @@ Wie Sie sehen, ist die Funktion mit einem `@asynccontextmanager` versehen. Dadurch wird die Funktion in einen sogenannten „**asynchronen Kontextmanager**“ umgewandelt. ```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Ein **Kontextmanager** in Python ist etwas, das Sie in einer `with`-Anweisung verwenden können, zum Beispiel kann `open()` als Kontextmanager verwendet werden: @@ -86,15 +89,18 @@ In unserem obigen Codebeispiel verwenden wir ihn nicht direkt, sondern übergebe Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontextmanager**, wir können ihm also unseren neuen asynchronen Kontextmanager `lifespan` übergeben. ```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` ## Alternative Events (deprecated) -!!! warning "Achtung" - Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides. +/// warning | Achtung + +Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides. - Sie können diesen Teil wahrscheinlich überspringen. +Sie können diesen Teil wahrscheinlich überspringen. + +/// Es gibt eine alternative Möglichkeit, diese Logik zu definieren, sodass sie beim *Hochfahren* und beim *Herunterfahren* ausgeführt wird. @@ -107,7 +113,7 @@ Diese Funktionen können mit `async def` oder normalem `def` deklariert werden. Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `startup`: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` In diesem Fall initialisiert die Eventhandler-Funktion `startup` die „Datenbank“ der Items (nur ein `dict`) mit einigen Werten. @@ -121,22 +127,28 @@ Und Ihre Anwendung empfängt erst dann Anfragen, wenn alle `startup`-Eventhandle Um eine Funktion hinzuzufügen, die beim Herunterfahren der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `shutdown`: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`. -!!! info - In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben. +/// info + +In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben. -!!! tip "Tipp" - Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert. +/// - Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden. +/// tip | Tipp - Aber `open()` verwendet nicht `async` und `await`. +Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert. - Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`. +Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden. + +Aber `open()` verwendet nicht `async` und `await`. + +Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`. + +/// ### `startup` und `shutdown` zusammen @@ -152,10 +164,13 @@ Nur ein technisches Detail für die neugierigen Nerds. 🤓 In der technischen ASGI-Spezifikation ist dies Teil des Lifespan Protokolls und definiert Events namens `startup` und `shutdown`. -!!! info - Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in Starlettes Lifespan-Dokumentation. +/// info + +Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in Starlettes Lifespan-Dokumentation. + +Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann. - Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann. +/// ## Unteranwendungen diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md index 2fcba5956..8f71e5419 100644 --- a/docs/de/docs/advanced/generate-clients.md +++ b/docs/de/docs/advanced/generate-clients.md @@ -10,7 +10,7 @@ Es gibt viele Tools zum Generieren von Clients aus **OpenAPI**. Ein gängiges Tool ist OpenAPI Generator. -Wenn Sie ein **Frontend** erstellen, ist openapi-typescript-codegen eine sehr interessante Alternative. +Wenn Sie ein **Frontend** erstellen, ist openapi-ts eine sehr interessante Alternative. ## Client- und SDK-Generatoren – Sponsor @@ -20,7 +20,7 @@ Einige von diesen ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponse Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇 -Beispielsweise könnten Sie Speakeasy ausprobieren. +Beispielsweise könnten Sie Speakeasy ausprobieren. Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und die Sie online suchen und finden können. 🤓 @@ -28,17 +28,21 @@ Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und d Beginnen wir mit einer einfachen FastAPI-Anwendung: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +```Python hl_lines="7-9 12-13 16-17 21" +{!> ../../docs_src/generate_clients/tutorial001_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +```Python hl_lines="9-11 14-15 18 19 23" +{!> ../../docs_src/generate_clients/tutorial001.py!} +``` + +//// Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-Payload verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden. @@ -58,14 +62,14 @@ Und dieselben Informationen aus den Modellen, die in OpenAPI enthalten sind, kö Nachdem wir nun die Anwendung mit den Modellen haben, können wir den Client-Code für das Frontend generieren. -#### `openapi-typescript-codegen` installieren +#### `openapi-ts` installieren -Sie können `openapi-typescript-codegen` in Ihrem Frontend-Code installieren mit: +Sie können `openapi-ts` in Ihrem Frontend-Code installieren mit:
```console -$ npm install openapi-typescript-codegen --save-dev +$ npm install @hey-api/openapi-ts --save-dev ---> 100% ``` @@ -74,7 +78,7 @@ $ npm install openapi-typescript-codegen --save-dev #### Client-Code generieren -Um den Client-Code zu generieren, können Sie das Kommandozeilentool `openapi` verwenden, das soeben installiert wurde. +Um den Client-Code zu generieren, können Sie das Kommandozeilentool `openapi-ts` verwenden, das soeben installiert wurde. Da es im lokalen Projekt installiert ist, könnten Sie diesen Befehl wahrscheinlich nicht direkt aufrufen, sondern würden ihn in Ihre Datei `package.json` einfügen. @@ -87,12 +91,12 @@ Diese könnte so aussehen: "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -106,7 +110,7 @@ Nachdem Sie das NPM-Skript `generate-client` dort stehen haben, können Sie es a $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios ```
@@ -123,8 +127,11 @@ Sie erhalten außerdem automatische Vervollständigung für die zu sendende Payl -!!! tip "Tipp" - Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden. +/// tip | Tipp + +Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden. + +/// Sie erhalten Inline-Fehlerberichte für die von Ihnen gesendeten Daten: @@ -140,17 +147,21 @@ In vielen Fällen wird Ihre FastAPI-Anwendung größer sein und Sie werden wahrs Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="21 26 34" +{!> ../../docs_src/generate_clients/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="23 28 36" +{!> ../../docs_src/generate_clients/tutorial002.py!} +``` - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +//// ### Einen TypeScript-Client mit Tags generieren @@ -197,17 +208,21 @@ Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6-7 10" +{!> ../../docs_src/generate_clients/tutorial003_py39.py!} +``` - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="8-9 12" +{!> ../../docs_src/generate_clients/tutorial003.py!} +``` - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +//// ### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren @@ -229,17 +244,21 @@ Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt v Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**: -=== "Python" +//// tab | Python - ```Python - {!> ../../../docs_src/generate_clients/tutorial004.py!} - ``` +```Python +{!> ../../docs_src/generate_clients/tutorial004.py!} +``` + +//// -=== "Node.js" +//// tab | Node.js + +```Javascript +{!> ../../docs_src/generate_clients/tutorial004.js!} +``` - ```Javascript - {!> ../../../docs_src/generate_clients/tutorial004.js!} - ``` +//// Damit würden die Operation-IDs von Dingen wie `items-get_items` in `get_items` umbenannt, sodass der Client-Generator einfachere Methodennamen generieren kann. @@ -254,12 +273,12 @@ Da das Endergebnis nun in einer Datei `openapi.json` vorliegt, würden Sie die ` "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } diff --git a/docs/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md index 048e31e06..d93cd5fe8 100644 --- a/docs/de/docs/advanced/index.md +++ b/docs/de/docs/advanced/index.md @@ -6,10 +6,13 @@ Das Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link t In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen. -!!! tip "Tipp" - Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. +/// tip | Tipp - Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. +Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + +Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +/// ## Lesen Sie zuerst das Tutorial diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index 2c4e8542a..d2130c9b7 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -43,10 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** enthält mehrere Middlewares für gängige Anwendungsfälle. Wir werden als Nächstes sehen, wie man sie verwendet. -!!! note "Technische Details" - Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. +/// note | Technische Details - **FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette. +Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. + +**FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette. + +/// ## `HTTPSRedirectMiddleware` @@ -55,7 +58,7 @@ Erzwingt, dass alle eingehenden Requests entweder `https` oder `wss` sein müsse Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Schema umgeleitet. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} +{!../../docs_src/advanced_middleware/tutorial001.py!} ``` ## `TrustedHostMiddleware` @@ -63,7 +66,7 @@ Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Erzwingt, dass alle eingehenden Requests einen korrekt gesetzten `Host`-Header haben, um sich vor HTTP-Host-Header-Angriffen zu schützen. ```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} +{!../../docs_src/advanced_middleware/tutorial002.py!} ``` Die folgenden Argumente werden unterstützt: @@ -79,7 +82,7 @@ Verarbeitet GZip-Responses für alle Requests, die `"gzip"` im `Accept-Encoding` Diese Middleware verarbeitet sowohl Standard- als auch Streaming-Responses. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} +{!../../docs_src/advanced_middleware/tutorial003.py!} ``` Die folgenden Argumente werden unterstützt: @@ -92,7 +95,6 @@ Es gibt viele andere ASGI-Middlewares. Zum Beispiel: -* Sentry * Uvicorns `ProxyHeadersMiddleware` * MessagePack diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md index 026fdb4fe..4ee2874a3 100644 --- a/docs/de/docs/advanced/openapi-callbacks.md +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -32,11 +32,14 @@ Sie verfügt über eine *Pfadoperation*, die einen `Invoice`-Body empfängt, und Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrscheinlich bereits bekannt: ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "Tipp" - Der Query-Parameter `callback_url` verwendet einen Pydantic-Url-Typ. +/// tip | Tipp + +Der Query-Parameter `callback_url` verwendet einen Pydantic-Url-Typ. + +/// Das einzig Neue ist `callbacks=invoices_callback_router.routes` als Argument für den *Pfadoperation-Dekorator*. Wir werden als Nächstes sehen, was das ist. @@ -61,10 +64,13 @@ Diese Dokumentation wird in der Swagger-Oberfläche unter `/docs` in Ihrer API a In diesem Beispiel wird nicht der Callback selbst implementiert (das könnte nur eine Codezeile sein), sondern nur der Dokumentationsteil. -!!! tip "Tipp" - Der eigentliche Callback ist nur ein HTTP-Request. +/// tip | Tipp + +Der eigentliche Callback ist nur ein HTTP-Request. - Wenn Sie den Callback selbst implementieren, können Sie beispielsweise HTTPX oder Requests verwenden. +Wenn Sie den Callback selbst implementieren, können Sie beispielsweise HTTPX oder Requests verwenden. + +/// ## Schreiben des Codes, der den Callback dokumentiert @@ -74,17 +80,20 @@ Sie wissen jedoch bereits, wie Sie mit **FastAPI** ganz einfach eine automatisch Daher werden wir dasselbe Wissen nutzen, um zu dokumentieren, wie die *externe API* aussehen sollte ... indem wir die *Pfadoperation(en)* erstellen, welche die externe API implementieren soll (die, welche Ihre API aufruft). -!!! tip "Tipp" - Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. +/// tip | Tipp + +Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. - Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören. +Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören. + +/// ### Einen Callback-`APIRouter` erstellen Erstellen Sie zunächst einen neuen `APIRouter`, der einen oder mehrere Callbacks enthält. ```Python hl_lines="3 25" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### Die Callback-*Pfadoperation* erstellen @@ -97,7 +106,7 @@ Sie sollte wie eine normale FastAPI-*Pfadoperation* aussehen: * Und sie könnte auch eine Deklaration der Response enthalten, die zurückgegeben werden soll, z. B. `response_model=InvoiceEventReceived`. ```Python hl_lines="16-18 21-22 28-32" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` Es gibt zwei Hauptunterschiede zu einer normalen *Pfadoperation*: @@ -154,8 +163,11 @@ und sie würde eine Response von dieser *externen API* mit einem JSON-Body wie d } ``` -!!! tip "Tipp" - Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). +/// tip | Tipp + +Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). + +/// ### Den Callback-Router hinzufügen @@ -164,11 +176,14 @@ An diesem Punkt haben Sie die benötigte(n) *Callback-Pfadoperation(en)* (diejen Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer API*, um das Attribut `.routes` (das ist eigentlich nur eine `list`e von Routen/*Pfadoperationen*) dieses Callback-Routers zu übergeben: ```Python hl_lines="35" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. +/// tip | Tipp + +Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. + +/// ### Es in der Dokumentation ansehen diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md index 339218080..9f1bb6959 100644 --- a/docs/de/docs/advanced/openapi-webhooks.md +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -22,21 +22,27 @@ Mit **FastAPI** können Sie mithilfe von OpenAPI die Namen dieser Webhooks, die Dies kann es Ihren Benutzern viel einfacher machen, **deren APIs zu implementieren**, um Ihre **Webhook**-Requests zu empfangen. Möglicherweise können diese sogar einen Teil des eigenem API-Codes automatisch generieren. -!!! info - Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt. +/// info + +Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt. + +/// ## Eine Anwendung mit Webhooks Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, mit dem Sie *Webhooks* definieren können, genauso wie Sie *Pfadoperationen* definieren würden, zum Beispiel mit `@app.webhooks.post()`. ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_webhooks/tutorial001.py!} +{!../../docs_src/openapi_webhooks/tutorial001.py!} ``` Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. -!!! info - Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren. +/// info + +Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren. + +/// Beachten Sie, dass Sie bei Webhooks tatsächlich keinen *Pfad* (wie `/items/`) deklarieren, sondern dass der Text, den Sie dort übergeben, lediglich eine **Kennzeichnung** des Webhooks (der Name des Events) ist. Zum Beispiel ist in `@app.webhooks.post("new-subscription")` der Webhook-Name `new-subscription`. diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md index 406a08e9e..53d395724 100644 --- a/docs/de/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -2,15 +2,18 @@ ## OpenAPI operationId -!!! warning "Achtung" - Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. +/// warning | Achtung + +Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. + +/// Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen, die in Ihrer *Pfadoperation* verwendet werden soll. Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist. ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### Verwendung des Namens der *Pfadoperation-Funktion* als operationId @@ -20,23 +23,29 @@ Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, kö Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben. ```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip "Tipp" - Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. +/// tip | Tipp + +Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. + +/// + +/// warning | Achtung + +Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. -!!! warning "Achtung" - Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. +Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. - Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. +/// ## Von OpenAPI ausschließen Um eine *Pfadoperation* aus dem generierten OpenAPI-Schema (und damit aus den automatischen Dokumentationssystemen) auszuschließen, verwenden Sie den Parameter `include_in_schema` und setzen Sie ihn auf `False`: ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## Fortgeschrittene Beschreibung mittels Docstring @@ -48,7 +57,7 @@ Das Hinzufügen eines `\f` (ein maskiertes „Form Feed“-Zeichen) führt dazu, Sie wird nicht in der Dokumentation angezeigt, aber andere Tools (z. B. Sphinx) können den Rest verwenden. ```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` ## Zusätzliche Responses @@ -65,8 +74,11 @@ Es gibt hier in der Dokumentation ein ganzes Kapitel darüber, Sie können es un Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen. -!!! note "Technische Details" - In der OpenAPI-Spezifikation wird das Operationsobjekt genannt. +/// note | Technische Details + +In der OpenAPI-Spezifikation wird das Operationsobjekt genannt. + +/// Es hat alle Informationen zur *Pfadoperation* und wird zur Erstellung der automatischen Dokumentation verwendet. @@ -74,10 +86,13 @@ Es enthält `tags`, `parameters`, `requestBody`, `responses`, usw. Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern. -!!! tip "Tipp" - Dies ist ein Low-Level Erweiterungspunkt. +/// tip | Tipp + +Dies ist ein Low-Level Erweiterungspunkt. - Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun. +Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun. + +/// Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie den Parameter `openapi_extra` verwenden. @@ -86,7 +101,7 @@ Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie de Dieses `openapi_extra` kann beispielsweise hilfreich sein, um OpenAPI-Erweiterungen zu deklarieren: ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} ``` Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt. @@ -135,7 +150,7 @@ Sie könnten sich beispielsweise dafür entscheiden, den Request mit Ihrem eigen Das könnte man mit `openapi_extra` machen: ```Python hl_lines="20-37 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} ``` In diesem Beispiel haben wir kein Pydantic-Modell deklariert. Tatsächlich wird der Requestbody nicht einmal als JSON geparst, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader ()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen. @@ -150,20 +165,27 @@ Und Sie könnten dies auch tun, wenn der Datentyp in der Anfrage nicht JSON ist. In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Funktionalität von FastAPI zum Extrahieren des JSON-Schemas aus Pydantic-Modellen noch die automatische Validierung für JSON. Tatsächlich deklarieren wir den Request-Content-Type als YAML und nicht als JSON: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="17-22 24" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="17-22 24" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +//// -=== "Pydantic v1" +/// info - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`. -!!! info - In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`. +/// Obwohl wir nicht die standardmäßig integrierte Funktionalität verwenden, verwenden wir dennoch ein Pydantic-Modell, um das JSON-Schema für die Daten, die wir in YAML empfangen möchten, manuell zu generieren. @@ -171,22 +193,32 @@ Dann verwenden wir den Request direkt und extrahieren den Body als `bytes`. Das Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann wieder dasselbe Pydantic-Modell, um den YAML-Inhalt zu validieren: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="26-33" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="26-33" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` + +//// + +/// info - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`. -=== "Pydantic v1" +/// - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +/// tip | Tipp -!!! info - In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`. +Hier verwenden wir dasselbe Pydantic-Modell wieder. -!!! tip "Tipp" - Hier verwenden wir dasselbe Pydantic-Modell wieder. +Aber genauso hätten wir es auch auf andere Weise validieren können. - Aber genauso hätten wir es auch auf andere Weise validieren können. +/// diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md index bba908a3e..202df0d87 100644 --- a/docs/de/docs/advanced/response-change-status-code.md +++ b/docs/de/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Anschließend können Sie den `status_code` in diesem *vorübergehenden* Response-Objekt festlegen. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` Und dann können Sie wie gewohnt jedes benötigte Objekt zurückgeben (ein `dict`, ein Datenbankmodell usw.). diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md index 0f09bd444..6f9d66e07 100644 --- a/docs/de/docs/advanced/response-cookies.md +++ b/docs/de/docs/advanced/response-cookies.md @@ -7,7 +7,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Und dann können Sie Cookies in diesem *vorübergehenden* Response-Objekt setzen. ```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} +{!../../docs_src/response_cookies/tutorial002.py!} ``` Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). @@ -27,23 +27,29 @@ Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurüc Setzen Sie dann Cookies darin und geben Sie sie dann zurück: ```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} +{!../../docs_src/response_cookies/tutorial001.py!} ``` -!!! tip "Tipp" - Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. +/// tip | Tipp - Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben. +Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. - Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen. +Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben. + +Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen. + +/// ### Mehr Informationen -!!! note "Technische Details" - Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. +/// note | Technische Details + +Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. - Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. +/// Um alle verfügbaren Parameter und Optionen anzuzeigen, sehen Sie sich deren Dokumentation in Starlette an. diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md index 13bca7825..fab2e3965 100644 --- a/docs/de/docs/advanced/response-directly.md +++ b/docs/de/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ Das kann beispielsweise nützlich sein, um benutzerdefinierte Header oder Cookie Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben. -!!! tip "Tipp" - `JSONResponse` selbst ist eine Unterklasse von `Response`. +/// tip | Tipp + +`JSONResponse` selbst ist eine Unterklasse von `Response`. + +/// Und wenn Sie eine `Response` zurückgeben, wird **FastAPI** diese direkt weiterleiten. @@ -32,13 +35,16 @@ Sie können beispielsweise kein Pydantic-Modell in eine `JSONResponse` einfügen In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu konvertieren, bevor Sie sie an eine Response übergeben: ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "Technische Details" - Sie können auch `from starlette.responses import JSONResponse` verwenden. +/// note | Technische Details + +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. - **FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. +/// ## Eine benutzerdefinierte `Response` zurückgeben @@ -51,7 +57,7 @@ Nehmen wir an, Sie möchten eine ../../../docs_src/security/tutorial006_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="2 7 11" - {!> ../../../docs_src/security/tutorial006_an.py!} - ``` - -=== "Python 3.8+ nicht annotiert" - - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. - - ```Python hl_lines="2 6 10" - {!> ../../../docs_src/security/tutorial006.py!} - ``` - +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} Wenn Sie versuchen, die URL zum ersten Mal zu öffnen (oder in der Dokumentation auf den Button „Execute“ zu klicken), wird der Browser Sie nach Ihrem Benutzernamen und Passwort fragen: @@ -59,26 +39,7 @@ Um dies zu lösen, konvertieren wir zunächst den `username` und das `password` Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass `credentials.username` `"stanleyjobson"` und `credentials.password` `"swordfish"` ist. -=== "Python 3.9+" - - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` - -=== "Python 3.8+ nicht annotiert" - - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. - - ```Python hl_lines="1 11-21" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} Dies wäre das gleiche wie: @@ -142,23 +103,4 @@ So ist Ihr Anwendungscode, dank der Verwendung von `secrets.compare_digest()`, v Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben Sie eine `HTTPException` mit dem Statuscode 401 zurück (derselbe, der auch zurückgegeben wird, wenn keine Anmeldeinformationen angegeben werden) und fügen den Header `WWW-Authenticate` hinzu, damit der Browser die Anmeldeaufforderung erneut anzeigt: -=== "Python 3.9+" - - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` - -=== "Python 3.8+ nicht annotiert" - - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. - - ```Python hl_lines="23-27" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/de/docs/advanced/security/index.md b/docs/de/docs/advanced/security/index.md index a3c975bed..25eeb25b5 100644 --- a/docs/de/docs/advanced/security/index.md +++ b/docs/de/docs/advanced/security/index.md @@ -4,10 +4,13 @@ Neben den in [Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} behandelten Funktionen gibt es noch einige zusätzliche Funktionen zur Handhabung der Sicherheit. -!!! tip "Tipp" - Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. +/// tip | Tipp - Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. +Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + +Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +/// ## Lesen Sie zuerst das Tutorial diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md index ffd34d65f..85175a895 100644 --- a/docs/de/docs/advanced/security/oauth2-scopes.md +++ b/docs/de/docs/advanced/security/oauth2-scopes.md @@ -10,18 +10,21 @@ Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder Twitter an In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten. -!!! warning "Achtung" - Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen. +/// warning | Achtung - Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten. +Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen. - Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden. +Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten. - Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten. +Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden. - In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein. +Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten. - Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter. +In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein. + +Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter. + +/// ## OAuth2-Scopes und OpenAPI @@ -43,63 +46,87 @@ Er wird normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu dekla * `instagram_basic` wird von Facebook / Instagram verwendet. * `https://www.googleapis.com/auth/drive` wird von Google verwendet. -!!! info - In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. +/// info + +In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. + +Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. - Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. +Diese Details sind implementierungsspezifisch. - Diese Details sind implementierungsspezifisch. +Für OAuth2 sind es einfach nur Strings. - Für OAuth2 sind es einfach nur Strings. +/// ## Gesamtübersicht Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im Haupt-**Tutorial – Benutzerhandbuch** für [OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} ändern. Diesmal verwenden wir OAuth2-Scopes: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | Tipp - ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.9+" +/// - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.10+ nicht annotiert" +/// tip | Tipp - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +/// -=== "Python 3.9+ nicht annotiert" +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +//// tab | Python 3.8+ nicht annotiert -=== "Python 3.8+ nicht annotiert" +/// tip | Tipp - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +/// + +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// Sehen wir uns diese Änderungen nun Schritt für Schritt an. @@ -109,51 +136,71 @@ Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei ve Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="62-65" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="62-65" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="63-66" +{!> ../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +/// tip | Tipp -=== "Python 3.10+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="61-64" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +```Python hl_lines="61-64" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.9+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | Tipp - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="62-65" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="62-65" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren. @@ -171,55 +218,79 @@ Wir verwenden immer noch dasselbe `OAuth2PasswordRequestForm`. Es enthält eine Und wir geben die Scopes als Teil des JWT-Tokens zurück. -!!! danger "Gefahr" - Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. +/// danger | Gefahr + +Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. - Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben. +Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben. -=== "Python 3.10+" +/// - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// tab | Python 3.10+ -=== "Python 3.9+" +```Python hl_lines="155" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.9+ - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +```Python hl_lines="155" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.10+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ - ```Python hl_lines="154" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +```Python hl_lines="156" +{!> ../../docs_src/security/tutorial005_an.py!} +``` -=== "Python 3.9+ nicht annotiert" +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.10+ nicht annotiert - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +/// tip | Tipp -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +```Python hl_lines="154" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="155" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="155" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// ## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren @@ -237,62 +308,89 @@ Und die Abhängigkeitsfunktion `get_current_active_user` kann auch Unterabhängi In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern). -!!! note "Hinweis" - Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. +/// note | Hinweis + +Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. + +Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="4 139 170" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 139 170" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 140 171" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | Tipp - Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet. +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+" +/// - ```Python hl_lines="4 139 170" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="3 138 167" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 139 170" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.8+" +/// tip | Tipp - ```Python hl_lines="4 140 171" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 139 168" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="3 138 167" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | Tipp - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="4 139 168" +{!> ../../docs_src/security/tutorial005.py!} +``` - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// -!!! info "Technische Details" - `Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. +/// info | Technische Details - Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann. +`Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. - Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben. +Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann. + +Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben. + +/// ## `SecurityScopes` verwenden @@ -308,50 +406,71 @@ Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der au Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8 105" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8 105" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 106" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="7 104" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ nicht annotiert -=== "Python 3.8+" +/// tip | Tipp - ```Python hl_lines="8 106" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="8 105" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` - ```Python hl_lines="7 104" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | Tipp - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="8 105" +{!> ../../docs_src/security/tutorial005.py!} +``` - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// ## Die `scopes` verwenden @@ -365,50 +484,71 @@ Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederve In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="105 107-115" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="105 107-115" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="106 108-116" +{!> ../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="104 106-114" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | Tipp - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="104 106-114" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// + +//// tab | Python 3.9+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="105 107-115" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="105 107-115" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// ## Den `username` und das Format der Daten überprüfen @@ -424,50 +564,71 @@ Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anw Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="46 116-127" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +```Python hl_lines="46 116-127" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ nicht annotiert" +```Python hl_lines="47 117-128" +{!> ../../docs_src/security/tutorial005_an.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="45 115-126" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+ nicht annotiert" +/// tip | Tipp - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +/// -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="45 115-126" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +//// tab | Python 3.9+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="46 116-127" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="46 116-127" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// ## Die `scopes` verifizieren @@ -475,50 +636,71 @@ Wir überprüfen nun, ob das empfangenen Token alle Scopes enthält, die von die Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="128-134" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` +```Python hl_lines="128-134" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="129-135" +{!> ../../docs_src/security/tutorial005_an.py!} +``` - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.10+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | Tipp - ```Python hl_lines="127-133" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.9+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="127-133" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +//// -=== "Python 3.8+ nicht annotiert" +//// tab | Python 3.9+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | Tipp - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="128-134" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="128-134" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// ## Abhängigkeitsbaum und Scopes @@ -545,10 +727,13 @@ So sieht die Hierarchie der Abhängigkeiten und Scopes aus: * `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist. * `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert. -!!! tip "Tipp" - Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. +/// tip | Tipp + +Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. - Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden. +Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden. + +/// ## Weitere Details zu `SecurityScopes`. @@ -586,10 +771,13 @@ Am häufigsten ist der „Implicit“-Flow. Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor. -!!! note "Hinweis" - Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. +/// note | Hinweis + +Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. + +Aber am Ende implementieren sie denselben OAuth2-Standard. - Aber am Ende implementieren sie denselben OAuth2-Standard. +/// **FastAPI** enthält Werkzeuge für alle diese OAuth2-Authentifizierungs-Flows in `fastapi.security.oauth2`. diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md index fe01d8e1f..c90f74844 100644 --- a/docs/de/docs/advanced/settings.md +++ b/docs/de/docs/advanced/settings.md @@ -8,44 +8,51 @@ Aus diesem Grund werden diese üblicherweise in Umgebungsvariablen bereitgestell ## Umgebungsvariablen -!!! tip "Tipp" - Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. +/// tip | Tipp + +Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. + +/// Eine Umgebungsvariable (auch bekannt als „env var“) ist eine Variable, die sich außerhalb des Python-Codes im Betriebssystem befindet und von Ihrem Python-Code (oder auch von anderen Programmen) gelesen werden kann. Sie können Umgebungsvariablen in der Shell erstellen und verwenden, ohne Python zu benötigen: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - // Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels - $ export MY_NAME="Wade Wilson" +```console +// Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels +$ export MY_NAME="Wade Wilson" - // Dann könnten Sie diese mit anderen Programmen verwenden, etwa - $ echo "Hello $MY_NAME" +// Dann könnten Sie diese mit anderen Programmen verwenden, etwa +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
- Hello Wade Wilson - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +// Erstelle eine Umgebungsvariable MY_NAME +$ $Env:MY_NAME = "Wade Wilson" - ```console - // Erstelle eine Umgebungsvariable MY_NAME - $ $Env:MY_NAME = "Wade Wilson" +// Verwende sie mit anderen Programmen, etwa +$ echo "Hello $Env:MY_NAME" - // Verwende sie mit anderen Programmen, etwa - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +
-
+//// ### Umgebungsvariablen mit Python auslesen @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip "Tipp" - Das zweite Argument für `os.getenv()` ist der zurückzugebende Defaultwert. +/// tip | Tipp + +Das zweite Argument für `os.getenv()` ist der zurückzugebende Defaultwert. - Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert. +Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert. + +/// Dann könnten Sie dieses Python-Programm aufrufen: @@ -114,8 +124,11 @@ Hello World from Python
-!!! tip "Tipp" - Weitere Informationen dazu finden Sie unter The Twelve-Factor App: Config. +/// tip | Tipp + +Weitere Informationen dazu finden Sie unter The Twelve-Factor App: Config. + +/// ### Typen und Validierung @@ -151,8 +164,11 @@ $ pip install "fastapi[all]" -!!! info - In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen. +/// info + +In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen. + +/// ### Das `Settings`-Objekt erstellen @@ -162,23 +178,33 @@ Auf die gleiche Weise wie bei Pydantic-Modellen deklarieren Sie Klassenattribute Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für Pydantic-Modelle verwenden, z. B. verschiedene Datentypen und zusätzliche Validierungen mit `Field()`. -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="2 5-8 11" +{!> ../../docs_src/settings/tutorial001.py!} +``` + +//// + +//// tab | Pydantic v1 - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001.py!} - ``` +/// info + +In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren. + +/// + +```Python hl_lines="2 5-8 11" +{!> ../../docs_src/settings/tutorial001_pv1.py!} +``` -=== "Pydantic v1" +//// - !!! info - In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren. +/// tip | Tipp - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001_pv1.py!} - ``` +Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. -!!! tip "Tipp" - Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. +/// Wenn Sie dann eine Instanz dieser `Settings`-Klasse erstellen (in diesem Fall als `settings`-Objekt), liest Pydantic die Umgebungsvariablen ohne Berücksichtigung der Groß- und Kleinschreibung. Eine Variable `APP_NAME` in Großbuchstaben wird also als Attribut `app_name` gelesen. @@ -189,7 +215,7 @@ Als Nächstes werden die Daten konvertiert und validiert. Wenn Sie also dieses ` Dann können Sie das neue `settings`-Objekt in Ihrer Anwendung verwenden: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### Den Server ausführen @@ -206,8 +232,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app -!!! tip "Tipp" - Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. +/// tip | Tipp + +Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. + +/// Und dann würde die Einstellung `admin_email` auf `"deadpool@example.com"` gesetzt. @@ -222,17 +251,20 @@ Sie könnten diese Einstellungen in eine andere Moduldatei einfügen, wie Sie in Sie könnten beispielsweise eine Datei `config.py` haben mit: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` Und dann verwenden Sie diese in einer Datei `main.py`: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` -!!! tip "Tipp" - Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. +/// tip | Tipp + +Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. + +/// ## Einstellungen in einer Abhängigkeit @@ -245,7 +277,7 @@ Dies könnte besonders beim Testen nützlich sein, da es sehr einfach ist, eine Ausgehend vom vorherigen Beispiel könnte Ihre Datei `config.py` so aussehen: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erstellen. @@ -254,61 +286,82 @@ Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erste Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurückgibt. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="6 12-13" +{!> ../../docs_src/settings/app02_an_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ nicht annotiert" +```Python hl_lines="6 12-13" +{!> ../../docs_src/settings/app02_an/main.py!} +``` + +//// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +/// tip | Tipp -!!! tip "Tipp" - Wir werden das `@lru_cache` in Kürze besprechen. +Bevorzugen Sie die `Annotated`-Version, falls möglich. - Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. +/// + +```Python hl_lines="5 11-12" +{!> ../../docs_src/settings/app02/main.py!} +``` + +//// + +/// tip | Tipp + +Wir werden das `@lru_cache` in Kürze besprechen. + +Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. + +/// Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einfordern und es überall dort verwenden, wo wir es brauchen. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="17 19-21" +{!> ../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// tip | Tipp -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +```Python hl_lines="16 18-20" +{!> ../../docs_src/settings/app02/main.py!} +``` + +//// ### Einstellungen und Tests Dann wäre es sehr einfach, beim Testen ein anderes Einstellungsobjekt bereitzustellen, indem man eine Abhängigkeitsüberschreibung für `get_settings` erstellt: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` Bei der Abhängigkeitsüberschreibung legen wir einen neuen Wert für `admin_email` fest, wenn wir das neue `Settings`-Objekt erstellen, und geben dann dieses neue Objekt zurück. @@ -321,15 +374,21 @@ Wenn Sie viele Einstellungen haben, die sich möglicherweise oft ändern, vielle Diese Praxis ist so weit verbreitet, dass sie einen Namen hat. Diese Umgebungsvariablen werden üblicherweise in einer Datei `.env` abgelegt und die Datei wird „dotenv“ genannt. -!!! tip "Tipp" - Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. +/// tip | Tipp + +Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. - Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. +Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. + +/// Pydantic unterstützt das Lesen dieser Dateitypen mithilfe einer externen Bibliothek. Weitere Informationen finden Sie unter Pydantic Settings: Dotenv (.env) support. -!!! tip "Tipp" - Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. +/// tip | Tipp + +Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. + +/// ### Die `.env`-Datei @@ -344,26 +403,39 @@ APP_NAME="ChimichangApp" Und dann aktualisieren Sie Ihre `config.py` mit: -=== "Pydantic v2" +//// tab | Pydantic v2 - ```Python hl_lines="9" - {!> ../../../docs_src/settings/app03_an/config.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/settings/app03_an/config.py!} +``` - !!! tip "Tipp" - Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic: Configuration. +/// tip | Tipp -=== "Pydantic v1" +Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic: Configuration. - ```Python hl_lines="9-10" - {!> ../../../docs_src/settings/app03_an/config_pv1.py!} - ``` +/// - !!! tip "Tipp" - Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic Model Config. +//// -!!! info - In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren. +//// tab | Pydantic v1 + +```Python hl_lines="9-10" +{!> ../../docs_src/settings/app03_an/config_pv1.py!} +``` + +/// tip | Tipp + +Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic Model Config. + +/// + +//// + +/// info + +In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren. + +/// Hier definieren wir die Konfiguration `env_file` innerhalb Ihrer Pydantic-`Settings`-Klasse und setzen den Wert auf den Dateinamen mit der dotenv-Datei, die wir verwenden möchten. @@ -390,26 +462,35 @@ würden wir dieses Objekt für jeden Request erstellen und die `.env`-Datei für Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Objekt nur einmal erstellt, nämlich beim ersten Aufruf. ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +```Python hl_lines="1 11" +{!> ../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../docs_src/settings/app03_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +/// tip | Tipp -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="1 10" +{!> ../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// Dann wird bei allen nachfolgenden Aufrufen von `get_settings()`, in den Abhängigkeiten für darauffolgende Requests, dasselbe Objekt zurückgegeben, das beim ersten Aufruf zurückgegeben wurde, anstatt den Code von `get_settings()` erneut auszuführen und ein neues `Settings`-Objekt zu erstellen. diff --git a/docs/de/docs/advanced/sub-applications.md b/docs/de/docs/advanced/sub-applications.md index 7dfaaa0cd..172b8d3c1 100644 --- a/docs/de/docs/advanced/sub-applications.md +++ b/docs/de/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ Wenn Sie zwei unabhängige FastAPI-Anwendungen mit deren eigenen unabhängigen O Erstellen Sie zunächst die Hauptanwendung **FastAPI** und deren *Pfadoperationen*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Unteranwendung @@ -21,7 +21,7 @@ Erstellen Sie dann Ihre Unteranwendung und deren *Pfadoperationen*. Diese Unteranwendung ist nur eine weitere Standard-FastAPI-Anwendung, aber diese wird „gemountet“: ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Die Unteranwendung mounten @@ -31,7 +31,7 @@ Mounten Sie in Ihrer Top-Level-Anwendung `app` die Unteranwendung `subapi`. In diesem Fall wird sie im Pfad `/subapi` gemountet: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Es in der automatischen API-Dokumentation betrachten diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md index 17d821e61..658a2592e 100644 --- a/docs/de/docs/advanced/templates.md +++ b/docs/de/docs/advanced/templates.md @@ -28,28 +28,37 @@ $ pip install jinja2 * Verwenden Sie die von Ihnen erstellten `templates`, um eine `TemplateResponse` zu rendern und zurückzugeben, übergeben Sie den Namen des Templates, das Requestobjekt und ein „Kontext“-Dictionary mit Schlüssel-Wert-Paaren, die innerhalb des Jinja2-Templates verwendet werden sollen. ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` -!!! note "Hinweis" - Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. +/// note | Hinweis - Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben. +Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. -!!! tip "Tipp" - Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. +Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben. -!!! note "Technische Details" - Sie können auch `from starlette.templating import Jinja2Templates` verwenden. +/// - **FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`. +/// tip | Tipp + +Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. + +/// + +/// note | Technische Details + +Sie können auch `from starlette.templating import Jinja2Templates` verwenden. + +**FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`. + +/// ## Templates erstellen Dann können Sie unter `templates/item.html` ein Template erstellen, mit z. B. folgendem Inhalt: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### Template-Kontextwerte @@ -103,13 +112,13 @@ Mit beispielsweise der ID `42` würde dies Folgendes ergeben: Sie können `url_for()` innerhalb des Templates auch beispielsweise mit den `StaticFiles` verwenden, die Sie mit `name="static"` gemountet haben. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` In diesem Beispiel würde das zu einer CSS-Datei unter `static/styles.css` verlinken, mit folgendem Inhalt: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` Und da Sie `StaticFiles` verwenden, wird diese CSS-Datei automatisch von Ihrer **FastAPI**-Anwendung unter der URL `/static/styles.css` bereitgestellt. diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md index e7841b5f5..3b4604da3 100644 --- a/docs/de/docs/advanced/testing-dependencies.md +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -28,48 +28,67 @@ Um eine Abhängigkeit für das Testen zu überschreiben, geben Sie als Schlüsse Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abhängigkeit auf. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="26-27 30" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} - ``` +```Python hl_lines="26-27 30" +{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="28-29 32" +{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="29-30 33" +{!> ../../docs_src/dependency_testing/tutorial001_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.8+" +/// tip | Tipp - ```Python hl_lines="29-30 33" - {!> ../../../docs_src/dependency_testing/tutorial001_an.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.10+ nicht annotiert" +/// - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +```Python hl_lines="24-25 28" +{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert - ```Python hl_lines="24-25 28" - {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} - ``` +/// tip | Tipp -=== "Python 3.8+ nicht annotiert" +Bevorzugen Sie die `Annotated`-Version, falls möglich. - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// + +```Python hl_lines="28-29 32" +{!> ../../docs_src/dependency_testing/tutorial001.py!} +``` - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001.py!} - ``` +//// -!!! tip "Tipp" - Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. +/// tip | Tipp - Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden. +Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. - FastAPI kann sie in jedem Fall überschreiben. +Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden. + +FastAPI kann sie in jedem Fall überschreiben. + +/// Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), indem Sie `app.dependency_overrides` auf ein leeres `dict` setzen: @@ -77,5 +96,8 @@ Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), inde app.dependency_overrides = {} ``` -!!! tip "Tipp" - Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. +/// tip | Tipp + +Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. + +/// diff --git a/docs/de/docs/advanced/testing-events.md b/docs/de/docs/advanced/testing-events.md index f50093548..3e63791c6 100644 --- a/docs/de/docs/advanced/testing-events.md +++ b/docs/de/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ Wenn Sie in Ihren Tests Ihre Event-Handler (`startup` und `shutdown`) ausführen wollen, können Sie den `TestClient` mit einer `with`-Anweisung verwenden: ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md index 53de72f15..5122e1f33 100644 --- a/docs/de/docs/advanced/testing-websockets.md +++ b/docs/de/docs/advanced/testing-websockets.md @@ -5,8 +5,11 @@ Sie können den schon bekannten `TestClient` zum Testen von WebSockets verwenden Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung zum WebSocket herstellend: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` -!!! note "Hinweis" - Weitere Informationen finden Sie in der Starlette-Dokumentation zum Testen von WebSockets. +/// note | Hinweis + +Weitere Informationen finden Sie in der Starlette-Dokumentation zum Testen von WebSockets. + +/// diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md index f40f5d4be..1c2a6f852 100644 --- a/docs/de/docs/advanced/using-request-directly.md +++ b/docs/de/docs/advanced/using-request-directly.md @@ -30,23 +30,29 @@ Angenommen, Sie möchten auf die IP-Adresse/den Host des Clients in Ihrer *Pfado Dazu müssen Sie direkt auf den Request zugreifen. ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. -!!! tip "Tipp" - Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. +/// tip | Tipp - Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert. +Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. - Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten. +Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert. + +Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten. + +/// ## `Request`-Dokumentation Weitere Details zum `Request`-Objekt finden Sie in der offiziellen Starlette-Dokumentation. -!!! note "Technische Details" - Sie können auch `from starlette.requests import Request` verwenden. +/// note | Technische Details + +Sie können auch `from starlette.requests import Request` verwenden. + +**FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette. - **FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette. +/// diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md index e5e6a9d01..5bc5f6902 100644 --- a/docs/de/docs/advanced/websockets.md +++ b/docs/de/docs/advanced/websockets.md @@ -39,7 +39,7 @@ In der Produktion hätten Sie eine der oben genannten Optionen. Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets zu konzentrieren und ein funktionierendes Beispiel zu haben: ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## Einen `websocket` erstellen @@ -47,20 +47,23 @@ Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` -!!! note "Technische Details" - Sie können auch `from starlette.websockets import WebSocket` verwenden. +/// note | Technische Details - **FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette. +Sie können auch `from starlette.websockets import WebSocket` verwenden. + +**FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette. + +/// ## Nachrichten erwarten und Nachrichten senden In Ihrer WebSocket-Route können Sie Nachrichten `await`en und Nachrichten senden. ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` Sie können Binär-, Text- und JSON-Daten empfangen und senden. @@ -112,46 +115,65 @@ In WebSocket-Endpunkten können Sie Folgendes aus `fastapi` importieren und verw Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="68-69 82" +{!> ../../docs_src/websockets/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="68-69 82" +{!> ../../docs_src/websockets/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="69-70 83" +{!> ../../docs_src/websockets/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ nicht annotiert -=== "Python 3.9+" +/// tip | Tipp - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+" +/// - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` +```Python hl_lines="66-67 79" +{!> ../../docs_src/websockets/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+ nicht annotiert" +//// tab | Python 3.8+ nicht annotiert - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +/// tip | Tipp - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +Bevorzugen Sie die `Annotated`-Version, falls möglich. -=== "Python 3.8+ nicht annotiert" +/// + +```Python hl_lines="68-69 81" +{!> ../../docs_src/websockets/tutorial002.py!} +``` - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. +//// - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` +/// info -!!! info - Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus. +Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus. - Sie können einen „Closing“-Code verwenden, aus den gültigen Codes, die in der Spezifikation definiert sind. +Sie können einen „Closing“-Code verwenden, aus den gültigen Codes, die in der Spezifikation definiert sind. + +/// ### WebSockets mit Abhängigkeiten ausprobieren @@ -174,8 +196,11 @@ Dort können Sie einstellen: * Die „Item ID“, die im Pfad verwendet wird. * Das „Token“, das als Query-Parameter verwendet wird. -!!! tip "Tipp" - Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. +/// tip | Tipp + +Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. + +/// Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfangen: @@ -185,17 +210,21 @@ Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfan Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` +```Python hl_lines="79-81" +{!> ../../docs_src/websockets/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="81-83" +{!> ../../docs_src/websockets/tutorial003.py!} +``` - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +//// Zum Ausprobieren: @@ -209,12 +238,15 @@ Das wird die Ausnahme `WebSocketDisconnect` auslösen und alle anderen Clients e Client #1596980209979 left the chat ``` -!!! tip "Tipp" - Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. +/// tip | Tipp + +Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. + +Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess. - Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess. +Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich encode/broadcaster an. - Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich encode/broadcaster an. +/// ## Mehr Informationen diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md index 19ff90a90..50abc84d1 100644 --- a/docs/de/docs/advanced/wsgi.md +++ b/docs/de/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ Wrappen Sie dann die WSGI-Anwendung (z. B. Flask) mit der Middleware. Und dann mounten Sie das auf einem Pfad. ```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## Es ansehen diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md index ea624ff3a..611315501 100644 --- a/docs/de/docs/alternatives.md +++ b/docs/de/docs/alternatives.md @@ -30,12 +30,17 @@ Es wird von vielen Unternehmen verwendet, darunter Mozilla, Red Hat und Eventbri Es war eines der ersten Beispiele für **automatische API-Dokumentation**, und dies war insbesondere eine der ersten Ideen, welche „die Suche nach“ **FastAPI** inspirierten. -!!! note "Hinweis" - Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. +/// note | Hinweis +Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. -!!! check "Inspirierte **FastAPI**" - Eine automatische API-Dokumentationsoberfläche zu haben. +/// + +/// check | Inspirierte **FastAPI** + +Eine automatische API-Dokumentationsoberfläche zu haben. + +/// ### Flask @@ -51,11 +56,13 @@ Diese Entkopplung der Teile und die Tatsache, dass es sich um ein „Mikroframew Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden. -!!! check "Inspirierte **FastAPI**" - Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. +/// check | Inspirierte **FastAPI** - Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen. +Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. +Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen. + +/// ### Requests @@ -91,11 +98,13 @@ def read_url(): Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an. -!!! check "Inspirierte **FastAPI**" - * Über eine einfache und intuitive API zu verfügen. - * HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. - * Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten. +/// check | Inspirierte **FastAPI** + +* Über eine einfache und intuitive API zu verfügen. +* HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. +* Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten. +/// ### Swagger / OpenAPI @@ -109,15 +118,18 @@ Irgendwann wurde Swagger an die Linux Foundation übergeben und in OpenAPI umben Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“. -!!! check "Inspirierte **FastAPI**" - Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. +/// check | Inspirierte **FastAPI** + +Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. - Und Standard-basierte Tools für die Oberfläche zu integrieren: +Und Standard-basierte Tools für die Oberfläche zu integrieren: - * Swagger UI - * ReDoc +* Swagger UI +* ReDoc - Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können). +Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können). + +/// ### Flask REST Frameworks @@ -135,8 +147,11 @@ Für diese Funktionen wurde Marshmallow entwickelt. Es ist eine großartige Bibl Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein Schema zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden. -!!! check "Inspirierte **FastAPI**" - Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. +/// check | Inspirierte **FastAPI** + +Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. + +/// ### Webargs @@ -148,11 +163,17 @@ Es verwendet unter der Haube Marshmallow, um die Datenvalidierung durchzuführen Es ist ein großartiges Tool und ich habe es auch oft verwendet, bevor ich **FastAPI** hatte. -!!! info - Webargs wurde von denselben Marshmallow-Entwicklern erstellt. +/// info + +Webargs wurde von denselben Marshmallow-Entwicklern erstellt. + +/// + +/// check | Inspirierte **FastAPI** -!!! check "Inspirierte **FastAPI**" - Eingehende Requestdaten automatisch zu validieren. +Eingehende Requestdaten automatisch zu validieren. + +/// ### APISpec @@ -172,12 +193,17 @@ Aber dann haben wir wieder das Problem einer Mikrosyntax innerhalb eines Python- Der Texteditor kann dabei nicht viel helfen. Und wenn wir Parameter oder Marshmallow-Schemas ändern und vergessen, auch den YAML-Docstring zu ändern, wäre das generierte Schema veraltet. -!!! info - APISpec wurde von denselben Marshmallow-Entwicklern erstellt. +/// info + +APISpec wurde von denselben Marshmallow-Entwicklern erstellt. + +/// +/// check | Inspirierte **FastAPI** -!!! check "Inspirierte **FastAPI**" - Den offenen Standard für APIs, OpenAPI, zu unterstützen. +Den offenen Standard für APIs, OpenAPI, zu unterstützen. + +/// ### Flask-apispec @@ -199,11 +225,17 @@ Die Verwendung führte zur Entwicklung mehrerer Flask-Full-Stack-Generatoren. Di Und dieselben Full-Stack-Generatoren bildeten die Basis der [**FastAPI**-Projektgeneratoren](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. +/// info + +Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. + +/// -!!! check "Inspirierte **FastAPI**" - Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. +/// check | Inspirierte **FastAPI** + +Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. + +/// ### NestJS (und Angular) @@ -219,24 +251,33 @@ Da TypeScript-Daten jedoch nach der Kompilierung nach JavaScript nicht erhalten Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body in der Anfrage also um ein JSON-Objekt mit inneren Feldern handelt, die wiederum verschachtelte JSON-Objekte sind, kann er nicht richtig dokumentiert und validiert werden. -!!! check "Inspirierte **FastAPI**" - Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. +/// check | Inspirierte **FastAPI** + +Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. - Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren. +Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren. + +/// ### Sanic Es war eines der ersten extrem schnellen Python-Frameworks, welches auf `asyncio` basierte. Es wurde so gestaltet, dass es Flask sehr ähnlich ist. -!!! note "Technische Details" - Es verwendete `uvloop` anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. +/// note | Technische Details + +Es verwendete `uvloop` anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. - Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind. +Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind. -!!! check "Inspirierte **FastAPI**" - Einen Weg zu finden, eine hervorragende Performanz zu haben. +/// - Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten). +/// check | Inspirierte **FastAPI** + +Einen Weg zu finden, eine hervorragende Performanz zu haben. + +Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten). + +/// ### Falcon @@ -246,12 +287,15 @@ Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter e Daher müssen Datenvalidierung, Serialisierung und Dokumentation im Code und nicht automatisch erfolgen. Oder sie müssen als Framework oberhalb von Falcon implementiert werden, so wie Hug. Dieselbe Unterscheidung findet auch in anderen Frameworks statt, die vom Design von Falcon inspiriert sind und ein Requestobjekt und ein Responseobjekt als Parameter haben. -!!! check "Inspirierte **FastAPI**" - Wege zu finden, eine großartige Performanz zu erzielen. +/// check | Inspirierte **FastAPI** - Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren. +Wege zu finden, eine großartige Performanz zu erzielen. - Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird. +Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren. + +Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird. + +/// ### Molten @@ -269,12 +313,15 @@ Das Dependency Injection System erfordert eine Vorab-Registrierung der Abhängig Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind. -!!! check "Inspirierte **FastAPI**" - Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. +/// check | Inspirierte **FastAPI** + +Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. - Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar). +Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar). -### Hug +/// + +### Hug Hug war eines der ersten Frameworks, welches die Deklaration von API-Parametertypen mithilfe von Python-Typhinweisen implementierte. Das war eine großartige Idee, die andere Tools dazu inspirierte, dasselbe zu tun. @@ -288,15 +335,21 @@ Es verfügt über eine interessante, ungewöhnliche Funktion: Mit demselben Fram Da es auf dem bisherigen Standard für synchrone Python-Webframeworks (WSGI) basiert, kann es nicht mit Websockets und anderen Dingen umgehen, verfügt aber dennoch über eine hohe Performanz. -!!! info - Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von `isort`, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien. +/// info + +Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von `isort`, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien. + +/// -!!! check "Ideen, die **FastAPI** inspiriert haben" - Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar. +/// check | Ideen, die **FastAPI** inspiriert haben - Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert. +Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar. - Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen. +Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert. + +Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen. + +/// ### APIStar (≦ 0.5) @@ -322,23 +375,29 @@ Es handelte sich nicht länger um ein API-Webframework, da sich der Entwickler a Jetzt handelt es sich bei APIStar um eine Reihe von Tools zur Validierung von OpenAPI-Spezifikationen, nicht um ein Webframework. -!!! info - APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat: +/// info + +APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat: - * Django REST Framework - * Starlette (auf welchem **FastAPI** basiert) - * Uvicorn (verwendet von Starlette und **FastAPI**) +* Django REST Framework +* Starlette (auf welchem **FastAPI** basiert) +* Uvicorn (verwendet von Starlette und **FastAPI**) -!!! check "Inspirierte **FastAPI**" - Zu existieren. +/// - Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee. +/// check | Inspirierte **FastAPI** - Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option. +Zu existieren. - Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**. +Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee. - Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools. +Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option. + +Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**. + +Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools. + +/// ## Verwendet von **FastAPI** @@ -350,10 +409,13 @@ Das macht es äußerst intuitiv. Es ist vergleichbar mit Marshmallow. Obwohl es in Benchmarks schneller als Marshmallow ist. Und da es auf den gleichen Python-Typhinweisen basiert, ist die Editorunterstützung großartig. -!!! check "**FastAPI** verwendet es, um" - Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen. +/// check | **FastAPI** verwendet es, um - **FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein. +Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen. + +**FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein. + +/// ### Starlette @@ -382,17 +444,23 @@ Es bietet jedoch keine automatische Datenvalidierung, Serialisierung oder Dokume Das ist eines der wichtigsten Dinge, welche **FastAPI** hinzufügt, alles basierend auf Python-Typhinweisen (mit Pydantic). Das, plus, das Dependency Injection System, Sicherheitswerkzeuge, OpenAPI-Schemagenerierung, usw. -!!! note "Technische Details" - ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun. +/// note | Technische Details + +ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun. - Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können. +Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können. -!!! check "**FastAPI** verwendet es, um" - Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf. +/// - Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`. +/// check | **FastAPI** verwendet es, um - Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt. +Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf. + +Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`. + +Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt. + +/// ### Uvicorn @@ -402,12 +470,15 @@ Es handelt sich nicht um ein Webframework, sondern um einen Server. Beispielswei Es ist der empfohlene Server für Starlette und **FastAPI**. -!!! check "**FastAPI** empfiehlt es als" - Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen. +/// check | **FastAPI** empfiehlt es als + +Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen. + +Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten. - Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten. +Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}. - Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}. +/// ## Benchmarks und Geschwindigkeit diff --git a/docs/de/docs/async.md b/docs/de/docs/async.md index c2a43ac66..b5b3a4c52 100644 --- a/docs/de/docs/async.md +++ b/docs/de/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden. +/// note + +Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden. + +/// --- @@ -136,8 +139,11 @@ Sie und Ihr Schwarm essen die Burger und haben eine schöne Zeit. ✨ -!!! info - Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 +/// info + +Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 + +/// --- @@ -199,8 +205,11 @@ Sie essen sie und sind fertig. ⏹ Es wurde nicht viel geredet oder geflirtet, da die meiste Zeit mit Warten 🕙 vor der Theke verbracht wurde. 😞 -!!! info - Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 +/// info + +Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 + +/// --- @@ -392,12 +401,15 @@ All das ist es, was FastAPI (via Starlette) befeuert und es eine so beeindrucken ## Sehr technische Details -!!! warning "Achtung" - Das folgende können Sie wahrscheinlich überspringen. +/// warning | Achtung + +Das folgende können Sie wahrscheinlich überspringen. + +Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert. - Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert. +Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort. - Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort. +/// ### Pfadoperation-Funktionen diff --git a/docs/de/docs/contributing.md b/docs/de/docs/contributing.md index 07a3c9a78..9dfa1e65a 100644 --- a/docs/de/docs/contributing.md +++ b/docs/de/docs/contributing.md @@ -4,7 +4,7 @@ Vielleicht möchten Sie sich zuerst die grundlegenden Möglichkeiten anschauen, ## Entwicklung -Wenn Sie das fastapi Repository bereits geklont haben und tief in den Code eintauchen möchten, hier einen Leitfaden zum Einrichten Ihrer Umgebung. +Wenn Sie das fastapi Repository bereits geklont haben und tief in den Code eintauchen möchten, hier einen Leitfaden zum Einrichten Ihrer Umgebung. ### Virtuelle Umgebung mit `venv` @@ -24,63 +24,73 @@ Das erstellt ein Verzeichnis `./env/` mit den Python-Binärdateien und Sie könn Aktivieren Sie die neue Umgebung mit: -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
+ +//// + +//// tab | Windows Bash - Oder, wenn Sie Bash für Windows verwenden (z. B. Git Bash): +Oder, wenn Sie Bash für Windows verwenden (z. B. Git Bash): -
+
+ +```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +
-
+//// Um zu überprüfen, ob es funktioniert hat, geben Sie ein: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ Get-Command pip +
- some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip + +some/directory/fastapi/env/bin/pip +``` -
+
+ +//// Wenn die `pip` Binärdatei unter `env/bin/pip` angezeigt wird, hat es funktioniert. 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip -!!! tip "Tipp" - Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut. +/// tip | Tipp + +Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut. - Dadurch wird sichergestellt, dass Sie, wenn Sie ein von diesem Package installiertes Terminalprogramm verwenden, das Programm aus Ihrer lokalen Umgebung verwenden und kein anderes, das global installiert sein könnte. +Dadurch wird sichergestellt, dass Sie, wenn Sie ein von diesem Package installiertes Terminalprogramm verwenden, das Programm aus Ihrer lokalen Umgebung verwenden und kein anderes, das global installiert sein könnte. + +/// ### Benötigtes mit pip installieren @@ -125,10 +138,13 @@ Und wenn Sie diesen lokalen FastAPI-Quellcode aktualisieren und dann die Python- Auf diese Weise müssen Sie Ihre lokale Version nicht „installieren“, um jede Änderung testen zu können. -!!! note "Technische Details" - Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen. +/// note | Technische Details + +Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen. - Das liegt daran, dass in der Datei `requirements.txt` die lokale Version von FastAPI mit der Option `-e` für die Installation im „editierbaren“ Modus markiert ist. +Das liegt daran, dass in der Datei `requirements.txt` die lokale Version von FastAPI mit der Option `-e` für die Installation im „editierbaren“ Modus markiert ist. + +/// ### Den Code formatieren @@ -170,20 +186,23 @@ Das stellt die Dokumentation unter `http://127.0.0.1:8008` bereit. Auf diese Weise können Sie die Dokumentation/Quelldateien bearbeiten und die Änderungen live sehen. -!!! tip "Tipp" - Alternativ können Sie die Schritte des Skripts auch manuell ausführen. +/// tip | Tipp - Gehen Sie in das Verzeichnis für die entsprechende Sprache. Das für die englischsprachige Hauptdokumentation befindet sich unter `docs/en/`: +Alternativ können Sie die Schritte des Skripts auch manuell ausführen. - ```console - $ cd docs/en/ - ``` +Gehen Sie in das Verzeichnis für die entsprechende Sprache. Das für die englischsprachige Hauptdokumentation befindet sich unter `docs/en/`: - Führen Sie dann `mkdocs` in diesem Verzeichnis aus: +```console +$ cd docs/en/ +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +Führen Sie dann `mkdocs` in diesem Verzeichnis aus: + +```console +$ mkdocs serve --dev-addr 8008 +``` + +/// #### Typer-CLI (optional) @@ -210,8 +229,11 @@ Die Dokumentation verwendet aktuellen Pull Requests für Ihre Sprache. Sie können die Pull Requests nach dem Label für Ihre Sprache filtern. Für Spanisch lautet das Label beispielsweise `lang-es`. +* Schauen Sie nach aktuellen Pull Requests für Ihre Sprache. Sie können die Pull Requests nach dem Label für Ihre Sprache filtern. Für Spanisch lautet das Label beispielsweise `lang-es`. * Sehen Sie diese Pull Requests durch (Review), schlagen Sie Änderungen vor, oder segnen Sie sie ab (Approval). Bei den Sprachen, die ich nicht spreche, warte ich, bis mehrere andere die Übersetzung durchgesehen haben, bevor ich den Pull Request merge. -!!! tip "Tipp" - Sie können Kommentare mit Änderungsvorschlägen zu vorhandenen Pull Requests hinzufügen. +/// tip | Tipp + +Sie können Kommentare mit Änderungsvorschlägen zu vorhandenen Pull Requests hinzufügen. + +Schauen Sie sich die Dokumentation an, wie man ein Review zu einem Pull Request hinzufügt, welches den PR absegnet oder Änderungen vorschlägt. - Schauen Sie sich die Dokumentation an, wie man ein Review zu einem Pull Request hinzufügt, welches den PR absegnet oder Änderungen vorschlägt. +/// -* Überprüfen Sie, ob es eine GitHub-Diskussion gibt, die Übersetzungen für Ihre Sprache koordiniert. Sie können sie abonnieren, und wenn ein neuer Pull Request zum Review vorliegt, wird der Diskussion automatisch ein Kommentar hinzugefügt. +* Überprüfen Sie, ob es eine GitHub-Diskussion gibt, die Übersetzungen für Ihre Sprache koordiniert. Sie können sie abonnieren, und wenn ein neuer Pull Request zum Review vorliegt, wird der Diskussion automatisch ein Kommentar hinzugefügt. * Wenn Sie Seiten übersetzen, fügen Sie einen einzelnen Pull Request pro übersetzter Seite hinzu. Dadurch wird es für andere viel einfacher, ihn zu durchzusehen. @@ -278,8 +303,11 @@ Angenommen, Sie möchten eine Seite für eine Sprache übersetzen, die bereits Im Spanischen lautet der Zwei-Buchstaben-Code `es`. Das Verzeichnis für spanische Übersetzungen befindet sich also unter `docs/es/`. -!!! tip "Tipp" - Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`. +/// tip | Tipp + +Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`. + +/// Führen Sie nun den Live-Server für die Dokumentation auf Spanisch aus: @@ -296,20 +324,23 @@ $ python ./scripts/docs.py live es -!!! tip "Tipp" - Alternativ können Sie die Schritte des Skripts auch manuell ausführen. +/// tip | Tipp + +Alternativ können Sie die Schritte des Skripts auch manuell ausführen. - Gehen Sie in das Sprachverzeichnis, für die spanischen Übersetzungen ist das `docs/es/`: +Gehen Sie in das Sprachverzeichnis, für die spanischen Übersetzungen ist das `docs/es/`: + +```console +$ cd docs/es/ +``` - ```console - $ cd docs/es/ - ``` +Dann führen Sie in dem Verzeichnis `mkdocs` aus: - Dann führen Sie in dem Verzeichnis `mkdocs` aus: +```console +$ mkdocs serve --dev-addr 8008 +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +/// Jetzt können Sie auf http://127.0.0.1:8008 gehen und Ihre Änderungen live sehen. @@ -329,8 +360,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip "Tipp" - Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`. +/// tip | Tipp + +Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`. + +/// Wenn Sie in Ihrem Browser nachsehen, werden Sie feststellen, dass die Dokumentation jetzt Ihren neuen Abschnitt anzeigt (die Info-Box oben ist verschwunden). 🎉 @@ -365,8 +399,11 @@ Obiges Kommando hat eine Datei `docs/ht/mkdocs.yml` mit einer Minimal-Konfigurat INHERIT: ../en/mkdocs.yml ``` -!!! tip "Tipp" - Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen. +/// tip | Tipp + +Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen. + +/// Das Kommando hat auch eine Dummy-Datei `docs/ht/index.md` für die Hauptseite erstellt. Sie können mit der Übersetzung dieser Datei beginnen. diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md index 5e1a4f109..97ad854e2 100644 --- a/docs/de/docs/deployment/concepts.md +++ b/docs/de/docs/deployment/concepts.md @@ -151,10 +151,13 @@ Und dennoch möchten Sie wahrscheinlich nicht, dass die Anwendung tot bleibt, we Aber in den Fällen mit wirklich schwerwiegenden Fehlern, die den laufenden **Prozess** zum Absturz bringen, benötigen Sie eine externe Komponente, die den Prozess **neu startet**, zumindest ein paar Mal ... -!!! tip "Tipp" - ... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. +/// tip | Tipp - Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten. +... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. + +Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten. + +/// Sie möchten wahrscheinlich, dass eine **externe Komponente** für den Neustart Ihrer Anwendung verantwortlich ist, da zu diesem Zeitpunkt dieselbe Anwendung mit Uvicorn und Python bereits abgestürzt ist und es daher nichts im selben Code derselben Anwendung gibt, was etwas dagegen tun kann. @@ -238,10 +241,13 @@ Hier sind einige mögliche Kombinationen und Strategien: * **Cloud-Dienste**, welche das für Sie erledigen * Der Cloud-Dienst wird wahrscheinlich **die Replikation für Sie übernehmen**. Er würde Sie möglicherweise **einen auszuführenden Prozess** oder ein **zu verwendendes Container-Image** definieren lassen, in jedem Fall wäre es höchstwahrscheinlich **ein einzelner Uvicorn-Prozess**, und der Cloud-Dienst wäre auch verantwortlich für die Replikation. -!!! tip "Tipp" - Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. +/// tip | Tipp + +Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. + +Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. - Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. +/// ## Schritte vor dem Start @@ -257,10 +263,13 @@ Und Sie müssen sicherstellen, dass es sich um einen einzelnen Prozess handelt, Natürlich gibt es Fälle, in denen es kein Problem darstellt, die Vorab-Schritte mehrmals auszuführen. In diesem Fall ist die Handhabung viel einfacher. -!!! tip "Tipp" - Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. +/// tip | Tipp - In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷 +Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. + +In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷 + +/// ### Beispiele für Strategien für Vorab-Schritte @@ -272,8 +281,11 @@ Hier sind einige mögliche Ideen: * Ein Bash-Skript, das die Vorab-Schritte ausführt und dann Ihre Anwendung startet * Sie benötigen immer noch eine Möglichkeit, *dieses* Bash-Skript zu starten/neu zu starten, Fehler zu erkennen, usw. -!!! tip "Tipp" - Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. +/// tip | Tipp + +Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +/// ## Ressourcennutzung diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md index b86cf92a4..a2734e068 100644 --- a/docs/de/docs/deployment/docker.md +++ b/docs/de/docs/deployment/docker.md @@ -4,8 +4,11 @@ Beim Deployment von FastAPI-Anwendungen besteht ein gängiger Ansatz darin, ein Die Verwendung von Linux-Containern bietet mehrere Vorteile, darunter **Sicherheit**, **Replizierbarkeit**, **Einfachheit** und andere. -!!! tip "Tipp" - Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). +/// tip | Tipp + +Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). + +///
Dockerfile-Vorschau 👀 @@ -130,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info - Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten. +/// info + +Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten. - Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇 +Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇 + +/// ### Den **FastAPI**-Code erstellen @@ -199,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Die Option `--no-cache-dir` weist `pip` an, die heruntergeladenen Pakete nicht lokal zu speichern, da dies nur benötigt wird, sollte `pip` erneut ausgeführt werden, um dieselben Pakete zu installieren, aber das ist beim Arbeiten mit Containern nicht der Fall. - !!! note "Hinweis" - Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun. + /// note | Hinweis + + Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun. + + /// Die Option `--upgrade` weist `pip` an, die Packages zu aktualisieren, wenn sie bereits installiert sind. @@ -222,8 +231,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Da das Programm unter `/code` gestartet wird und sich darin das Verzeichnis `./app` mit Ihrem Code befindet, kann **Uvicorn** `app` sehen und aus `app.main` **importieren**. -!!! tip "Tipp" - Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 +/// tip | Tipp + +Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 + +/// Sie sollten jetzt eine Verzeichnisstruktur wie diese haben: @@ -293,10 +305,13 @@ $ docker build -t myimage . -!!! tip "Tipp" - Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. +/// tip | Tipp + +Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. - In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`). +In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`). + +/// ### Den Docker-Container starten @@ -394,8 +409,11 @@ Wenn wir uns nur auf das **Containerimage** für eine FastAPI-Anwendung (und sp Es könnte sich um einen anderen Container handeln, zum Beispiel mit Traefik, welcher **HTTPS** und **automatischen** Erwerb von **Zertifikaten** handhabt. -!!! tip "Tipp" - Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. +/// tip | Tipp + +Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. + +/// Alternativ könnte HTTPS von einem Cloud-Anbieter als einer seiner Dienste gehandhabt werden (während die Anwendung weiterhin in einem Container ausgeführt wird). @@ -423,8 +441,11 @@ Bei der Verwendung von Containern ist normalerweise eine Komponente vorhanden, * Da diese Komponente die **Last** an Requests aufnehmen und diese (hoffentlich) **ausgewogen** auf die Worker verteilen würde, wird sie üblicherweise auch **Load Balancer** – Lastverteiler – genannt. -!!! tip "Tipp" - Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. +/// tip | Tipp + +Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. + +/// Und wenn Sie mit Containern arbeiten, verfügt das gleiche System, mit dem Sie diese starten und verwalten, bereits über interne Tools, um die **Netzwerkkommunikation** (z. B. HTTP-Requests) von diesem **Load Balancer** (das könnte auch ein **TLS-Terminierungsproxy** sein) zu den Containern mit Ihrer Anwendung weiterzuleiten. @@ -503,8 +524,11 @@ Wenn Sie Container (z. B. Docker, Kubernetes) verwenden, können Sie hauptsächl Wenn Sie **mehrere Container** haben, von denen wahrscheinlich jeder einen **einzelnen Prozess** ausführt (z. B. in einem **Kubernetes**-Cluster), dann möchten Sie wahrscheinlich einen **separaten Container** haben, welcher die Arbeit der **Vorab-Schritte** in einem einzelnen Container, mit einem einzelnenen Prozess ausführt, **bevor** die replizierten Workercontainer ausgeführt werden. -!!! info - Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein Init-Container. +/// info + +Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein Init-Container. + +/// Wenn es in Ihrem Anwendungsfall kein Problem darstellt, diese vorherigen Schritte **mehrmals parallel** auszuführen (z. B. wenn Sie keine Datenbankmigrationen ausführen, sondern nur prüfen, ob die Datenbank bereits bereit ist), können Sie sie auch einfach in jedem Container direkt vor dem Start des Hauptprozesses einfügen. @@ -520,8 +544,11 @@ Dieses Image wäre vor allem in den oben beschriebenen Situationen nützlich: [C * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning "Achtung" - Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). +/// warning | Achtung + +Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). + +/// Dieses Image verfügt über einen **Auto-Tuning**-Mechanismus, um die **Anzahl der Arbeitsprozesse** basierend auf den verfügbaren CPU-Kernen festzulegen. @@ -529,8 +556,11 @@ Es verfügt über **vernünftige Standardeinstellungen**, aber Sie können trotz Es unterstützt auch die Ausführung von **Vorab-Schritten vor dem Start** mit einem Skript. -!!! tip "Tipp" - Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: tiangolo/uvicorn-gunicorn-fastapi. +/// tip | Tipp + +Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### Anzahl der Prozesse auf dem offiziellen Docker-Image @@ -657,8 +687,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Führe den Befehl `uvicorn` aus und weise ihn an, das aus `app.main` importierte `app`-Objekt zu verwenden. -!!! tip "Tipp" - Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. +/// tip | Tipp + +Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. + +/// Eine **Docker-Phase** ist ein Teil eines `Dockerfile`s, welcher als **temporäres Containerimage** fungiert und nur zum Generieren einiger Dateien für die spätere Verwendung verwendet wird. diff --git a/docs/de/docs/deployment/https.md b/docs/de/docs/deployment/https.md index 3ebe59af2..630582995 100644 --- a/docs/de/docs/deployment/https.md +++ b/docs/de/docs/deployment/https.md @@ -4,8 +4,11 @@ Es ist leicht anzunehmen, dass HTTPS etwas ist, was einfach nur „aktiviert“ Aber es ist viel komplexer als das. -!!! tip "Tipp" - Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. +/// tip | Tipp + +Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. + +/// Um **die Grundlagen von HTTPS** aus Sicht des Benutzers zu erlernen, schauen Sie sich https://howhttps.works/ an. @@ -68,8 +71,11 @@ In dem oder den DNS-Server(n) würden Sie einen Eintrag (einen „`A record`“) Sie würden dies wahrscheinlich nur einmal tun, beim ersten Mal, wenn Sie alles einrichten. -!!! tip "Tipp" - Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. +/// tip | Tipp + +Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. + +/// ### DNS @@ -115,8 +121,11 @@ Danach verfügen der Client und der Server über eine **verschlüsselte TCP-Verb Und genau das ist **HTTPS**, es ist einfach **HTTP** innerhalb einer **sicheren TLS-Verbindung**, statt einer puren (unverschlüsselten) TCP-Verbindung. -!!! tip "Tipp" - Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. +/// tip | Tipp + +Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. + +/// ### HTTPS-Request diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md index c8e348aa1..fdb33f7fe 100644 --- a/docs/de/docs/deployment/manually.md +++ b/docs/de/docs/deployment/manually.md @@ -5,7 +5,7 @@ Das Wichtigste, was Sie zum Ausführen einer **FastAPI**-Anwendung auf einer ent Es gibt 3 Hauptalternativen: * Uvicorn: ein hochperformanter ASGI-Server. -* Hypercorn: ein ASGI-Server, der unter anderem mit HTTP/2 und Trio kompatibel ist. +* Hypercorn: ein ASGI-Server, der unter anderem mit HTTP/2 und Trio kompatibel ist. * Daphne: Der für Django Channels entwickelte ASGI-Server. ## Servermaschine und Serverprogramm @@ -22,75 +22,89 @@ Wenn man sich auf die entfernte Maschine bezieht, wird sie üblicherweise als ** Sie können einen ASGI-kompatiblen Server installieren mit: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools. +* Uvicorn, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools. -
+
+ +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +
- ---> 100% - ``` +/// tip | Tipp -
+Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. - !!! tip "Tipp" - Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. +Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt. - Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt. +/// -=== "Hypercorn" +//// - * Hypercorn, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. +//// tab | Hypercorn -
+* Hypercorn, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. - ```console - $ pip install hypercorn +
+ +```console +$ pip install hypercorn + +---> 100% +``` - ---> 100% - ``` +
-
+... oder jeden anderen ASGI-Server. - ... oder jeden anderen ASGI-Server. +//// ## Das Serverprogramm ausführen Anschließend können Sie Ihre Anwendung auf die gleiche Weise ausführen, wie Sie es in den Tutorials getan haben, jedoch ohne die Option `--reload`, z. B.: -=== "Uvicorn" +//// tab | Uvicorn -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
+ +//// -=== "Hypercorn" +//// tab | Hypercorn -
+
+ +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning | Achtung -
+Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. -!!! warning "Achtung" - Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. +Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw. - Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw. +Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden. - Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden. +/// ## Hypercorn mit Trio diff --git a/docs/de/docs/deployment/server-workers.md b/docs/de/docs/deployment/server-workers.md index 04d48dc6c..5cd282b4b 100644 --- a/docs/de/docs/deployment/server-workers.md +++ b/docs/de/docs/deployment/server-workers.md @@ -17,10 +17,13 @@ Wie Sie im vorherigen Kapitel über [Deployment-Konzepte](concepts.md){.internal Hier zeige ich Ihnen, wie Sie **Gunicorn** mit **Uvicorn Workerprozessen** verwenden. -!!! info - Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. +/// info - Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen. +Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen. + +/// ## Gunicorn mit Uvicorn-Workern diff --git a/docs/de/docs/deployment/versions.md b/docs/de/docs/deployment/versions.md index d71aded22..5b8c69754 100644 --- a/docs/de/docs/deployment/versions.md +++ b/docs/de/docs/deployment/versions.md @@ -42,8 +42,11 @@ Gemäß den Konventionen zur semantischen Versionierung könnte jede Version unt FastAPI folgt auch der Konvention, dass jede „PATCH“-Versionsänderung für Bugfixes und abwärtskompatible Änderungen gedacht ist. -!!! tip "Tipp" - Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. +/// tip | Tipp + +Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. + +/// Sie sollten also in der Lage sein, eine Version wie folgt anzupinnen: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Nicht abwärtskompatible Änderungen und neue Funktionen werden in „MINOR“-Versionen hinzugefügt. -!!! tip "Tipp" - „MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. +/// tip | Tipp + +„MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. + +/// ## Upgrade der FastAPI-Versionen diff --git a/docs/de/docs/external-links.md b/docs/de/docs/external-links.md deleted file mode 100644 index d97f4d39c..000000000 --- a/docs/de/docs/external-links.md +++ /dev/null @@ -1,36 +0,0 @@ -# Externe Links und Artikel - -**FastAPI** hat eine großartige Community, die ständig wächst. - -Es gibt viele Beiträge, Artikel, Tools und Projekte zum Thema **FastAPI**. - -Hier ist eine unvollständige Liste einiger davon. - -!!! tip "Tipp" - Wenn Sie einen Artikel, ein Projekt, ein Tool oder irgendetwas im Zusammenhang mit **FastAPI** haben, was hier noch nicht aufgeführt ist, erstellen Sie einen Pull Request und fügen Sie es hinzu. - -!!! note "Hinweis Deutsche Übersetzung" - Die folgenden Überschriften und Links werden aus einer anderen Datei gelesen und sind daher nicht ins Deutsche übersetzt. - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projekte - -Die neuesten GitHub-Projekte zum Thema `fastapi`: - -
-
diff --git a/docs/de/docs/fastapi-people.md b/docs/de/docs/fastapi-people.md deleted file mode 100644 index 522a4bce5..000000000 --- a/docs/de/docs/fastapi-people.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI Leute - -FastAPI hat eine großartige Gemeinschaft, die Menschen mit unterschiedlichstem Hintergrund willkommen heißt. - -## Erfinder - Betreuer - -Hey! 👋 - -Das bin ich: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Ich bin der Erfinder und Betreuer von **FastAPI**. Sie können mehr darüber in [FastAPI helfen – Hilfe erhalten – Mit dem Autor vernetzen](help-fastapi.md#mit-dem-autor-vernetzen){.internal-link target=_blank} erfahren. - -... Aber hier möchte ich Ihnen die Gemeinschaft vorstellen. - ---- - -**FastAPI** erhält eine Menge Unterstützung aus der Gemeinschaft. Und ich möchte ihre Beiträge hervorheben. - -Das sind die Menschen, die: - -* [Anderen bei Fragen auf GitHub helfen](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. -* [Pull Requests erstellen](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank}. -* Pull Requests überprüfen (Review), [besonders wichtig für Übersetzungen](contributing.md#ubersetzungen){.internal-link target=_blank}. - -Eine Runde Applaus für sie. 👏 🙇 - -## Aktivste Benutzer im letzten Monat - -Hier die Benutzer, die im letzten Monat am meisten [anderen mit Fragen auf Github](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank} geholfen haben. ☕ - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
Fragen beantwortet: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Experten - -Hier die **FastAPI-Experten**. 🤓 - -Das sind die Benutzer, die *insgesamt* [anderen am meisten mit Fragen auf GitHub geholfen haben](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. - -Sie haben bewiesen, dass sie Experten sind, weil sie vielen anderen geholfen haben. ✨ - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
Fragen beantwortet: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Top-Mitwirkende - -Hier sind die **Top-Mitwirkenden**. 👷 - -Diese Benutzer haben [die meisten Pull Requests erstellt](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank} welche *gemerged* wurden. - -Sie haben Quellcode, Dokumentation, Übersetzungen, usw. beigesteuert. 📦 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Es gibt viele andere Mitwirkende (mehr als hundert), Sie können sie alle auf der FastAPI GitHub Contributors-Seite sehen. 👷 - -## Top-Rezensenten - -Diese Benutzer sind die **Top-Rezensenten**. 🕵️ - -### Rezensionen für Übersetzungen - -Ich spreche nur ein paar Sprachen (und nicht sehr gut 😅). Daher bestätigen Reviewer [**Übersetzungen der Dokumentation**](contributing.md#ubersetzungen){.internal-link target=_blank}. Ohne sie gäbe es keine Dokumentation in mehreren anderen Sprachen. - ---- - -Die **Top-Reviewer** 🕵️ haben die meisten Pull Requests von anderen überprüft und stellen die Qualität des Codes, der Dokumentation und insbesondere der **Übersetzungen** sicher. - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsoren - -Dies sind die **Sponsoren**. 😎 - -Sie unterstützen meine Arbeit an **FastAPI** (und andere), hauptsächlich durch GitHub-Sponsoren. - -### Gold Sponsoren - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -### Silber Sponsoren - -{% if sponsors %} -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if people %} -{% if people.sponsors_50 %} - -### Bronze Sponsoren - -
-{% for user in people.sponsors_50 %} - - -{% endfor %} - -
- -{% endif %} -{% endif %} - -### Individuelle Sponsoren - -{% if people %} -
-{% for user in people.sponsors %} - - -{% endfor %} - -
-{% endif %} - -## Über diese Daten - technische Details - -Der Hauptzweck dieser Seite ist es zu zeigen, wie die Gemeinschaft anderen hilft. - -Das beinhaltet auch Hilfe, die normalerweise weniger sichtbar und in vielen Fällen mühsamer ist, wie, anderen bei Problemen zu helfen und Pull Requests mit Übersetzungen zu überprüfen. - -Diese Daten werden jeden Monat berechnet, Sie können den Quellcode hier lesen. - -Hier weise ich auch auf Beiträge von Sponsoren hin. - -Ich behalte mir auch das Recht vor, den Algorithmus, die Abschnitte, die Schwellenwerte usw. zu aktualisieren (nur für den Fall 🤷). diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index 76aad9f16..8fdf42622 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Merkmale ## FastAPI Merkmale @@ -11,7 +6,7 @@ hide: ### Basiert auf offenen Standards -* OpenAPI für die Erstellung von APIs, inklusive Deklarationen von Pfad-Operationen, Parametern, Body-Anfragen, Sicherheit, usw. +* OpenAPI für die Erstellung von APIs, inklusive Deklarationen von Pfad-Operationen, Parametern, Requestbodys, Sicherheit, usw. * Automatische Dokumentation der Datenmodelle mit JSON Schema (da OpenAPI selbst auf JSON Schema basiert). * Um diese Standards herum entworfen, nach sorgfältigem Studium. Statt einer nachträglichen Schicht darüber. * Dies ermöglicht auch automatische **Client-Code-Generierung** in vielen Sprachen. @@ -69,10 +64,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` bedeutet: +/// info + +`**second_user_data` bedeutet: + +Nimm die Schlüssel-Wert-Paare des `second_user_data` Dicts und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`. - Nimm die Schlüssel-Wert-Paare des `second_user_data` Dicts und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`. +/// ### Editor Unterstützung diff --git a/docs/de/docs/help-fastapi.md b/docs/de/docs/help-fastapi.md index bdc07e55f..0b9c52316 100644 --- a/docs/de/docs/help-fastapi.md +++ b/docs/de/docs/help-fastapi.md @@ -25,13 +25,13 @@ Sie können den (unregelmäßig erscheinenden) [**FastAPI and Friends**-Newslett ## **FastAPI** auf GitHub einen Stern geben -Sie können FastAPI auf GitHub „starren“ (durch Klicken auf den Stern-Button oben rechts): https://github.com/tiangolo/fastapi. ⭐️ +Sie können FastAPI auf GitHub „starren“ (durch Klicken auf den Stern-Button oben rechts): https://github.com/fastapi/fastapi. ⭐️ Durch das Hinzufügen eines Sterns können andere Benutzer es leichter finden und sehen, dass es für andere bereits nützlich war. ## Das GitHub-Repository auf Releases beobachten -Sie können FastAPI in GitHub beobachten (Klicken Sie oben rechts auf den Button „watch“): https://github.com/tiangolo/fastapi. 👀 +Sie können FastAPI in GitHub beobachten (Klicken Sie oben rechts auf den Button „watch“): https://github.com/fastapi/fastapi. 👀 Dort können Sie „Releases only“ auswählen. @@ -58,7 +58,7 @@ Insbesondere: ## Über **FastAPI** tweeten -Tweeten Sie über **FastAPI** und teilen Sie mir und anderen mit, warum es Ihnen gefällt. 🎉 +Tweeten Sie über **FastAPI** und teilen Sie mir und anderen mit, warum es Ihnen gefällt. 🎉 Ich höre gerne, wie **FastAPI** verwendet wird, was Ihnen daran gefallen hat, in welchem Projekt/Unternehmen Sie es verwenden, usw. @@ -72,8 +72,8 @@ Ich höre gerne, wie **FastAPI** verwendet wird, was Ihnen daran gefallen hat, i Sie können versuchen, anderen bei ihren Fragen zu helfen: -* GitHub-Diskussionen -* GitHub-Issues +* GitHub-Diskussionen +* GitHub-Issues In vielen Fällen kennen Sie möglicherweise bereits die Antwort auf diese Fragen. 🤓 @@ -124,7 +124,7 @@ Wenn die Person antwortet, besteht eine hohe Chance, dass Sie ihr Problem gelös ## Das GitHub-Repository beobachten -Sie können FastAPI auf GitHub „beobachten“ (Klicken Sie oben rechts auf die Schaltfläche „watch“): https://github.com/tiangolo/fastapi. 👀 +Sie können FastAPI auf GitHub „beobachten“ (Klicken Sie oben rechts auf die Schaltfläche „watch“): https://github.com/fastapi/fastapi. 👀 Wenn Sie dann „Watching“ statt „Releases only“ auswählen, erhalten Sie Benachrichtigungen, wenn jemand ein neues Issue eröffnet oder eine neue Frage stellt. Sie können auch spezifizieren, dass Sie nur über neue Issues, Diskussionen, PRs, usw. benachrichtigt werden möchten. @@ -132,7 +132,7 @@ Dann können Sie versuchen, bei der Lösung solcher Fragen zu helfen. ## Fragen stellen -Sie können im GitHub-Repository eine neue Frage erstellen, zum Beispiel: +Sie können im GitHub-Repository eine neue Frage erstellen, zum Beispiel: * Stellen Sie eine **Frage** oder bitten Sie um Hilfe mit einem **Problem**. * Schlagen Sie eine neue **Funktionalität** vor. @@ -169,12 +169,15 @@ Und wenn es irgendeinen anderen Stil- oder Konsistenz-Bedarf gibt, bitte ich dir * Schreiben Sie dann einen **Kommentar** und berichten, dass Sie das getan haben. So weiß ich, dass Sie ihn wirklich überprüft haben. -!!! info - Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen. +/// info - Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅 +Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen. - Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓 +Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅 + +Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓 + +/// * Wenn der PR irgendwie vereinfacht werden kann, fragen Sie ruhig danach, aber seien Sie nicht zu wählerisch, es gibt viele subjektive Standpunkte (und ich habe auch meinen eigenen 🙈), also ist es besser, wenn man sich auf die wesentlichen Dinge konzentriert. @@ -195,7 +198,7 @@ Und wenn es irgendeinen anderen Stil- oder Konsistenz-Bedarf gibt, bitte ich dir Sie können zum Quellcode mit Pull Requests [beitragen](contributing.md){.internal-link target=_blank}, zum Beispiel: * Um einen Tippfehler zu beheben, den Sie in der Dokumentation gefunden haben. -* Um einen Artikel, ein Video oder einen Podcast über FastAPI zu teilen, den Sie erstellt oder gefunden haben, indem Sie diese Datei bearbeiten. +* Um einen Artikel, ein Video oder einen Podcast über FastAPI zu teilen, den Sie erstellt oder gefunden haben, indem Sie diese Datei bearbeiten. * Stellen Sie sicher, dass Sie Ihren Link am Anfang des entsprechenden Abschnitts einfügen. * Um zu helfen, [die Dokumentation in Ihre Sprache zu übersetzen](contributing.md#ubersetzungen){.internal-link target=_blank}. * Sie können auch dabei helfen, die von anderen erstellten Übersetzungen zu überprüfen (Review). @@ -225,10 +228,13 @@ Wenn Sie mir dabei helfen können, **helfen Sie mir, FastAPI am Laufen zu erhalt Treten Sie dem 👥 Discord-Chatserver 👥 bei und treffen Sie sich mit anderen Mitgliedern der FastAPI-Community. -!!! tip "Tipp" - Wenn Sie Fragen haben, stellen Sie sie bei GitHub Diskussionen, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. +/// tip | Tipp + +Wenn Sie Fragen haben, stellen Sie sie bei GitHub Diskussionen, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. + +Nutzen Sie den Chat nur für andere allgemeine Gespräche. - Nutzen Sie den Chat nur für andere allgemeine Gespräche. +/// ### Den Chat nicht für Fragen verwenden diff --git a/docs/de/docs/help/index.md b/docs/de/docs/help/index.md deleted file mode 100644 index 8fdc4a049..000000000 --- a/docs/de/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Hilfe - -Helfen und Hilfe erhalten, beitragen, mitmachen. 🤝 diff --git a/docs/de/docs/history-design-future.md b/docs/de/docs/history-design-future.md index 22597b1f5..ee917608e 100644 --- a/docs/de/docs/history-design-future.md +++ b/docs/de/docs/history-design-future.md @@ -1,6 +1,6 @@ # Geschichte, Design und Zukunft -Vor einiger Zeit fragte ein **FastAPI**-Benutzer: +Vor einiger Zeit fragte ein **FastAPI**-Benutzer: > Was ist die Geschichte dieses Projekts? Es scheint, als wäre es in ein paar Wochen aus dem Nichts zu etwas Großartigem geworden [...] diff --git a/docs/de/docs/how-to/conditional-openapi.md b/docs/de/docs/how-to/conditional-openapi.md index 7f277bb88..a0a4983bb 100644 --- a/docs/de/docs/how-to/conditional-openapi.md +++ b/docs/de/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ Sie können problemlos dieselben Pydantic-Einstellungen verwenden, um Ihre gener Zum Beispiel: ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` Hier deklarieren wir die Einstellung `openapi_url` mit dem gleichen Defaultwert `"/openapi.json"`. diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md index c18091efd..1ee72d205 100644 --- a/docs/de/docs/how-to/configure-swagger-ui.md +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # Swagger-Oberfläche konfigurieren -Sie können einige zusätzliche Parameter der Swagger-Oberfläche konfigurieren. +Sie können einige zusätzliche Parameter der Swagger-Oberfläche konfigurieren. Um diese zu konfigurieren, übergeben Sie das Argument `swagger_ui_parameters` beim Erstellen des `FastAPI()`-App-Objekts oder an die Funktion `get_swagger_ui_html()`. @@ -18,9 +18,7 @@ Ohne Änderung der Einstellungen ist die Syntaxhervorhebung standardmäßig akti Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` setzen: -```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ... und dann zeigt die Swagger-Oberfläche die Syntaxhervorhebung nicht mehr an: @@ -30,9 +28,7 @@ Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` set Auf die gleiche Weise könnten Sie das Theme der Syntaxhervorhebung mit dem Schlüssel `syntaxHighlight.theme` festlegen (beachten Sie, dass er einen Punkt in der Mitte hat): -```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} Obige Konfiguration würde das Theme für die Farbe der Syntaxhervorhebung ändern: @@ -44,21 +40,17 @@ FastAPI enthält einige Defaultkonfigurationsparameter, die für die meisten Anw Es umfasst die folgenden Defaultkonfigurationen: -```Python -{!../../../fastapi/openapi/docs.py[ln:7-23]!} -``` +{* ../../fastapi/openapi/docs.py ln[7:23] *} Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_parameters` einen anderen Wert festlegen. Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellungen an `swagger_ui_parameters` übergeben: -```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## Andere Parameter der Swagger-Oberfläche -Um alle anderen möglichen Konfigurationen zu sehen, die Sie verwenden können, lesen Sie die offizielle Dokumentation für die Parameter der Swagger-Oberfläche. +Um alle anderen möglichen Konfigurationen zu sehen, die Sie verwenden können, lesen Sie die offizielle Dokumentation für die Parameter der Swagger-Oberfläche. ## JavaScript-basierte Einstellungen diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index 991eaf269..a292be69b 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -19,7 +19,7 @@ Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivier Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: ```Python hl_lines="8" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` ### Die benutzerdefinierten Dokumentationen hinzufügen @@ -37,22 +37,25 @@ Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Sei Und genau so für ReDoc ... ```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` -!!! tip "Tipp" - Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. +/// tip | Tipp - Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. +Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. - Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. +Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. + +Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. + +/// ### Eine *Pfadoperation* erstellen, um es zu testen Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: ```Python hl_lines="36-38" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` ### Es ausprobieren @@ -96,8 +99,8 @@ Sie können wahrscheinlich mit der rechten Maustaste auf jeden Link klicken und **Swagger UI** verwendet folgende Dateien: -* `swagger-ui-bundle.js` -* `swagger-ui.css` +* `swagger-ui-bundle.js` +* `swagger-ui.css` Und **ReDoc** verwendet diese Datei: @@ -122,7 +125,7 @@ Danach könnte Ihre Dateistruktur wie folgt aussehen: * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. ```Python hl_lines="7 11" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Die statischen Dateien testen @@ -156,7 +159,7 @@ Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt d Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: ```Python hl_lines="9" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen @@ -174,22 +177,25 @@ Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um di Und genau so für ReDoc ... ```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` -!!! tip "Tipp" - Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. +/// tip | Tipp + +Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. + +Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. - Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. +Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. - Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. +/// ### Eine *Pfadoperation* erstellen, um statische Dateien zu testen Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: ```Python hl_lines="39-41" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Benutzeroberfläche, mit statischen Dateien, testen diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md index b51a20bfc..ef71d96dc 100644 --- a/docs/de/docs/how-to/custom-request-and-route.md +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -6,10 +6,13 @@ Das kann insbesondere eine gute Alternative zur Logik in einer Middleware sein. Wenn Sie beispielsweise den Requestbody lesen oder manipulieren möchten, bevor er von Ihrer Anwendung verarbeitet wird. -!!! danger "Gefahr" - Dies ist eine „fortgeschrittene“ Funktion. +/// danger | Gefahr - Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen. +Dies ist eine „fortgeschrittene“ Funktion. + +Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen. + +/// ## Anwendungsfälle @@ -27,8 +30,11 @@ Und eine `APIRoute`-Unterklasse zur Verwendung dieser benutzerdefinierten Reques ### Eine benutzerdefinierte `GzipRequest`-Klasse erstellen -!!! tip "Tipp" - Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. +/// tip | Tipp + +Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. + +/// Zuerst erstellen wir eine `GzipRequest`-Klasse, welche die Methode `Request.body()` überschreibt, um den Body bei Vorhandensein eines entsprechenden Headers zu dekomprimieren. @@ -37,7 +43,7 @@ Wenn der Header kein `gzip` enthält, wird nicht versucht, den Body zu dekomprim Auf diese Weise kann dieselbe Routenklasse gzip-komprimierte oder unkomprimierte Requests verarbeiten. ```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` ### Eine benutzerdefinierte `GzipRoute`-Klasse erstellen @@ -51,19 +57,22 @@ Diese Methode gibt eine Funktion zurück. Und diese Funktion empfängt einen Req Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` zu erstellen. ```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` -!!! note "Technische Details" - Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält. +/// note | Technische Details - Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt. +Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält. - Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation. +Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt. - Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen. +Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation. - Um mehr über den `Request` zu erfahren, schauen Sie sich Starlettes Dokumentation zu Requests an. +Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen. + +Um mehr über den `Request` zu erfahren, schauen Sie sich Starlettes Dokumentation zu Requests an. + +/// Das Einzige, was die von `GzipRequest.get_route_handler` zurückgegebene Funktion anders macht, ist die Konvertierung von `Request` in ein `GzipRequest`. @@ -75,23 +84,26 @@ Aufgrund unserer Änderungen in `GzipRequest.body` wird der Requestbody jedoch b ## Zugriff auf den Requestbody in einem Exceptionhandler -!!! tip "Tipp" - Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). +/// tip | Tipp + +Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). + +Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird. - Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird. +/// Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf den Requestbody zuzugreifen. Alles, was wir tun müssen, ist, den Request innerhalb eines `try`/`except`-Blocks zu handhaben: ```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im Gültigkeitsbereich, sodass wir den Requestbody lesen und bei der Fehlerbehandlung verwenden können: ```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` ## Benutzerdefinierte `APIRoute`-Klasse in einem Router @@ -99,11 +111,11 @@ Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im G Sie können auch den Parameter `route_class` eines `APIRouter` festlegen: ```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` In diesem Beispiel verwenden die *Pfadoperationen* unter dem `router` die benutzerdefinierte `TimedRoute`-Klasse und haben in der Response einen zusätzlichen `X-Response-Time`-Header mit der Zeit, die zum Generieren der Response benötigt wurde: ```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md index 2fbfa13e5..c895fb860 100644 --- a/docs/de/docs/how-to/extending-openapi.md +++ b/docs/de/docs/how-to/extending-openapi.md @@ -27,8 +27,11 @@ Und diese Funktion `get_openapi()` erhält als Parameter: * `description`: Die Beschreibung Ihrer API. Dies kann Markdown enthalten und wird in der Dokumentation angezeigt. * `routes`: Eine Liste von Routen, dies sind alle registrierten *Pfadoperationen*. Sie stammen von `app.routes`. -!!! info - Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt. +/// info + +Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt. + +/// ## Überschreiben der Standardeinstellungen @@ -41,7 +44,7 @@ Fügen wir beispielsweise Strawberry 🍓 * Mit Dokumentation für FastAPI * Ariadne - * Mit Dokumentation für Starlette (welche auch für FastAPI gilt) + * Mit Dokumentation für FastAPI * Tartiflette * Mit Tartiflette ASGI, für ASGI-Integration * Graphene @@ -33,7 +36,7 @@ Abhängig von Ihrem Anwendungsfall bevorzugen Sie vielleicht eine andere Bibliot Hier ist eine kleine Vorschau, wie Sie Strawberry mit FastAPI integrieren können: ```Python hl_lines="3 22 25-26" -{!../../../docs_src/graphql/tutorial001.py!} +{!../../docs_src/graphql/tutorial001.py!} ``` Weitere Informationen zu Strawberry finden Sie in der Strawberry-Dokumentation. @@ -46,8 +49,11 @@ Frühere Versionen von Starlette enthielten eine `GraphQLApp`-Klasse zur Integra Das wurde von Starlette deprecated, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu starlette-graphene3 **migrieren**, welches denselben Anwendungsfall abdeckt und über eine **fast identische Schnittstelle** verfügt. -!!! tip "Tipp" - Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich Strawberry anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. +/// tip | Tipp + +Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich Strawberry anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. + +/// ## Mehr darüber lernen diff --git a/docs/de/docs/how-to/index.md b/docs/de/docs/how-to/index.md index 101829ff8..84a178fc8 100644 --- a/docs/de/docs/how-to/index.md +++ b/docs/de/docs/how-to/index.md @@ -6,5 +6,8 @@ Die meisten dieser Ideen sind mehr oder weniger **unabhängig**, und in den meis Wenn etwas für Ihr Projekt interessant und nützlich erscheint, lesen Sie es, andernfalls überspringen Sie es einfach. -!!! tip "Tipp" - Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. +/// tip | Tipp + +Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md index 000bcf633..974341dd2 100644 --- a/docs/de/docs/how-to/separate-openapi-schemas.md +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -10,111 +10,123 @@ Sehen wir uns an, wie das funktioniert und wie Sie es bei Bedarf ändern können Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} +```Python hl_lines="7" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - # Code unterhalb weggelassen 👇 - ``` +# Code unterhalb weggelassen 👇 +``` -
- 👀 Vollständige Dateivorschau +
+👀 Vollständige Dateivorschau - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` -
+
-=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} +//// tab | Python 3.9+ - # Code unterhalb weggelassen 👇 - ``` +```Python hl_lines="9" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} -
- 👀 Vollständige Dateivorschau +# Code unterhalb weggelassen 👇 +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +
+👀 Vollständige Dateivorschau -
+```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -=== "Python 3.8+" +
- ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} +//// - # Code unterhalb weggelassen 👇 - ``` +//// tab | Python 3.8+ -
- 👀 Vollständige Dateivorschau +```Python hl_lines="9" +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +# Code unterhalb weggelassen 👇 +``` -
+
+👀 Vollständige Dateivorschau + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +
+ +//// ### Modell für Eingabe Wenn Sie dieses Modell wie hier als Eingabe verwenden: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - ```Python hl_lines="14" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} +# Code unterhalb weggelassen 👇 +``` - # Code unterhalb weggelassen 👇 - ``` +
+👀 Vollständige Dateivorschau -
- 👀 Vollständige Dateivorschau +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +
-
+//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} +```Python hl_lines="16" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - # Code unterhalb weggelassen 👇 - ``` +# Code unterhalb weggelassen 👇 +``` -
- 👀 Vollständige Dateivorschau +
+👀 Vollständige Dateivorschau - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -
+
-=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} +//// tab | Python 3.8+ - # Code unterhalb weggelassen 👇 - ``` +```Python hl_lines="16" +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} -
- 👀 Vollständige Dateivorschau +# Code unterhalb weggelassen 👇 +``` - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +
+👀 Vollständige Dateivorschau -
+```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +
+ +//// ... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat. @@ -130,23 +142,29 @@ Sie können überprüfen, dass das Feld `description` in der Dokumentation kein Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` +```Python hl_lines="21" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +//// ... dann, weil `description` einen Defaultwert hat, wird es, wenn Sie für dieses Feld **nichts zurückgeben**, immer noch diesen **Defaultwert** haben. @@ -199,26 +217,35 @@ Der Hauptanwendungsfall hierfür besteht wahrscheinlich darin, dass Sie das mal In diesem Fall können Sie diese Funktion in **FastAPI** mit dem Parameter `separate_input_output_schemas=False` deaktivieren. -!!! info - Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓 +/// info + +Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓 + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="12" +{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} - ``` +//// ### Gleiches Schema für Eingabe- und Ausgabemodelle in der Dokumentation diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index cf5a2b2d6..411c8e969 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI +

FastAPI

@@ -5,11 +11,11 @@ FastAPI 🛠️, ↕ 🎭, ⏩ 💡, ⏩ 📟, 🔜 🏭

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,7 +29,7 @@ **🧾**: https://fastapi.tiangolo.com -**ℹ 📟**: https://github.com/tiangolo/fastapi +**ℹ 📟**: https://github.com/fastapi/fastapi --- @@ -31,7 +37,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ 🔑 ⚒: -* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#performance). +* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#_15). * **⏩ 📟**: 📈 🚅 🛠️ ⚒ 🔃 2️⃣0️⃣0️⃣ 💯 3️⃣0️⃣0️⃣ 💯. * * **👩‍❤‍👨 🐛**: 📉 🔃 4️⃣0️⃣ 💯 🗿 (👩‍💻) 📉 ❌. * * **🏋️**: 👑 👨‍🎨 🐕‍🦺. 🛠️ 🌐. 🌘 🕰 🛠️. @@ -63,7 +69,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ "_[...] 👤 ⚙️ **FastAPI** 📚 👫 📆. [...] 👤 🤙 📆 ⚙️ ⚫️ 🌐 👇 🏉 **⚗ 🐕‍🦺 🤸‍♂**. 👫 💆‍♂ 🛠️ 🔘 🐚 **🖥** 🏬 & **📠** 🏬._" -

🧿 🇵🇰 - 🤸‍♂ (🇦🇪)
+
🧿 🇵🇰 - 🤸‍♂ (🇦🇪)
--- @@ -87,7 +93,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ "_🤙, ⚫️❔ 👆 ✔️ 🏗 👀 💎 💠 & 🇵🇱. 📚 🌌, ⚫️ ⚫️❔ 👤 💚 **🤗** - ⚫️ 🤙 😍 👀 👱 🏗 👈._" -
✡ 🗄 - 🤗 👼 (🇦🇪)
+
✡ 🗄 - 🤗 👼 (🇦🇪)
--- @@ -127,7 +133,7 @@ FastAPI 🧍 🔛 ⌚ 🐘:
```console -$ pip install fastapi +$ pip install "fastapi[standard]" ---> 100% ``` @@ -445,8 +451,7 @@ item: Item ⚙️ Pydantic: -* ujson - ⏩ 🎻 "🎻". -* email_validator - 📧 🔬. +* email-validator - 📧 🔬. ⚙️ 💃: @@ -455,12 +460,12 @@ item: Item * python-multipart - ✔ 🚥 👆 💚 🐕‍🦺 📨 "✍", ⏮️ `request.form()`. * itsdangerous - ✔ `SessionMiddleware` 🐕‍🦺. * pyyaml - ✔ 💃 `SchemaGenerator` 🐕‍🦺 (👆 🎲 🚫 💪 ⚫️ ⏮️ FastAPI). -* ujson - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`. ⚙️ FastAPI / 💃: * uvicorn - 💽 👈 📐 & 🍦 👆 🈸. * orjson - ✔ 🚥 👆 💚 ⚙️ `ORJSONResponse`. +* ujson - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`. 👆 💪 ❎ 🌐 👫 ⏮️ `pip install "fastapi[all]"`. diff --git a/docs/em/docs/project-generation.md b/docs/em/docs/project-generation.md index ae959e1d5..ef6a21821 100644 --- a/docs/em/docs/project-generation.md +++ b/docs/em/docs/project-generation.md @@ -14,7 +14,7 @@ * ☁ 🐝 📳 🛠️. * **☁ ✍** 🛠️ & 🛠️ 🇧🇿 🛠️. * **🏭 🔜** 🐍 🕸 💽 ⚙️ Uvicorn & 🐁. -* 🐍 **FastAPI** 👩‍💻: +* 🐍 **FastAPI** 👩‍💻: * **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). * **🏋️**: 👑 👨‍🎨 🐕‍🦺. 🛠️ 🌐. 🌘 🕰 🛠️. * **⏩**: 🔧 ⏩ ⚙️ & 💡. 🌘 🕰 👂 🩺. diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md index b8f61a113..d2af23bb9 100644 --- a/docs/em/docs/python-types.md +++ b/docs/em/docs/python-types.md @@ -12,15 +12,18 @@ ✋️ 🚥 👆 🙅 ⚙️ **FastAPI**, 👆 🔜 💰 ⚪️➡️ 🏫 🍖 🔃 👫. -!!! note - 🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃. +/// note + +🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃. + +/// ## 🎯 ➡️ ▶️ ⏮️ 🙅 🖼: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` 🤙 👉 📋 🔢: @@ -36,7 +39,7 @@ John Doe * 🔢 👫 ⏮️ 🚀 🖕. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### ✍ ⚫️ @@ -80,7 +83,7 @@ John Doe 👈 "🆎 🔑": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` 👈 🚫 🎏 📣 🔢 💲 💖 🔜 ⏮️: @@ -110,7 +113,7 @@ John Doe ✅ 👉 🔢, ⚫️ ⏪ ✔️ 🆎 🔑: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` ↩️ 👨‍🎨 💭 🆎 🔢, 👆 🚫 🕴 🤚 🛠️, 👆 🤚 ❌ ✅: @@ -120,7 +123,7 @@ John Doe 🔜 👆 💭 👈 👆 ✔️ 🔧 ⚫️, 🗜 `age` 🎻 ⏮️ `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 📣 🆎 @@ -141,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 💊 🆎 ⏮️ 🆎 🔢 @@ -164,45 +167,55 @@ John Doe 🖼, ➡️ 🔬 🔢 `list` `str`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): +⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` - ``` Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. - 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. +🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`. - 🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`. +📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: - 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. +📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. - 🆎, 🚮 `list`. +🆎, 🚮 `list`. - 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: +📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` -!!! info - 👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢". +//// - 👉 💼, `str` 🆎 🔢 🚶‍♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛). +/// info + +👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢". + +👉 💼, `str` 🆎 🔢 🚶‍♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛). + +/// 👈 ⛓: "🔢 `items` `list`, & 🔠 🏬 👉 📇 `str`". -!!! tip - 🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️. +/// tip + +🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️. + +/// 🔨 👈, 👆 👨‍🎨 💪 🚚 🐕‍🦺 ⏪ 🏭 🏬 ⚪️➡️ 📇: @@ -218,17 +231,21 @@ John Doe 👆 🔜 🎏 📣 `tuple`Ⓜ & `set`Ⓜ: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// 👉 ⛓: @@ -243,17 +260,21 @@ John Doe 🥈 🆎 🔢 💲 `dict`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// 👉 ⛓: @@ -269,17 +290,21 @@ John Doe 🐍 3️⃣.1️⃣0️⃣ 📤 **🎛 ❕** 🌐❔ 👆 💪 🚮 💪 🆎 👽 ⏸ ⏸ (`|`). -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +//// 👯‍♂️ 💼 👉 ⛓ 👈 `item` 💪 `int` ⚖️ `str`. @@ -290,7 +315,7 @@ John Doe 🐍 3️⃣.6️⃣ & 🔛 (✅ 🐍 3️⃣.1️⃣0️⃣) 👆 💪 📣 ⚫️ 🏭 & ⚙️ `Optional` ⚪️➡️ `typing` 🕹. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` ⚙️ `Optional[str]` ↩️ `str` 🔜 ➡️ 👨‍🎨 ℹ 👆 🔍 ❌ 🌐❔ 👆 💪 🤔 👈 💲 🕧 `str`, 🕐❔ ⚫️ 💪 🤙 `None` 💁‍♂️. @@ -299,23 +324,29 @@ John Doe 👉 ⛓ 👈 🐍 3️⃣.1️⃣0️⃣, 👆 💪 ⚙️ `Something | None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// -=== "🐍 3️⃣.6️⃣ & 🔛 - 🎛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - 🎛 - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// #### ⚙️ `Union` ⚖️ `Optional` @@ -333,7 +364,7 @@ John Doe 🖼, ➡️ ✊ 👉 🔢: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` 🔢 `name` 🔬 `Optional[str]`, ✋️ ⚫️ **🚫 📦**, 👆 🚫🔜 🤙 🔢 🍵 🔢: @@ -351,7 +382,7 @@ say_hi(name=None) # This works, None is valid 🎉 👍 📰, 🕐 👆 🔛 🐍 3️⃣.1️⃣0️⃣ 👆 🏆 🚫 ✔️ 😟 🔃 👈, 👆 🔜 💪 🎯 ⚙️ `|` 🔬 🇪🇺 🆎: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` & ⤴️ 👆 🏆 🚫 ✔️ 😟 🔃 📛 💖 `Optional` & `Union`. 👶 @@ -360,47 +391,53 @@ say_hi(name=None) # This works, None is valid 🎉 👉 🆎 👈 ✊ 🆎 🔢 ⬜ 🗜 🤙 **💊 🆎** ⚖️ **💊**, 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...& 🎏. - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...& 🎏. +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): +👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: + & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: - * `Union` - * `Optional` - * ...& 🎏. +* `Union` +* `Optional` +* ...& 🎏. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - * `list` - * `tuple` - * `set` - * `dict` +👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): - & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: +* `list` +* `tuple` +* `set` +* `dict` - * `Union` - * `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣) - * ...& 🎏. + & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: - 🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎. +* `Union` +* `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣) +* ...& 🎏. + +🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎. + +//// ### 🎓 🆎 @@ -409,13 +446,13 @@ say_hi(name=None) # This works, None is valid 🎉 ➡️ 💬 👆 ✔️ 🎓 `Person`, ⏮️ 📛: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` ⤴️ 👆 💪 📣 🔢 🆎 `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` & ⤴️, 🔄, 👆 🤚 🌐 👨‍🎨 🐕‍🦺: @@ -436,33 +473,45 @@ say_hi(name=None) # This works, None is valid 🎉 🖼 ⚪️➡️ 🛂 Pydantic 🩺: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +/// info -!!! info - 💡 🌖 🔃 Pydantic, ✅ 🚮 🩺. +💡 🌖 🔃 Pydantic, ✅ 🚮 🩺. + +/// **FastAPI** 🌐 ⚓️ 🔛 Pydantic. 👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩‍💻 🦮](tutorial/index.md){.internal-link target=_blank}. -!!! tip - Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. +/// tip + +Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. + +/// ## 🆎 🔑 **FastAPI** @@ -486,5 +535,8 @@ say_hi(name=None) # This works, None is valid 🎉 ⚠ 👜 👈 ⚙️ 🐩 🐍 🆎, 👁 🥉 (↩️ ❎ 🌖 🎓, 👨‍🎨, ♒️), **FastAPI** 🔜 📚 👷 👆. -!!! info - 🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`. +/// info + +🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`. + +/// diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md index e28ead415..0f4585ebe 100644 --- a/docs/em/docs/tutorial/background-tasks.md +++ b/docs/em/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ 🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶‍♀️ ⚫️ 👈 🔢. @@ -34,7 +34,7 @@ & ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## 🚮 🖥 📋 @@ -42,7 +42,7 @@ 🔘 👆 *➡ 🛠️ 🔢*, 🚶‍♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩‍🔬 `.add_task()`: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` 📨 ❌: @@ -57,17 +57,21 @@ **FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯‍♂️ & 🏃 🖥 ⏮️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../docs_src/background_tasks/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="11 13 20 23" +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} +``` - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// 👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨. diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index c30bba106..68f506f27 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ **FastAPI** 🚚 🏪 🧰 📊 👆 🈸 ⏪ 🚧 🌐 💪. -!!! info - 🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗. +/// info + +🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗. + +/// ## 🖼 📁 📊 @@ -26,16 +29,19 @@ │   └── admin.py ``` -!!! tip - 📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁. +/// tip + +📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁. - 👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣. +👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣. - 🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖: +🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * `app` 📁 🔌 🌐. & ⚫️ ✔️ 🛁 📁 `app/__init__.py`, ⚫️ "🐍 📦" (🗃 "🐍 🕹"): `app`. * ⚫️ 🔌 `app/main.py` 📁. ⚫️ 🔘 🐍 📦 (📁 ⏮️ 📁 `__init__.py`), ⚫️ "🕹" 👈 📦: `app.main`. @@ -80,7 +86,7 @@ 👆 🗄 ⚫️ & ✍ "👐" 🎏 🌌 👆 🔜 ⏮️ 🎓 `FastAPI`: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### *➡ 🛠️* ⏮️ `APIRouter` @@ -90,7 +96,7 @@ ⚙️ ⚫️ 🎏 🌌 👆 🔜 ⚙️ `FastAPI` 🎓: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` 👆 💪 💭 `APIRouter` "🐩 `FastAPI`" 🎓. @@ -99,8 +105,11 @@ 🌐 🎏 `parameters`, `responses`, `dependencies`, `tags`, ♒️. -!!! tip - 👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚. +/// tip + +👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚. + +/// 👥 🔜 🔌 👉 `APIRouter` 👑 `FastAPI` 📱, ✋️ 🥇, ➡️ ✅ 🔗 & ➕1️⃣ `APIRouter`. @@ -113,13 +122,16 @@ 👥 🔜 🔜 ⚙️ 🙅 🔗 ✍ 🛃 `X-Token` 🎚: ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!../../../docs_src/bigger_applications/app/dependencies.py!} +{!../../docs_src/bigger_applications/app/dependencies.py!} ``` -!!! tip - 👥 ⚙️ 💭 🎚 📉 👉 🖼. +/// tip + +👥 ⚙️ 💭 🎚 📉 👉 🖼. + +✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂‍♂ 🚙](security/index.md){.internal-link target=_blank}. - ✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂‍♂ 🚙](./security/index.md){.internal-link target=_blank}. +/// ## ➕1️⃣ 🕹 ⏮️ `APIRouter` @@ -144,7 +156,7 @@ , ↩️ ❎ 🌐 👈 🔠 *➡ 🛠️*, 👥 💪 🚮 ⚫️ `APIRouter`. ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` ➡ 🔠 *➡ 🛠️* ✔️ ▶️ ⏮️ `/`, 💖: @@ -163,8 +175,11 @@ async def read_item(item_id: str): & 👥 💪 🚮 📇 `dependencies` 👈 🔜 🚮 🌐 *➡ 🛠️* 📻 & 🔜 🛠️/❎ 🔠 📨 ⚒ 👫. -!!! tip - 🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨‍🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅‍♂ 💲 🔜 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. +/// tip + +🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨‍🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅‍♂ 💲 🔜 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. + +/// 🔚 🏁 👈 🏬 ➡ 🔜: @@ -181,11 +196,17 @@ async def read_item(item_id: str): * 📻 🔗 🛠️ 🥇, ⤴️ [`dependencies` 👨‍🎨](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, & ⤴️ 😐 🔢 🔗. * 👆 💪 🚮 [`Security` 🔗 ⏮️ `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. -!!! tip - ✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫. +/// tip + +✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫. + +/// + +/// check -!!! check - `prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎. +`prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎. + +/// ### 🗄 🔗 @@ -196,13 +217,16 @@ async def read_item(item_id: str): 👥 ⚙️ ⚖ 🗄 ⏮️ `..` 🔗: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### ❔ ⚖ 🗄 👷 -!!! tip - 🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛. +/// tip + +🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛. + +/// 👁 ❣ `.`, 💖: @@ -266,13 +290,16 @@ that 🔜 ⛓: ✋️ 👥 💪 🚮 _🌅_ `tags` 👈 🔜 ✔ 🎯 *➡ 🛠️*, & ➕ `responses` 🎯 👈 *➡ 🛠️*: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip - 👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`. +/// tip + +👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`. - & ⚫️ 🔜 ✔️ 👯‍♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`. + & ⚫️ 🔜 ✔️ 👯‍♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`. + +/// ## 👑 `FastAPI` @@ -291,7 +318,7 @@ that 🔜 ⛓: & 👥 💪 📣 [🌐 🔗](dependencies/global-dependencies.md){.internal-link target=_blank} 👈 🔜 🌀 ⏮️ 🔗 🔠 `APIRouter`: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 🗄 `APIRouter` @@ -299,7 +326,7 @@ that 🔜 ⛓: 🔜 👥 🗄 🎏 🔁 👈 ✔️ `APIRouter`Ⓜ: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 📁 `app/routers/users.py` & `app/routers/items.py` 🔁 👈 🍕 🎏 🐍 📦 `app`, 👥 💪 ⚙️ 👁 ❣ `.` 🗄 👫 ⚙️ "⚖ 🗄". @@ -328,20 +355,23 @@ from .routers import items, users from app.routers import items, users ``` -!!! info - 🥇 ⏬ "⚖ 🗄": +/// info + +🥇 ⏬ "⚖ 🗄": - ```Python - from .routers import items, users - ``` +```Python +from .routers import items, users +``` - 🥈 ⏬ "🎆 🗄": +🥈 ⏬ "🎆 🗄": + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹. - 💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹. +/// ### ❎ 📛 💥 @@ -361,7 +391,7 @@ from .routers.users import router , 💪 ⚙️ 👯‍♂️ 👫 🎏 📁, 👥 🗄 🔁 🔗: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 🔌 `APIRouter`Ⓜ `users` & `items` @@ -369,29 +399,38 @@ from .routers.users import router 🔜, ➡️ 🔌 `router`Ⓜ ⚪️➡️ 🔁 `users` & `items`: ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`. +/// info - & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`. +`users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`. + + & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`. + +/// ⏮️ `app.include_router()` 👥 💪 🚮 🔠 `APIRouter` 👑 `FastAPI` 🈸. ⚫️ 🔜 🔌 🌐 🛣 ⚪️➡️ 👈 📻 🍕 ⚫️. -!!! note "📡 ℹ" - ⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`. +/// note | 📡 ℹ + +⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`. + +, ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱. + +/// - , ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱. +/// check -!!! check - 👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻. +👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻. - 👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴. +👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴. - ⚫️ 🏆 🚫 📉 🎭. 👶 +⚫️ 🏆 🚫 📉 🎭. 👶 + +/// ### 🔌 `APIRouter` ⏮️ 🛃 `prefix`, `tags`, `responses`, & `dependencies` @@ -402,7 +441,7 @@ from .routers.users import router 👉 🖼 ⚫️ 🔜 💎 🙅. ✋️ ➡️ 💬 👈 ↩️ ⚫️ 💰 ⏮️ 🎏 🏗 🏢, 👥 🚫🔜 🔀 ⚫️ & 🚮 `prefix`, `dependencies`, `tags`, ♒️. 🔗 `APIRouter`: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` ✋️ 👥 💚 ⚒ 🛃 `prefix` 🕐❔ ✅ `APIRouter` 👈 🌐 🚮 *➡ 🛠️* ▶️ ⏮️ `/admin`, 👥 💚 🔐 ⚫️ ⏮️ `dependencies` 👥 ⏪ ✔️ 👉 🏗, & 👥 💚 🔌 `tags` & `responses`. @@ -410,7 +449,7 @@ from .routers.users import router 👥 💪 📣 🌐 👈 🍵 ✔️ 🔀 ⏮️ `APIRouter` 🚶‍♀️ 👈 🔢 `app.include_router()`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 👈 🌌, ⏮️ `APIRouter` 🔜 🚧 ⚗, 👥 💪 💰 👈 🎏 `app/internal/admin.py` 📁 ⏮️ 🎏 🏗 🏢. @@ -433,21 +472,24 @@ from .routers.users import router 📥 👥 ⚫️... 🎦 👈 👥 💪 🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` & ⚫️ 🔜 👷 ☑, 👯‍♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`. -!!! info "📶 📡 ℹ" - **🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**. +/// info | 📶 📡 ℹ + +**🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**. + +--- - --- + `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸. - `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸. +👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩‍💻 🔢. - 👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩‍💻 🔢. +👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗. - 👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗. +/// ## ✅ 🏧 🛠️ 🩺 diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md index 9f2c914f4..be39b4a9a 100644 --- a/docs/em/docs/tutorial/body-fields.md +++ b/docs/em/docs/tutorial/body-fields.md @@ -6,50 +6,67 @@ 🥇, 👆 ✔️ 🗄 ⚫️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -!!! warning - 👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️). +```Python hl_lines="2" +{!> ../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +/// warning + +👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️). + +/// ## 📣 🏷 🔢 👆 💪 ⤴️ ⚙️ `Field` ⏮️ 🏷 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="9-12" +{!> ../../docs_src/body_fields/tutorial001_py310.py!} +``` - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// `Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️. -!!! note "📡 ℹ" - 🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓. +/// note | 📡 ℹ - & Pydantic `Field` 📨 👐 `FieldInfo` 👍. +🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓. - `Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓. + & Pydantic `Field` 📨 👐 `FieldInfo` 👍. - 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +`Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓. -!!! tip - 👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`. +💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. + +/// + +/// tip + +👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`. + +/// ## 🚮 ➕ ℹ @@ -57,9 +74,12 @@ 👆 🔜 💡 🌅 🔃 ❎ ➕ ℹ ⏪ 🩺, 🕐❔ 🏫 📣 🖼. -!!! warning - ➕ 🔑 🚶‍♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸. - 👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗. +/// warning + +➕ 🔑 🚶‍♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸. +👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗. + +/// ## 🌃 diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md index 9ada7dee1..2e20c83f9 100644 --- a/docs/em/docs/tutorial/body-multiple-params.md +++ b/docs/em/docs/tutorial/body-multiple-params.md @@ -8,20 +8,27 @@ & 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +```Python hl_lines="19-21" +{!> ../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="17-19" +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +//// -!!! note - 👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲. +/// note + +👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲. + +/// ## 💗 💪 🔢 @@ -38,17 +45,21 @@ ✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +```Python hl_lines="22" +{!> ../../docs_src/body_multiple_params/tutorial002.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="20" +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` + +//// 👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷). @@ -69,9 +80,11 @@ } ``` -!!! note - 👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`. +/// note +👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`. + +/// **FastAPI** 🔜 🏧 🛠️ ⚪️➡️ 📨, 👈 🔢 `item` 📨 ⚫️ 🎯 🎚 & 🎏 `user`. @@ -87,17 +100,21 @@ ✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../docs_src/body_multiple_params/tutorial003.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="20" +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` + +//// 👉 💼, **FastAPI** 🔜 ⌛ 💪 💖: @@ -137,20 +154,27 @@ q: str | None = None 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="27" +{!> ../../docs_src/body_multiple_params/tutorial004.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +```Python hl_lines="26" +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="26" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +`Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪. -!!! info - `Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪. +/// ## ⏯ 👁 💪 🔢 @@ -166,17 +190,21 @@ item: Item = Body(embed=True) : -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="17" +{!> ../../docs_src/body_multiple_params/tutorial005.py!} +``` + +//// - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="15" +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +//// 👉 💼 **FastAPI** 🔜 ⌛ 💪 💖: diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index c941fa08a..3b56b7a07 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ 👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="12" +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +//// 👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇. @@ -31,7 +35,7 @@ ✋️ 🐍 ⏬ ⏭ 3️⃣.9️⃣ (3️⃣.6️⃣ & 🔛), 👆 🥇 💪 🗄 `List` ⚪️➡️ 🐩 🐍 `typing` 🕹: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### 📣 `list` ⏮️ 🆎 🔢 @@ -61,23 +65,29 @@ my_list: List[str] , 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻": -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="12" +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// ## ⚒ 🆎 @@ -87,23 +97,29 @@ my_list: List[str] ⤴️ 👥 💪 📣 `tags` ⚒ 🎻: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 14" +{!> ../../docs_src/body_nested_models/tutorial003.py!} +``` - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="12" +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// ⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬. @@ -125,45 +141,57 @@ my_list: List[str] 🖼, 👥 💪 🔬 `Image` 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9-11" +{!> ../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="9-11" +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7-9" +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} +``` - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// ### ⚙️ 📊 🆎 & ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial004.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// 👉 🔜 ⛓ 👈 **FastAPI** 🔜 ⌛ 💪 🎏: @@ -196,23 +224,29 @@ my_list: List[str] 🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="4 10" +{!> ../../docs_src/body_nested_models/tutorial005.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +```Python hl_lines="4 10" +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="2 8" +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} +``` - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +//// 🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅. @@ -220,23 +254,29 @@ my_list: List[str] 👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// 👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖: @@ -264,33 +304,45 @@ my_list: List[str] } ``` -!!! info - 👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚. +/// info + +👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚. + +/// ## 🙇 🐦 🏷 👆 💪 🔬 🎲 🙇 🐦 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9 14 20 23 27" +{!> ../../docs_src/body_nested_models/tutorial007.py!} +``` + +//// - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="9 14 20 23 27" +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 12 18 21 25" +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ -!!! info - 👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ +/// ## 💪 😁 📇 @@ -308,17 +360,21 @@ images: list[Image] : -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15" +{!> ../../docs_src/body_nested_models/tutorial008.py!} +``` - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} +``` + +//// ## 👨‍🎨 🐕‍🦺 🌐 @@ -348,26 +404,33 @@ images: list[Image] 👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../docs_src/body_nested_models/tutorial009.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +✔️ 🤯 👈 🎻 🕴 🐕‍🦺 `str` 🔑. -!!! tip - ✔️ 🤯 👈 🎻 🕴 🐕‍🦺 `str` 🔑. +✋️ Pydantic ✔️ 🏧 💽 🛠️. - ✋️ Pydantic ✔️ 🏧 💽 🛠️. +👉 ⛓ 👈, ✋️ 👆 🛠️ 👩‍💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫. - 👉 ⛓ 👈, ✋️ 👆 🛠️ 👩‍💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫. + & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲. - & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md index 98058ab52..7e2fbfaf7 100644 --- a/docs/em/docs/tutorial/body-updates.md +++ b/docs/em/docs/tutorial/body-updates.md @@ -6,23 +6,7 @@ 👆 💪 ⚙️ `jsonable_encoder` 🗜 🔢 💽 📊 👈 💪 🏪 🎻 (✅ ⏮️ ☁ 💽). 🖼, 🏭 `datetime` `str`. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="28-33" - {!> ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +{* ../../docs_src/body_updates/tutorial001.py hl[30:35] *} `PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽. @@ -48,14 +32,17 @@ 👉 ⛓ 👈 👆 💪 📨 🕴 💽 👈 👆 💚 ℹ, 🍂 🎂 🐣. -!!! Note - `PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`. +/// note - & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ. +`PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`. - 👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫. + & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ. - ✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️. +👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫. + +✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️. + +/// ### ⚙️ Pydantic `exclude_unset` 🔢 @@ -67,23 +54,7 @@ ⤴️ 👆 💪 ⚙️ 👉 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ (📨 📨), 🚫 🔢 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### ⚙️ Pydantic `update` 🔢 @@ -91,23 +62,7 @@ 💖 `stored_item_model.copy(update=update_data)`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 🍕 ℹ 🌃 @@ -124,32 +79,22 @@ * 🖊 💽 👆 💽. * 📨 ℹ 🏷. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *} -=== "🐍 3️⃣.9️⃣ & 🔛" +/// tip - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼. - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +/// -!!! tip - 👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️. +/// note - ✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼. +👀 👈 🔢 🏷 ✔. -!!! note - 👀 👈 🔢 🏷 ✔. +, 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`). - , 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`). +🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}. - 🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}. +/// diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index db850162a..3468fc512 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -8,28 +8,35 @@ 📣 **📨** 💪, 👆 ⚙️ Pydantic 🏷 ⏮️ 🌐 👫 🏋️ & 💰. -!!! info - 📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`. +/// info - 📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕‍🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼. +📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`. - ⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕‍🦺 ⚫️. +📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕‍🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼. + +⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕‍🦺 ⚫️. + +/// ## 🗄 Pydantic `BaseModel` 🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="4" +{!> ../../docs_src/body/tutorial001.py!} +``` + +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="2" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// ## ✍ 👆 💽 🏷 @@ -37,17 +44,21 @@ ⚙️ 🐩 🐍 🆎 🌐 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="7-11" +{!> ../../docs_src/body/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="5-9" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` + +//// 🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦. @@ -75,17 +86,21 @@ 🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="18" +{!> ../../docs_src/body/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="16" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` + +//// ...& 📣 🚮 🆎 🏷 👆 ✍, `Item`. @@ -134,32 +149,39 @@ -!!! tip - 🚥 👆 ⚙️ 🗒 👆 👨‍🎨, 👆 💪 ⚙️ Pydantic 🗒 📁. +/// tip + +🚥 👆 ⚙️ 🗒 👆 👨‍🎨, 👆 💪 ⚙️ Pydantic 🗒 📁. - ⚫️ 📉 👨‍🎨 🐕‍🦺 Pydantic 🏷, ⏮️: +⚫️ 📉 👨‍🎨 🐕‍🦺 Pydantic 🏷, ⏮️: - * 🚘-🛠️ - * 🆎 ✅ - * 🛠️ - * 🔎 - * 🔬 +* 🚘-🛠️ +* 🆎 ✅ +* 🛠️ +* 🔎 +* 🔬 + +/// ## ⚙️ 🏷 🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="21" +{!> ../../docs_src/body/tutorial002.py!} +``` + +//// - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="19" +{!> ../../docs_src/body/tutorial002_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// ## 📨 💪 ➕ ➡ 🔢 @@ -167,17 +189,21 @@ **FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="17-18" +{!> ../../docs_src/body/tutorial003.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +```Python hl_lines="15-16" +{!> ../../docs_src/body/tutorial003_py310.py!} +``` + +//// ## 📨 💪 ➕ ➡ ➕ 🔢 🔢 @@ -185,17 +211,21 @@ **FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../docs_src/body/tutorial004.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../docs_src/body/tutorial004_py310.py!} +``` + +//// 🔢 🔢 🔜 🤔 ⏩: @@ -203,11 +233,14 @@ * 🚥 🔢 **⭐ 🆎** (💖 `int`, `float`, `str`, `bool`, ♒️) ⚫️ 🔜 🔬 **🔢** 🔢. * 🚥 🔢 📣 🆎 **Pydantic 🏷**, ⚫️ 🔜 🔬 📨 **💪**. -!!! note - FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. +/// note + +FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. + + `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. - `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. +/// ## 🍵 Pydantic -🚥 👆 🚫 💚 ⚙️ Pydantic 🏷, 👆 💪 ⚙️ **💪** 🔢. 👀 🩺 [💪 - 💗 🔢: ⭐ 💲 💪](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. +🚥 👆 🚫 💚 ⚙️ Pydantic 🏷, 👆 💪 ⚙️ **💪** 🔢. 👀 🩺 [💪 - 💗 🔢: ⭐ 💲 💪](body-multiple-params.md#_2){.internal-link target=_blank}. diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md index 47f4a62f5..5126eab0a 100644 --- a/docs/em/docs/tutorial/cookie-params.md +++ b/docs/em/docs/tutorial/cookie-params.md @@ -6,17 +6,21 @@ 🥇 🗄 `Cookie`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// ## 📣 `Cookie` 🔢 @@ -24,25 +28,35 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +/// note | 📡 ℹ - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +`Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// -!!! note "📡 ℹ" - `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. +/// info - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. -!!! info - 📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md index 8c5e33ed7..801d66fdd 100644 --- a/docs/em/docs/tutorial/cors.md +++ b/docs/em/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 🎯 🇺🇸🔍 🎚 ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` 🔢 🔢 ⚙️ `CORSMiddleware` 🛠️ 🚫 🔢, 👆 🔜 💪 🎯 🛠️ 🎯 🇨🇳, 👩‍🔬, ⚖️ 🎚, ✔ 🖥 ✔ ⚙️ 👫 ✖️-🆔 🔑. @@ -78,7 +78,10 @@ 🌖 ℹ 🔃 , ✅ 🦎 ⚜ 🧾. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`. +/// note | 📡 ℹ - **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. + +/// diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md index c7c11b5ce..9320370d6 100644 --- a/docs/em/docs/tutorial/debugging.md +++ b/docs/em/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ 👆 FastAPI 🈸, 🗄 & 🏃 `uvicorn` 🔗: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### 🔃 `__name__ == "__main__"` @@ -74,8 +74,11 @@ from myapp import app 🔜 🚫 🛠️. -!!! info - 🌅 ℹ, ✅ 🛂 🐍 🩺. +/// info + +🌅 ℹ, ✅ 🛂 🐍 🩺. + +/// ## 🏃 👆 📟 ⏮️ 👆 🕹 diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md index e2d2686d3..3e58d506c 100644 --- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,21 @@ ⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// ✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*. @@ -79,45 +83,57 @@ fluffy = Cat(name="Mr Fluffy") ⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="11-15" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="9-13" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// 💸 🙋 `__init__` 👩‍🔬 ⚙️ ✍ 👐 🎓: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// ...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="6" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗. @@ -133,17 +149,21 @@ fluffy = Cat(name="Mr Fluffy") 🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// **FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶‍♀️ 🔢 `commons` 👆 🔢. @@ -183,17 +203,21 @@ commons = Depends(CommonQueryParams) ...: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial003.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial003_py310.py!} +``` + +//// ✋️ 📣 🆎 💡 👈 🌌 👆 👨‍🎨 🔜 💭 ⚫️❔ 🔜 🚶‍♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️: @@ -227,21 +251,28 @@ commons: CommonQueryParams = Depends() 🎏 🖼 🔜 ⤴️ 👀 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial004.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial004_py310.py!} +``` + +//// ...& **FastAPI** 🔜 💭 ⚫️❔. -!!! tip - 🚥 👈 😑 🌅 😨 🌘 👍, 🤷‍♂ ⚫️, 👆 🚫 *💪* ⚫️. +/// tip + +🚥 👈 😑 🌅 😨 🌘 👍, 🤷‍♂ ⚫️, 👆 🚫 *💪* ⚫️. + +⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁. - ⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁. +/// diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 4d54b91c7..cd36ad100 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -15,22 +15,28 @@ ⚫️ 🔜 `list` `Depends()`: ```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` 👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. -!!! tip - 👨‍🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌. +/// tip - ⚙️ 👉 `dependencies` *➡ 🛠️ 👨‍🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨‍🎨/🏭 ❌. +👨‍🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌. - ⚫️ 💪 ℹ ❎ 😨 🆕 👩‍💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃. +⚙️ 👉 `dependencies` *➡ 🛠️ 👨‍🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨‍🎨/🏭 ❌. -!!! info - 👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`. +⚫️ 💪 ℹ ❎ 😨 🆕 👩‍💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃. - ✋️ 🎰 💼, 🕐❔ 🛠️ 💂‍♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂‍♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}. +/// + +/// info + +👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`. + +✋️ 🎰 💼, 🕐❔ 🛠️ 💂‍♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂‍♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}. + +/// ## 🔗 ❌ & 📨 💲 @@ -41,7 +47,7 @@ 👫 💪 📣 📨 📄 (💖 🎚) ⚖️ 🎏 🎧-🔗: ```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 🤚 ⚠ @@ -49,7 +55,7 @@ 👫 🔗 💪 `raise` ⚠, 🎏 😐 🔗: ```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 📨 💲 @@ -59,7 +65,7 @@ , 👆 💪 🏤-⚙️ 😐 🔗 (👈 📨 💲) 👆 ⏪ ⚙️ 👱 🙆, & ✋️ 💲 🏆 🚫 ⚙️, 🔗 🔜 🛠️: ```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ## 🔗 👪 *➡ 🛠️* diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index 9617667f4..2896be39d 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ FastAPI 🐕‍🦺 🔗 👈 🔑 👨‍💼. +/// note | 📡 ℹ + +👉 👷 👏 🐍 🔑 👨‍💼. - **FastAPI** ⚙️ 👫 🔘 🏆 👉. +**FastAPI** ⚙️ 👫 🔘 🏆 👉. + +/// ## 🔗 ⏮️ `yield` & `HTTPException` @@ -99,7 +111,7 @@ FastAPI 🐕‍🦺 🔗 👈 🏗 🎓 ⏮️ 2️⃣ 👩‍🔬: `__enter__()` & `__exit__()`. @@ -201,19 +225,22 @@ with open("./somefile.txt") as f: `with` ⚖️ `async with` 📄 🔘 🔗 🔢: ```Python hl_lines="1-9 13" -{!../../../docs_src/dependencies/tutorial010.py!} +{!../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip - ➕1️⃣ 🌌 ✍ 🔑 👨‍💼 ⏮️: +/// tip + +➕1️⃣ 🌌 ✍ 🔑 👨‍💼 ⏮️: + +* `@contextlib.contextmanager` ⚖️ +* `@contextlib.asynccontextmanager` - * `@contextlib.contextmanager` ⚖️ - * `@contextlib.asynccontextmanager` +⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`. - ⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`. +👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`. - 👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`. +✋️ 👆 🚫 ✔️ ⚙️ 👨‍🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫). - ✋️ 👆 🚫 ✔️ ⚙️ 👨‍🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫). +FastAPI 🔜 ⚫️ 👆 🔘. - FastAPI 🔜 ⚫️ 👆 🔘. +/// diff --git a/docs/em/docs/tutorial/dependencies/global-dependencies.md b/docs/em/docs/tutorial/dependencies/global-dependencies.md index 81759d0e8..bb69e78a8 100644 --- a/docs/em/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/global-dependencies.md @@ -7,7 +7,7 @@ 👈 💼, 👫 🔜 ✔ 🌐 *➡ 🛠️* 🈸: ```Python hl_lines="15" -{!../../../docs_src/dependencies/tutorial012.py!} +{!../../docs_src/dependencies/tutorial012.py!} ``` & 🌐 💭 📄 🔃 [❎ `dependencies` *➡ 🛠️ 👨‍🎨*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} ✔, ✋️ 👉 💼, 🌐 *➡ 🛠️* 📱. diff --git a/docs/em/docs/tutorial/dependencies/index.md b/docs/em/docs/tutorial/dependencies/index.md index ffd38d716..b029b85b7 100644 --- a/docs/em/docs/tutorial/dependencies/index.md +++ b/docs/em/docs/tutorial/dependencies/index.md @@ -31,17 +31,21 @@ ⚫️ 🔢 👈 💪 ✊ 🌐 🎏 🔢 👈 *➡ 🛠️ 🔢* 💪 ✊: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="8-11" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +```Python hl_lines="6-7" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// 👈 ⚫️. @@ -63,33 +67,41 @@ ### 🗄 `Depends` -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// ### 📣 🔗, "⚓️" 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️. ⏮️ 👆 *➡ 🛠️ 🔢* 🔢, ⚙️ `Depends` ⏮️ 🆕 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15 20" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="11 16" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 👐 👆 ⚙️ `Depends` 🔢 👆 🔢 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️, `Depends` 👷 👄 🎏. @@ -99,8 +111,11 @@ & 👈 🔢 ✊ 🔢 🎏 🌌 👈 *➡ 🛠️ 🔢* . -!!! tip - 👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃. +/// tip + +👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃. + +/// 🕐❔ 🆕 📨 🛬, **FastAPI** 🔜 ✊ 💅: @@ -121,10 +136,13 @@ common_parameters --> read_users 👉 🌌 👆 ✍ 🔗 📟 🕐 & **FastAPI** ✊ 💅 🤙 ⚫️ 👆 *➡ 🛠️*. -!!! check - 👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶‍♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏. +/// check - 👆 🚶‍♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂. +👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶‍♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏. + +👆 🚶‍♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂. + +/// ## `async` ⚖️ 🚫 `async` @@ -136,8 +154,11 @@ common_parameters --> read_users ⚫️ 🚫 🤔. **FastAPI** 🔜 💭 ⚫️❔. -!!! note - 🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺. +/// note + +🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺. + +/// ## 🛠️ ⏮️ 🗄 diff --git a/docs/em/docs/tutorial/dependencies/sub-dependencies.md b/docs/em/docs/tutorial/dependencies/sub-dependencies.md index 454ff5129..a1e7be134 100644 --- a/docs/em/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/sub-dependencies.md @@ -10,17 +10,21 @@ 👆 💪 ✍ 🥇 🔗 ("☑") 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +```Python hl_lines="8-9" +{!> ../../docs_src/dependencies/tutorial005.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="6-7" +{!> ../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +//// ⚫️ 📣 📦 🔢 🔢 `q` `str`, & ⤴️ ⚫️ 📨 ⚫️. @@ -30,17 +34,21 @@ ⤴️ 👆 💪 ✍ ➕1️⃣ 🔗 🔢 ("☑") 👈 🎏 🕰 📣 🔗 🚮 👍 (⚫️ "⚓️" 💁‍♂️): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +```Python hl_lines="13" +{!> ../../docs_src/dependencies/tutorial005.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="11" +{!> ../../docs_src/dependencies/tutorial005_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +//// ➡️ 🎯 🔛 🔢 📣: @@ -53,22 +61,29 @@ ⤴️ 👥 💪 ⚙️ 🔗 ⏮️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +```Python hl_lines="22" +{!> ../../docs_src/dependencies/tutorial005.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`. -!!! info - 👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`. +✋️ **FastAPI** 🔜 💭 👈 ⚫️ ✔️ ❎ `query_extractor` 🥇, 🚶‍♀️ 🏁 👈 `query_or_cookie_extractor` ⏪ 🤙 ⚫️. - ✋️ **FastAPI** 🔜 💭 👈 ⚫️ ✔️ ❎ `query_extractor` 🥇, 🚶‍♀️ 🏁 👈 `query_or_cookie_extractor` ⏪ 🤙 ⚫️. +/// ```mermaid graph TB @@ -102,9 +117,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False ✋️, ⚫️ 📶 🏋️, & ✔ 👆 📣 🎲 🙇 🐦 🔗 "📊" (🌲). -!!! tip - 🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼. +/// tip + +🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼. + +✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂‍♂**. - ✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂‍♂**. + & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆. - & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆. +/// diff --git a/docs/em/docs/tutorial/encoder.md b/docs/em/docs/tutorial/encoder.md index 75ca3824d..21419ef21 100644 --- a/docs/em/docs/tutorial/encoder.md +++ b/docs/em/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ ⚫️ 📨 🎚, 💖 Pydantic 🏷, & 📨 🎻 🔗 ⏬: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +```Python hl_lines="5 22" +{!> ../../docs_src/encoder/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="4 21" +{!> ../../docs_src/encoder/tutorial001_py310.py!} +``` + +//// 👉 🖼, ⚫️ 🔜 🗜 Pydantic 🏷 `dict`, & `datetime` `str`. @@ -38,5 +42,8 @@ ⚫️ 🚫 📨 ⭕ `str` ⚗ 💽 🎻 📁 (🎻). ⚫️ 📨 🐍 🐩 💽 📊 (✅ `dict`) ⏮️ 💲 & 🎧-💲 👈 🌐 🔗 ⏮️ 🎻. -!!! note - `jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐. +/// note + +`jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐. + +/// diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index 54a186f12..1d473bd93 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -55,28 +55,36 @@ 📥 🖼 *➡ 🛠️* ⏮️ 🔢 ⚙️ 🔛 🆎. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../docs_src/extra_data_types/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1 2 11-15" +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// 🗒 👈 🔢 🔘 🔢 ✔️ 👫 🐠 💽 🆎, & 👆 💪, 🖼, 🎭 😐 📅 🎭, 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="17-18" +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 7cb54a963..4fdf196e8 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -8,26 +8,33 @@ * **🔢 🏷** 🔜 🚫 ✔️ 🔐. * **💽 🏷** 🔜 🎲 💪 ✔️ #️⃣ 🔐. -!!! danger - 🙅 🏪 👩‍💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔. +/// danger - 🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂‍♂ 📃](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +🙅 🏪 👩‍💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔. + +🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂‍♂ 📃](security/simple-oauth2.md#_4){.internal-link target=_blank}. + +/// ## 💗 🏷 📥 🏢 💭 ❔ 🏷 💪 👀 💖 ⏮️ 👫 🔐 🏑 & 🥉 🌐❔ 👫 ⚙️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../docs_src/extra_models/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// ### 🔃 `**user_in.dict()` @@ -139,8 +146,11 @@ UserInDB( ) ``` -!!! warning - 🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂‍♂. +/// warning + +🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂‍♂. + +/// ## 📉 ❎ @@ -158,17 +168,21 @@ UserInDB( 👈 🌌, 👥 💪 📣 🔺 🖖 🏷 (⏮️ 🔢 `password`, ⏮️ `hashed_password` & 🍵 🔐): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../docs_src/extra_models/tutorial002.py!} +``` + +//// - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../docs_src/extra_models/tutorial002_py310.py!} +``` - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +//// ## `Union` ⚖️ `anyOf` @@ -178,20 +192,27 @@ UserInDB( 👈, ⚙️ 🐩 🐍 🆎 🔑 `typing.Union`: -!!! note - 🕐❔ ⚖ `Union`, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. +/// note + +🕐❔ ⚖ `Union`, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. -=== "🐍 3️⃣.6️⃣ & 🔛" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.6️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1 14-15 18-20 33" +{!> ../../docs_src/extra_models/tutorial003.py!} +``` + +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// ### `Union` 🐍 3️⃣.1️⃣0️⃣ @@ -213,17 +234,21 @@ some_variable: PlaneItem | CarItem 👈, ⚙️ 🐩 🐍 `typing.List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +```Python hl_lines="1 20" +{!> ../../docs_src/extra_models/tutorial004.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// ## 📨 ⏮️ ❌ `dict` @@ -233,17 +258,21 @@ some_variable: PlaneItem | CarItem 👉 💼, 👆 💪 ⚙️ `typing.Dict` (⚖️ `dict` 🐍 3️⃣.9️⃣ & 🔛): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 8" +{!> ../../docs_src/extra_models/tutorial005.py!} +``` + +//// - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="6" +{!> ../../docs_src/extra_models/tutorial005_py39.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index 252e769f4..d6762422e 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ 🙅 FastAPI 📁 💪 👀 💖 👉: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 📁 👈 📁 `main.py`. @@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note - 📋 `uvicorn main:app` 🔗: +/// note - * `main`: 📁 `main.py` (🐍 "🕹"). - * `app`: 🎚 ✍ 🔘 `main.py` ⏮️ ⏸ `app = FastAPI()`. - * `--reload`: ⚒ 💽 ⏏ ⏮️ 📟 🔀. 🕴 ⚙️ 🛠️. +📋 `uvicorn main:app` 🔗: + +* `main`: 📁 `main.py` (🐍 "🕹"). +* `app`: 🎚 ✍ 🔘 `main.py` ⏮️ ⏸ `app = FastAPI()`. +* `--reload`: ⚒ 💽 ⏏ ⏮️ 📟 🔀. 🕴 ⚙️ 🛠️. + +/// 🔢, 📤 ⏸ ⏮️ 🕳 💖: @@ -131,20 +134,23 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 1️⃣: 🗄 `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️. -!!! note "📡 ℹ" - `FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`. +/// note | 📡 ℹ + +`FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`. - 👆 💪 ⚙️ 🌐 💃 🛠️ ⏮️ `FastAPI` 💁‍♂️. +👆 💪 ⚙️ 🌐 💃 🛠️ ⏮️ `FastAPI` 💁‍♂️. + +/// ### 🔁 2️⃣: ✍ `FastAPI` "👐" ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 📥 `app` 🔢 🔜 "👐" 🎓 `FastAPI`. @@ -166,7 +172,7 @@ $ uvicorn main:app --reload 🚥 👆 ✍ 👆 📱 💖: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` & 🚮 ⚫️ 📁 `main.py`, ⤴️ 👆 🔜 🤙 `uvicorn` 💖: @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - "➡" 🛎 🤙 "🔗" ⚖️ "🛣". +/// info + +"➡" 🛎 🤙 "🔗" ⚖️ "🛣". + +/// ⏪ 🏗 🛠️, "➡" 👑 🌌 🎏 "⚠" & "ℹ". @@ -242,7 +251,7 @@ https://example.com/items/foo #### 🔬 *➡ 🛠️ 👨‍🎨* ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")` 💬 **FastAPI** 👈 🔢 ▶️️ 🔛 🈚 🚚 📨 👈 🚶: @@ -250,16 +259,19 @@ https://example.com/items/foo * ➡ `/` * ⚙️ get 🛠️ -!!! info "`@decorator` ℹ" - 👈 `@something` ❕ 🐍 🤙 "👨‍🎨". +/// info | `@decorator` ℹ - 👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️). +👈 `@something` ❕ 🐍 🤙 "👨‍🎨". - "👨‍🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️. +👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️). - 👆 💼, 👉 👨‍🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`. + "👨‍🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️. - ⚫️ "**➡ 🛠️ 👨‍🎨**". +👆 💼, 👉 👨‍🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`. + +⚫️ "**➡ 🛠️ 👨‍🎨**". + +/// 👆 💪 ⚙️ 🎏 🛠️: @@ -274,14 +286,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip - 👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩‍🔬) 👆 🎋. +/// tip + +👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩‍🔬) 👆 🎋. - **FastAPI** 🚫 🛠️ 🙆 🎯 🔑. +**FastAPI** 🚫 🛠️ 🙆 🎯 🔑. - ℹ 📥 🎁 📄, 🚫 📄. +ℹ 📥 🎁 📄, 🚫 📄. - 🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️. +🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️. + +/// ### 🔁 4️⃣: 🔬 **➡ 🛠️ 🔢** @@ -292,7 +307,7 @@ https://example.com/items/foo * **🔢**: 🔢 🔛 "👨‍🎨" (🔛 `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 👉 🐍 🔢. @@ -306,16 +321,19 @@ https://example.com/items/foo 👆 💪 🔬 ⚫️ 😐 🔢 ↩️ `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - 🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note + +🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#_2){.internal-link target=_blank}. + +/// ### 🔁 5️⃣: 📨 🎚 ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 👆 💪 📨 `dict`, `list`, ⭐ 💲 `str`, `int`, ♒️. diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index 36d58e2af..e0edae51a 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -26,7 +26,7 @@ ### 🗄 `HTTPException` ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### 🤚 `HTTPException` 👆 📟 @@ -42,7 +42,7 @@ 👉 🖼, 🕐❔ 👩‍💻 📨 🏬 🆔 👈 🚫 🔀, 🤚 ⚠ ⏮️ 👔 📟 `404`: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### 📉 📨 @@ -63,12 +63,15 @@ } ``` -!!! tip - 🕐❔ 🙋‍♀ `HTTPException`, 👆 💪 🚶‍♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`. +/// tip - 👆 💪 🚶‍♀️ `dict`, `list`, ♒️. +🕐❔ 🙋‍♀ `HTTPException`, 👆 💪 🚶‍♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`. - 👫 🍵 🔁 **FastAPI** & 🗜 🎻. +👆 💪 🚶‍♀️ `dict`, `list`, ♒️. + +👫 🍵 🔁 **FastAPI** & 🗜 🎻. + +/// ## 🚮 🛃 🎚 @@ -79,7 +82,7 @@ ✋️ 💼 👆 💪 ⚫️ 🏧 😐, 👆 💪 🚮 🛃 🎚: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` ## ❎ 🛃 ⚠ 🐕‍🦺 @@ -93,7 +96,7 @@ 👆 💪 🚮 🛃 ⚠ 🐕‍🦺 ⏮️ `@app.exception_handler()`: ```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` 📥, 🚥 👆 📨 `/unicorns/yolo`, *➡ 🛠️* 🔜 `raise` `UnicornException`. @@ -106,10 +109,13 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`. +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`. +/// ## 🔐 🔢 ⚠ 🐕‍🦺 @@ -130,7 +136,7 @@ ⚠ 🐕‍🦺 🔜 📨 `Request` & ⚠. ```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` 🔜, 🚥 👆 🚶 `/items/foo`, ↩️ 💆‍♂ 🔢 🎻 ❌ ⏮️: @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError` 🆚 `ValidationError` -!!! warning - 👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜. +/// warning + +👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜. + +/// `RequestValidationError` 🎧-🎓 Pydantic `ValidationError`. @@ -180,13 +189,16 @@ path -> item_id 🖼, 👆 💪 💚 📨 ✅ ✍ 📨 ↩️ 🎻 👫 ❌: ```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`. +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +/// ### ⚙️ `RequestValidationError` 💪 @@ -195,7 +207,7 @@ path -> item_id 👆 💪 ⚙️ ⚫️ ⏪ 🛠️ 👆 📱 🕹 💪 & ℹ ⚫️, 📨 ⚫️ 👩‍💻, ♒️. ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} +{!../../docs_src/handling_errors/tutorial005.py!} ``` 🔜 🔄 📨 ❌ 🏬 💖: @@ -255,7 +267,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException 🚥 👆 💚 ⚙️ ⚠ ⤴️ ⏮️ 🎏 🔢 ⚠ 🐕‍🦺 ⚪️➡️ **FastAPI**, 👆 💪 🗄 & 🏤-⚙️ 🔢 ⚠ 🐕‍🦺 ⚪️➡️ `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` 👉 🖼 👆 `print`😅 ❌ ⏮️ 📶 🎨 📧, ✋️ 👆 🤚 💭. 👆 💪 ⚙️ ⚠ & ⤴️ 🏤-⚙️ 🔢 ⚠ 🐕‍🦺. diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md index 0f33a1774..d9eafe77e 100644 --- a/docs/em/docs/tutorial/header-params.md +++ b/docs/em/docs/tutorial/header-params.md @@ -6,17 +6,21 @@ 🥇 🗄 `Header`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/header_params/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../docs_src/header_params/tutorial001_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +//// ## 📣 `Header` 🔢 @@ -24,25 +28,35 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +/// note | 📡 ℹ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +`Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +/// -!!! note "📡 ℹ" - `Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. +/// info - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. -!!! info - 📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. +/// ## 🏧 🛠️ @@ -60,20 +74,27 @@ 🚥 🤔 👆 💪 ❎ 🏧 🛠️ 🎦 🔠, ⚒ 🔢 `convert_underscores` `Header` `False`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/header_params/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../docs_src/header_params/tutorial002_py310.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// warning - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦. -!!! warning - ⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦. +/// ## ❎ 🎚 @@ -85,23 +106,29 @@ 🖼, 📣 🎚 `X-Token` 👈 💪 😑 🌅 🌘 🕐, 👆 💪 ✍: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../docs_src/header_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// 🚥 👆 🔗 ⏮️ 👈 *➡ 🛠️* 📨 2️⃣ 🇺🇸🔍 🎚 💖: diff --git a/docs/em/docs/tutorial/index.md b/docs/em/docs/tutorial/index.md index 26b4c1913..5f7532341 100644 --- a/docs/em/docs/tutorial/index.md +++ b/docs/em/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...👈 🔌 `uvicorn`, 👈 👆 💪 ⚙️ 💽 👈 🏃 👆 📟. -!!! note - 👆 💪 ❎ ⚫️ 🍕 🍕. +/// note - 👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭: +👆 💪 ❎ ⚫️ 🍕 🍕. - ``` - pip install fastapi - ``` +👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭: - ❎ `uvicorn` 👷 💽: +``` +pip install "fastapi[standard]" +``` + +❎ `uvicorn` 👷 💽: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` + & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️. - & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️. +/// ## 🏧 👩‍💻 🦮 diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index 75508af4d..a30db113d 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -18,11 +18,14 @@ 👆 💪 ⚒ 👫 ⏩: ```Python hl_lines="3-16 19-31" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` -!!! tip - 👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢. +/// tip + +👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢. + +/// ⏮️ 👉 📳, 🏧 🛠️ 🩺 🔜 👀 💖: @@ -49,24 +52,30 @@ ✍ 🗃 👆 🔖 & 🚶‍♀️ ⚫️ `openapi_tags` 🔢: ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` 👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_). -!!! tip - 👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️. +/// tip + +👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️. + +/// ### ⚙️ 👆 🔖 ⚙️ `tags` 🔢 ⏮️ 👆 *➡ 🛠️* (& `APIRouter`Ⓜ) 🛠️ 👫 🎏 🔖: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` -!!! info - ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#tags){.internal-link target=_blank}. +/// info + +✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#_3){.internal-link target=_blank}. + +/// ### ✅ 🩺 @@ -89,7 +98,7 @@ 🖼, ⚒ ⚫️ 🍦 `/api/v1/openapi.json`: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` 🚥 👆 💚 ❎ 🗄 🔗 🍕 👆 💪 ⚒ `openapi_url=None`, 👈 🔜 ❎ 🧾 👩‍💻 🔢 👈 ⚙️ ⚫️. @@ -108,5 +117,5 @@ 🖼, ⚒ 🦁 🎚 🍦 `/documentation` & ❎ 📄: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md index 644b4690c..a794ab019 100644 --- a/docs/em/docs/tutorial/middleware.md +++ b/docs/em/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * ⚫️ 💪 🕳 👈 **📨** ⚖️ 🏃 🙆 💪 📟. * ⤴️ ⚫️ 📨 **📨**. -!!! note "📡 ℹ" - 🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️. +/// note | 📡 ℹ - 🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️. +🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️. + +🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️. + +/// ## ✍ 🛠️ @@ -29,18 +32,24 @@ * 👆 💪 ⤴️ 🔀 🌅 `response` ⏭ 🛬 ⚫️. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` -!!! tip - ✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡. +/// tip + +✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡. + +✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩‍💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺. + +/// + +/// note | 📡 ℹ - ✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩‍💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺. +👆 💪 ⚙️ `from starlette.requests import Request`. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request`. +**FastAPI** 🚚 ⚫️ 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 ⚫️ 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ### ⏭ & ⏮️ `response` @@ -51,7 +60,7 @@ 🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## 🎏 🛠️ diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md index 916529258..deb71c807 100644 --- a/docs/em/docs/tutorial/path-operation-configuration.md +++ b/docs/em/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ 📤 📚 🔢 👈 👆 💪 🚶‍♀️ 👆 *➡ 🛠️ 👨‍🎨* 🔗 ⚫️. -!!! warning - 👀 👈 👫 🔢 🚶‍♀️ 🔗 *➡ 🛠️ 👨‍🎨*, 🚫 👆 *➡ 🛠️ 🔢*. +/// warning + +👀 👈 👫 🔢 🚶‍♀️ 🔗 *➡ 🛠️ 👨‍🎨*, 🚫 👆 *➡ 🛠️ 🔢*. + +/// ## 📨 👔 📟 @@ -13,52 +16,67 @@ ✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="3 17" +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="3 17" +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1 15" +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// 👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette import status`. +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette import status`. + +**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ## 🔖 👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶‍♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`): -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="15 20 25" +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// 👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢: @@ -73,30 +91,36 @@ **FastAPI** 🐕‍🦺 👈 🎏 🌌 ⏮️ ✅ 🎻: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## 📄 & 📛 👆 💪 🚮 `summary` & `description`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="20-21" +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="20-21" +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="18-19" +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// ## 📛 ⚪️➡️ #️⃣ @@ -104,23 +128,29 @@ 👆 💪 ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐). -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19-27" +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="19-27" +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +```Python hl_lines="17-25" +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// ⚫️ 🔜 ⚙️ 🎓 🩺: @@ -130,31 +160,43 @@ 👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="21" +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="21" +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="19" +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +/// check -!!! info - 👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢. +🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛. -!!! check - 🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛. +, 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨". - , 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨". +/// @@ -163,7 +205,7 @@ 🚥 👆 💪 ™ *➡ 🛠️* 😢, ✋️ 🍵 ❎ ⚫️, 🚶‍♀️ 🔢 `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` ⚫️ 🔜 🎯 ™ 😢 🎓 🩺: diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md index b1ba2670b..74dbb55f7 100644 --- a/docs/em/docs/tutorial/path-params-numeric-validations.md +++ b/docs/em/docs/tutorial/path-params-numeric-validations.md @@ -6,17 +6,21 @@ 🥇, 🗄 `Path` ⚪️➡️ `fastapi`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// ## 📣 🗃 @@ -24,24 +28,31 @@ 🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` -!!! note - ➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡. +//// - , 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔. +/// note - 👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚. +➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡. + +, 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔. + +👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚. + +/// ## ✔ 🔢 👆 💪 @@ -60,7 +71,7 @@ , 👆 💪 📣 👆 🔢: ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## ✔ 🔢 👆 💪, 🎱 @@ -72,7 +83,7 @@ 🐍 🏆 🚫 🕳 ⏮️ 👈 `*`, ✋️ ⚫️ 🔜 💭 👈 🌐 📄 🔢 🔜 🤙 🇨🇻 ❌ (🔑-💲 👫), 💭 kwargs. 🚥 👫 🚫 ✔️ 🔢 💲. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## 🔢 🔬: 👑 🌘 ⚖️ 🌓 @@ -82,7 +93,7 @@ 📥, ⏮️ `ge=1`, `item_id` 🔜 💪 🔢 🔢 "`g`🅾 🌘 ⚖️ `e`🅾" `1`. ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓 @@ -93,7 +104,7 @@ * `le`: `l`👭 🌘 ⚖️ `e`🅾 ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘 @@ -107,7 +118,7 @@ & 🎏 lt. ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## 🌃 @@ -121,18 +132,24 @@ * `lt`: `l`👭 `t`👲 * `le`: `l`👭 🌘 ⚖️ `e`🅾 -!!! info - `Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓. +/// info + +`Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓. + +🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀. + +/// + +/// note | 📡 ℹ - 🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀. +🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢. -!!! note "📡 ℹ" - 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢. +👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛. - 👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛. +, 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`. - , 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`. +👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨‍🎨 🚫 ™ ❌ 🔃 👫 🆎. - 👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨‍🎨 🚫 ™ ❌ 🔃 👫 🆎. +👈 🌌 👆 💪 ⚙️ 👆 😐 👨‍🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷‍♂ 📚 ❌. - 👈 🌌 👆 💪 ⚙️ 👆 😐 👨‍🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷‍♂ 📚 ❌. +/// diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index ac64d2ebb..daf5417eb 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ 👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` 💲 ➡ 🔢 `item_id` 🔜 🚶‍♀️ 👆 🔢 ❌ `item_id`. @@ -19,13 +19,16 @@ 👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍: ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` 👉 💼, `item_id` 📣 `int`. -!!! check - 👉 🔜 🤝 👆 👨‍🎨 🐕‍🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️. +/// check + +👉 🔜 🤝 👆 👨‍🎨 🐕‍🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️. + +/// ## 💽 🛠️ @@ -35,10 +38,13 @@ {"item_id":3} ``` -!!! check - 👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`. +/// check + +👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`. + +, ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍". - , ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍". +/// ## 💽 🔬 @@ -63,12 +69,15 @@ 🎏 ❌ 🔜 😑 🚥 👆 🚚 `float` ↩️ `int`,: http://127.0.0.1:8000/items/4.2 -!!! check - , ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬. +/// check - 👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶‍♀️. +, ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬. - 👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️. +👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶‍♀️. + +👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️. + +/// ## 🧾 @@ -76,10 +85,13 @@ -!!! check - 🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚). +/// check + +🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚). + +👀 👈 ➡ 🔢 📣 🔢. - 👀 👈 ➡ 🔢 📣 🔢. +/// ## 🐩-⚓️ 💰, 🎛 🧾 @@ -110,7 +122,7 @@ ↩️ *➡ 🛠️* 🔬 ✔, 👆 💪 ⚒ 💭 👈 ➡ `/users/me` 📣 ⏭ 1️⃣ `/users/{user_id}`: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` ⏪, ➡ `/users/{user_id}` 🔜 🏏 `/users/me`, "💭" 👈 ⚫️ 📨 🔢 `user_id` ⏮️ 💲 `"me"`. @@ -118,7 +130,7 @@ ➡, 👆 🚫🔜 ↔ ➡ 🛠️: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003b.py!} +{!../../docs_src/path_params/tutorial003b.py!} ``` 🥇 🕐 🔜 🕧 ⚙️ ↩️ ➡ 🏏 🥇. @@ -136,21 +148,27 @@ ⤴️ ✍ 🎓 🔢 ⏮️ 🔧 💲, ❔ 🔜 💪 ☑ 💲: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! info - 🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣. +/// info -!!! tip - 🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷. +🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣. + +/// + +/// tip + +🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷. + +/// ### 📣 *➡ 🔢* ⤴️ ✍ *➡ 🔢* ⏮️ 🆎 ✍ ⚙️ 🔢 🎓 👆 ✍ (`ModelName`): ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### ✅ 🩺 @@ -168,7 +186,7 @@ 👆 💪 🔬 ⚫️ ⏮️ *🔢 👨‍🎓* 👆 ✍ 🔢 `ModelName`: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### 🤚 *🔢 💲* @@ -176,11 +194,14 @@ 👆 💪 🤚 ☑ 💲 ( `str` 👉 💼) ⚙️ `model_name.value`, ⚖️ 🏢, `your_enum_member.value`: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! tip - 👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`. +/// tip + +👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`. + +/// #### 📨 *🔢 👨‍🎓* @@ -189,7 +210,7 @@ 👫 🔜 🗜 👫 🔗 💲 (🎻 👉 💼) ⏭ 🛬 👫 👩‍💻: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` 👆 👩‍💻 👆 🔜 🤚 🎻 📨 💖: @@ -230,13 +251,16 @@ , 👆 💪 ⚙️ ⚫️ ⏮️: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` -!!! tip - 👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`). +/// tip + +👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`). + +👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`. - 👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index 1268c0d6e..f75c0a26f 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,31 @@ ➡️ ✊ 👉 🈸 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +//// 🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔. -!!! note - FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. +/// note + +FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. - `Union` `Union[str, None]` 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. + `Union` `Union[str, None]` 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. + +/// ## 🌖 🔬 @@ -31,33 +38,41 @@ 🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="3" +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +//// ## ⚙️ `Query` 🔢 💲 & 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +//// 👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲. @@ -87,22 +102,25 @@ q: str | None = None ✋️ ⚫️ 📣 ⚫️ 🎯 💆‍♂ 🔢 🔢. -!!! info - ✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕: +/// info - ```Python - = None - ``` +✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕: - ⚖️: +```Python += None +``` + +⚖️: + +```Python += Query(default=None) +``` - ```Python - = Query(default=None) - ``` +⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**. - ⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**. + `Union[str, None]` 🍕 ✔ 👆 👨‍🎨 🚚 👻 🐕‍🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔. - `Union[str, None]` 🍕 ✔ 👆 👨‍🎨 🚚 👻 🐕‍🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔. +/// ⤴️, 👥 💪 🚶‍♀️ 🌅 🔢 `Query`. 👉 💼, `max_length` 🔢 👈 ✔ 🎻: @@ -116,33 +134,41 @@ q: Union[str, None] = Query(default=None, max_length=50) 👆 💪 🚮 🔢 `min_length`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial003.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +//// ## 🚮 🥔 🧬 👆 💪 🔬 🥔 🧬 👈 🔢 🔜 🏏: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +```Python hl_lines="11" +{!> ../../docs_src/query_params_str_validations/tutorial004.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} +``` + +//// 👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲: @@ -161,11 +187,14 @@ q: Union[str, None] = Query(default=None, max_length=50) ➡️ 💬 👈 👆 💚 📣 `q` 🔢 🔢 ✔️ `min_length` `3`, & ✔️ 🔢 💲 `"fixedquery"`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note - ✔️ 🔢 💲 ⚒ 🔢 📦. +/// note + +✔️ 🔢 💲 ⚒ 🔢 📦. + +/// ## ⚒ ⚫️ ✔ @@ -190,7 +219,7 @@ q: Union[str, None] = Query(default=None, min_length=3) , 🕐❔ 👆 💪 📣 💲 ✔ ⏪ ⚙️ `Query`, 👆 💪 🎯 🚫 📣 🔢 💲: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` ### ✔ ⏮️ ❕ (`...`) @@ -198,13 +227,16 @@ q: Union[str, None] = Query(default=None, min_length=3) 📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006b.py!} +{!../../docs_src/query_params_str_validations/tutorial006b.py!} ``` -!!! info - 🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕". +/// info + +🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕". + +⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔. - ⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔. +/// 👉 🔜 ➡️ **FastAPI** 💭 👈 👉 🔢 ✔. @@ -214,31 +246,41 @@ q: Union[str, None] = Query(default=None, min_length=3) 👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. -!!! tip - Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. +/// ### ⚙️ Pydantic `Required` ↩️ ❕ (`...`) 🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic: ```Python hl_lines="2 8" -{!../../../docs_src/query_params_str_validations/tutorial006d.py!} +{!../../docs_src/query_params_str_validations/tutorial006d.py!} ``` -!!! tip - 💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`. +/// tip + +💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`. + +/// ## 🔢 🔢 📇 / 💗 💲 @@ -246,23 +288,29 @@ q: Union[str, None] = Query(default=None, min_length=3) 🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial011.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} +``` + +//// ⤴️, ⏮️ 📛 💖: @@ -283,8 +331,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip - 📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪. +/// tip + +📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪. + +/// 🎓 🛠️ 🩺 🔜 ℹ ➡️, ✔ 💗 💲: @@ -294,17 +345,21 @@ http://localhost:8000/items/?q=foo&q=bar & 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial012.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +//// 🚥 👆 🚶: @@ -328,13 +383,16 @@ http://localhost:8000/items/ 👆 💪 ⚙️ `list` 🔗 ↩️ `List[str]` (⚖️ `list[str]` 🐍 3️⃣.9️⃣ ➕): ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note - ✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇. +/// note - 🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜. +✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇. + +🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜. + +/// ## 📣 🌅 🗃 @@ -342,38 +400,49 @@ http://localhost:8000/items/ 👈 ℹ 🔜 🔌 🏗 🗄 & ⚙️ 🧾 👩‍💻 🔢 & 🔢 🧰. -!!! note - ✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕‍🦺. +/// note + +✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕‍🦺. - 👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️. +👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️. + +/// 👆 💪 🚮 `title`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial007.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} +``` + +//// & `description`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="13" +{!> ../../docs_src/query_params_str_validations/tutorial008.py!} +``` + +//// - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="11" +{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +//// ## 📛 🔢 @@ -393,17 +462,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial009.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +//// ## 😛 🔢 @@ -413,17 +486,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 🚶‍♀️ 🔢 `deprecated=True` `Query`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../docs_src/query_params_str_validations/tutorial010.py!} +``` + +//// - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="16" +{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +//// 🩺 🔜 🎦 ⚫️ 💖 👉: @@ -433,17 +510,21 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial014.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md index ccb235c15..c8432f182 100644 --- a/docs/em/docs/tutorial/query-params.md +++ b/docs/em/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ 🕐❔ 👆 📣 🎏 🔢 🔢 👈 🚫 🍕 ➡ 🔢, 👫 🔁 🔬 "🔢" 🔢. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` 🔢 ⚒ 🔑-💲 👫 👈 🚶 ⏮️ `?` 📛, 🎏 `&` 🦹. @@ -63,38 +63,49 @@ http://127.0.0.1:8000/items/?skip=20 🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params/tutorial002.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// 👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢. -!!! check - 👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢. +/// check + +👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢. + +/// ## 🔢 🔢 🆎 🛠️ 👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../docs_src/query_params/tutorial003.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// 👉 💼, 🚥 👆 🚶: @@ -137,17 +148,21 @@ http://127.0.0.1:8000/items/foo?short=yes 👫 🔜 🔬 📛: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="8 10" +{!> ../../docs_src/query_params/tutorial004.py!} +``` + +//// - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="6 8" +{!> ../../docs_src/query_params/tutorial004_py310.py!} +``` - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// ## ✔ 🔢 🔢 @@ -158,7 +173,7 @@ http://127.0.0.1:8000/items/foo?short=yes ✋️ 🕐❔ 👆 💚 ⚒ 🔢 🔢 ✔, 👆 💪 🚫 📣 🙆 🔢 💲: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` 📥 🔢 🔢 `needy` ✔ 🔢 🔢 🆎 `str`. @@ -203,17 +218,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy & ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/query_params/tutorial006.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="8" +{!> ../../docs_src/query_params/tutorial006_py310.py!} +``` + +//// 👉 💼, 📤 3️⃣ 🔢 🔢: @@ -221,5 +240,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, `int` ⏮️ 🔢 💲 `0`. * `limit`, 📦 `int`. -!!! tip - 👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#predefined-values){.internal-link target=_blank}. +/// tip + +👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}. + +/// diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index be2218f89..9dcad81b4 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -2,19 +2,22 @@ 👆 💪 🔬 📁 📂 👩‍💻 ⚙️ `File`. -!!! info - 📨 📂 📁, 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +📨 📂 📁, 🥇 ❎ `python-multipart`. - 👉 ↩️ 📂 📁 📨 "📨 💽". +🤶 Ⓜ. `pip install python-multipart`. + +👉 ↩️ 📂 📁 📨 "📨 💽". + +/// ## 🗄 `File` 🗄 `File` & `UploadFile` ⚪️➡️ `fastapi`: ```Python hl_lines="1" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` ## 🔬 `File` 🔢 @@ -22,16 +25,22 @@ ✍ 📁 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Form`: ```Python hl_lines="7" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` -!!! info - `File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`. +/// info + +`File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`. + +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +/// -!!! tip - 📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. +/// tip + +📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. + +/// 📁 🔜 📂 "📨 💽". @@ -46,7 +55,7 @@ 🔬 📁 🔢 ⏮️ 🆎 `UploadFile`: ```Python hl_lines="12" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` ⚙️ `UploadFile` ✔️ 📚 📈 🤭 `bytes`: @@ -90,11 +99,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 📡 ℹ" - 🕐❔ 👆 ⚙️ `async` 👩‍🔬, **FastAPI** 🏃 📁 👩‍🔬 🧵 & ⌛ 👫. +/// note | `async` 📡 ℹ + +🕐❔ 👆 ⚙️ `async` 👩‍🔬, **FastAPI** 🏃 📁 👩‍🔬 🧵 & ⌛ 👫. -!!! note "💃 📡 ℹ" - **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI. +/// + +/// note | 💃 📡 ℹ + +**FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI. + +/// ## ⚫️❔ "📨 💽" @@ -102,40 +117,50 @@ contents = myfile.file.read() **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -!!! note "📡 ℹ" - 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁. +/// note | 📡 ℹ + +📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁. + +✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪. + +🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. + +/// - ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪. +/// warning - 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. +👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. -!!! warning - 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 📦 📁 📂 👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +```Python hl_lines="9 17" +{!> ../../docs_src/request_files/tutorial001_02.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 14" +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} +``` - ```Python hl_lines="7 14" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// ## `UploadFile` ⏮️ 🌖 🗃 👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃: ```Python hl_lines="13" -{!../../../docs_src/request_files/tutorial001_03.py!} +{!../../docs_src/request_files/tutorial001_03.py!} ``` ## 💗 📁 📂 @@ -146,40 +171,51 @@ contents = myfile.file.read() ⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="10 15" +{!> ../../docs_src/request_files/tutorial002.py!} +``` + +//// - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="8 13" +{!> ../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +//// 👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + +/// ### 💗 📁 📂 ⏮️ 🌖 🗃 & 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +```Python hl_lines="18" +{!> ../../docs_src/request_files/tutorial003.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="16" +{!> ../../docs_src/request_files/tutorial003_py39.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index 0415dbf01..80793dae4 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -2,15 +2,18 @@ 👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`. -!!! info - 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`. + +🤶 Ⓜ. `pip install python-multipart`. + +/// ## 🗄 `File` & `Form` ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## 🔬 `File` & `Form` 🔢 @@ -18,17 +21,20 @@ ✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` 📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑. & 👆 💪 📣 📁 `bytes` & `UploadFile`. -!!! warning - 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. +/// warning + +👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. + +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index f12d6e650..d364d2c92 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -2,17 +2,20 @@ 🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`. -!!! info - ⚙️ 📨, 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +⚙️ 📨, 🥇 ❎ `python-multipart`. + +🤶 Ⓜ. `pip install python-multipart`. + +/// ## 🗄 `Form` 🗄 `Form` ⚪️➡️ `fastapi`: ```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` ## 🔬 `Form` 🔢 @@ -20,7 +23,7 @@ ✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: ```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` 🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑. @@ -29,11 +32,17 @@ ⏮️ `Form` 👆 💪 📣 🎏 📳 ⏮️ `Body` (& `Query`, `Path`, `Cookie`), 🔌 🔬, 🖼, 📛 (✅ `user-name` ↩️ `username`), ♒️. -!!! info - `Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`. +/// info + +`Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`. + +/// + +/// tip -!!! tip - 📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. +📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. + +/// ## 🔃 "📨 🏑" @@ -41,17 +50,23 @@ **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -!!! note "📡 ℹ" - 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`. +/// note | 📡 ℹ + +📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`. + +✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃. + +🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. + +/// - ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃. +/// warning - 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. +👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`. -!!! warning - 👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`. +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index 7103e9176..fb5c17dd6 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -4,23 +4,29 @@ 👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +```Python hl_lines="18 23" +{!> ../../docs_src/response_model/tutorial001_01.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="18 23" +{!> ../../docs_src/response_model/tutorial001_01_py39.py!} +``` + +//// - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="16 21" +{!> ../../docs_src/response_model/tutorial001_01_py310.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +//// FastAPI 🔜 ⚙️ 👉 📨 🆎: @@ -53,35 +59,47 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: * `@app.delete()` * ♒️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../docs_src/response_model/tutorial001.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="17 22 24-27" +{!> ../../docs_src/response_model/tutorial001_py310.py!} +``` -!!! note - 👀 👈 `response_model` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. +//// + +/// note + +👀 👈 `response_model` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. + +/// `response_model` 📨 🎏 🆎 👆 🔜 📣 Pydantic 🏷 🏑,, ⚫️ 💪 Pydantic 🏷, ✋️ ⚫️ 💪, ✅ `list` Pydantic 🏷, 💖 `List[Item]`. FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **🗜 & ⛽ 🔢 📊** 🚮 🆎 📄. -!!! tip - 🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨‍🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`. +/// tip + +🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨‍🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`. + +👈 🌌 👆 💬 👨‍🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`. - 👈 🌌 👆 💬 👨‍🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`. +/// ### `response_model` 📫 @@ -95,37 +113,48 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** 📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +```Python hl_lines="9 11" +{!> ../../docs_src/response_model/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7 9" +{!> ../../docs_src/response_model/tutorial002_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +/// info -!!! info - ⚙️ `EmailStr`, 🥇 ❎ `email_validator`. +⚙️ `EmailStr`, 🥇 ❎ `email-validator`. - 🤶 Ⓜ. `pip install email-validator` - ⚖️ `pip install pydantic[email]`. +🤶 Ⓜ. `pip install email-validator` +⚖️ `pip install pydantic[email]`. + +/// & 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="18" +{!> ../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="16" +{!> ../../docs_src/response_model/tutorial002_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// 🔜, 🕐❔ 🖥 🏗 👩‍💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨. @@ -133,52 +162,67 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** ✋️ 🚥 👥 ⚙️ 🎏 🏷 ➕1️⃣ *➡ 🛠️*, 👥 💪 📨 👆 👩‍💻 🔐 🔠 👩‍💻. -!!! danger - 🙅 🏪 ✅ 🔐 👩‍💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨. +/// danger + +🙅 🏪 ✅ 🔐 👩‍💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨. + +/// ## 🚮 🔢 🏷 👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9 11 16" +{!> ../../docs_src/response_model/tutorial003.py!} +``` + +//// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="9 11 16" +{!> ../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// 📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩‍💻 👈 🔌 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="24" +{!> ../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="24" +{!> ../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// ...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../docs_src/response_model/tutorial003.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// , **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic). @@ -202,17 +246,21 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** & 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕‍🦺 👨‍🎨 & 🧰, & 🤚 FastAPI **💽 🖥**. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9-13 15-16 20" +{!> ../../docs_src/response_model/tutorial003_01.py!} +``` + +//// - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="7-10 13-14 18" +{!> ../../docs_src/response_model/tutorial003_01_py310.py!} +``` - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +//// ⏮️ 👉, 👥 🤚 🏭 🐕‍🦺, ⚪️➡️ 👨‍🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI. @@ -255,7 +303,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🏆 ⚠ 💼 🔜 [🛬 📨 🔗 🔬 ⏪ 🏧 🩺](../advanced/response-directly.md){.internal-link target=_blank}. ```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} +{!> ../../docs_src/response_model/tutorial003_02.py!} ``` 👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`. @@ -267,7 +315,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚙️ 🏿 `Response` 🆎 ✍: ```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} +{!> ../../docs_src/response_model/tutorial003_03.py!} ``` 👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼. @@ -278,17 +326,21 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/response_model/tutorial003_04.py!} +``` + +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../docs_src/response_model/tutorial003_04_py310.py!} +``` + +//// ...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`. @@ -300,17 +352,21 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="9" +{!> ../../docs_src/response_model/tutorial003_05.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="7" +{!> ../../docs_src/response_model/tutorial003_05_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +//// 👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶 @@ -318,23 +374,29 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 📨 🏷 💪 ✔️ 🔢 💲, 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +```Python hl_lines="11 13-14" +{!> ../../docs_src/response_model/tutorial004.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="11 13-14" +{!> ../../docs_src/response_model/tutorial004_py39.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="9 11-12" +{!> ../../docs_src/response_model/tutorial004_py310.py!} +``` - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +//// * `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`. * `tax: float = 10.5` ✔️ 🔢 `10.5`. @@ -348,23 +410,29 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚒ *➡ 🛠️ 👨‍🎨* 🔢 `response_model_exclude_unset=True`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +```Python hl_lines="24" +{!> ../../docs_src/response_model/tutorial004.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="24" +{!> ../../docs_src/response_model/tutorial004_py39.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="22" +{!> ../../docs_src/response_model/tutorial004_py310.py!} +``` + +//// & 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒. @@ -377,16 +445,22 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 } ``` -!!! info - FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉. +/// info + +FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉. + +/// + +/// info -!!! info - 👆 💪 ⚙️: +👆 💪 ⚙️: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - 🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`. +🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`. + +/// #### 📊 ⏮️ 💲 🏑 ⏮️ 🔢 @@ -421,10 +495,13 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t , 👫 🔜 🔌 🎻 📨. -!!! tip - 👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`. +/// tip + +👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`. + +👫 💪 📇 (`[]`), `float` `10.5`, ♒️. - 👫 💪 📇 (`[]`), `float` `10.5`, ♒️. +/// ### `response_model_include` & `response_model_exclude` @@ -434,45 +511,59 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t 👉 💪 ⚙️ ⏩ ⌨ 🚥 👆 ✔️ 🕴 1️⃣ Pydantic 🏷 & 💚 ❎ 💽 ⚪️➡️ 🔢. -!!! tip - ✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢. +/// tip + +✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢. + +👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢. - 👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢. +👉 ✔ `response_model_by_alias` 👈 👷 ➡. - 👉 ✔ `response_model_by_alias` 👈 👷 ➡. +/// -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +```Python hl_lines="31 37" +{!> ../../docs_src/response_model/tutorial005.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="29 35" +{!> ../../docs_src/response_model/tutorial005_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +/// tip -!!! tip - ❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲. +❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲. - ⚫️ 🌓 `set(["name", "description"])`. +⚫️ 🌓 `set(["name", "description"])`. + +/// #### ⚙️ `list`Ⓜ ↩️ `set`Ⓜ 🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="31 37" +{!> ../../docs_src/response_model/tutorial006.py!} +``` - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="29 35" +{!> ../../docs_src/response_model/tutorial006_py310.py!} +``` - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md index e5149de7d..478060326 100644 --- a/docs/em/docs/tutorial/response-status-code.md +++ b/docs/em/docs/tutorial/response-status-code.md @@ -9,16 +9,22 @@ * ♒️. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note - 👀 👈 `status_code` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. +/// note + +👀 👈 `status_code` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. + +/// `status_code` 🔢 📨 🔢 ⏮️ 🇺🇸🔍 👔 📟. -!!! info - `status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`. +/// info + +`status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`. + +/// ⚫️ 🔜: @@ -27,15 +33,21 @@ -!!! note - 📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪. +/// note + +📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪. + +FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 💪. - FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 💪. +/// ## 🔃 🇺🇸🔍 👔 📟 -!!! note - 🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄. +/// note + +🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄. + +/// 🇺🇸🔍, 👆 📨 🔢 👔 📟 3️⃣ 9️⃣ 🍕 📨. @@ -54,15 +66,18 @@ * 💊 ❌ ⚪️➡️ 👩‍💻, 👆 💪 ⚙️ `400`. * `500` & 🔛 💽 ❌. 👆 🌖 🙅 ⚙️ 👫 🔗. 🕐❔ 🕳 🚶 ❌ 🍕 👆 🈸 📟, ⚖️ 💽, ⚫️ 🔜 🔁 📨 1️⃣ 👫 👔 📟. -!!! tip - 💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟. +/// tip + +💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟. + +/// ## ⌨ 💭 📛 ➡️ 👀 ⏮️ 🖼 🔄: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` 👔 📟 "✍". @@ -72,17 +87,20 @@ 👆 💪 ⚙️ 🏪 🔢 ⚪️➡️ `fastapi.status`. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` 👫 🏪, 👫 🧑‍🤝‍🧑 🎏 🔢, ✋️ 👈 🌌 👆 💪 ⚙️ 👨‍🎨 📋 🔎 👫: -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette import status`. +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette import status`. + +**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ## 🔀 🔢 diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index 114d5a84a..e4f877a8e 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -8,24 +8,31 @@ 👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +```Python hl_lines="15-23" +{!> ../../docs_src/schema_extra_example/tutorial001.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="13-21" +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` + +//// 👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺. -!!! tip - 👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ. +/// tip + +👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ. + +🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩‍💻 🔢, ♒️. - 🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩‍💻 🔢, ♒️. +/// ## `Field` 🌖 ❌ @@ -33,20 +40,27 @@ 👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="4 10-13" +{!> ../../docs_src/schema_extra_example/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +```Python hl_lines="2 8-11" +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +/// warning -!!! warning - 🚧 🤯 👈 📚 ➕ ❌ 🚶‍♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯. +🚧 🤯 👈 📚 ➕ ❌ 🚶‍♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯. + +/// ## `example` & `examples` 🗄 @@ -66,17 +80,21 @@ 📥 👥 🚶‍♀️ `example` 📊 ⌛ `Body()`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="20-25" +{!> ../../docs_src/schema_extra_example/tutorial003.py!} +``` - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +```Python hl_lines="18-23" +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` + +//// ### 🖼 🩺 🎚 @@ -97,17 +115,21 @@ * `value`: 👉 ☑ 🖼 🎦, ✅ `dict`. * `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕‍🦺 📚 🧰 `value`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="21-47" +{!> ../../docs_src/schema_extra_example/tutorial004.py!} +``` - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +```Python hl_lines="19-45" +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` + +//// ### 🖼 🩺 🎚 @@ -117,10 +139,13 @@ ## 📡 ℹ -!!! warning - 👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**. +/// warning + +👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**. + +🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫. - 🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫. +/// 🕐❔ 👆 🚮 🖼 🔘 Pydantic 🏷, ⚙️ `schema_extra` ⚖️ `Field(example="something")` 👈 🖼 🚮 **🎻 🔗** 👈 Pydantic 🏷. diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 8c2c95cfd..21c48757f 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -21,17 +21,20 @@ 📁 🖼 📁 `main.py`: ```Python -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ## 🏃 ⚫️ -!!! info - 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +🥇 ❎ `python-multipart`. - 👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`. +🤶 Ⓜ. `pip install python-multipart`. + +👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`. + +/// 🏃 🖼 ⏮️: @@ -53,17 +56,23 @@ $ uvicorn main:app --reload -!!! check "✔ 🔼 ❗" - 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼. +/// check | ✔ 🔼 ❗ + +👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼. + + & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊. - & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊. +/// & 🚥 👆 🖊 ⚫️, 👆 ✔️ 🐥 ✔ 📨 🆎 `username` & `password` (& 🎏 📦 🏑): -!!! note - ⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤. +/// note + +⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤. + +/// 👉 ↗️ 🚫 🕸 🏁 👩‍💻, ✋️ ⚫️ 👑 🏧 🧰 📄 🖥 🌐 👆 🛠️. @@ -105,36 +114,45 @@ Oauth2️⃣ 🔧 👈 👩‍💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 👉 🖼 👥 🔜 ⚙️ **Oauth2️⃣**, ⏮️ **🔐** 💧, ⚙️ **📨** 🤝. 👥 👈 ⚙️ `OAuth2PasswordBearer` 🎓. -!!! info - "📨" 🤝 🚫 🕴 🎛. +/// info + +"📨" 🤝 🚫 🕴 🎛. - ✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼. +✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼. - & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪. + & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪. - 👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️. +👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️. + +/// 🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶‍♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩‍💻 (🕸 🏃 👩‍💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝. ```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` -!!! tip - 📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`. +/// tip + +📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`. - ↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`. +↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`. - ⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. +⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. + +/// 👉 🔢 🚫 ✍ 👈 🔗 / *➡ 🛠️*, ✋️ 📣 👈 📛 `/token` 🔜 1️⃣ 👈 👩‍💻 🔜 ⚙️ 🤚 🤝. 👈 ℹ ⚙️ 🗄, & ⤴️ 🎓 🛠️ 🧾 ⚙️. 👥 🔜 🔜 ✍ ☑ ➡ 🛠️. -!!! info - 🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`. +/// info + +🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`. - 👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂‍♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️. +👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂‍♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️. + +/// `oauth2_scheme` 🔢 👐 `OAuth2PasswordBearer`, ✋️ ⚫️ "🇧🇲". @@ -151,17 +169,20 @@ oauth2_scheme(some, parameters) 🔜 👆 💪 🚶‍♀️ 👈 `oauth2_scheme` 🔗 ⏮️ `Depends`. ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` 👉 🔗 🔜 🚚 `str` 👈 🛠️ 🔢 `token` *➡ 🛠️ 🔢*. **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 👉 🔗 🔬 "💂‍♂ ⚖" 🗄 🔗 (& 🏧 🛠️ 🩺). -!!! info "📡 ℹ" - **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂‍♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`. +/// info | 📡 ℹ + +**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂‍♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`. + +🌐 💂‍♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄. - 🌐 💂‍♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄. +/// ## ⚫️❔ ⚫️ 🔨 diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md index 455cb4f46..4e5b4ebfc 100644 --- a/docs/em/docs/tutorial/security/get-current-user.md +++ b/docs/em/docs/tutorial/security/get-current-user.md @@ -3,7 +3,7 @@ ⏮️ 📃 💂‍♂ ⚙️ (❔ 🧢 🔛 🔗 💉 ⚙️) 🤝 *➡ 🛠️ 🔢* `token` `str`: ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ✋️ 👈 🚫 👈 ⚠. @@ -16,17 +16,21 @@ 🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="5 12-16" +{!> ../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="3 10-14" +{!> ../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## ✍ `get_current_user` 🔗 @@ -38,63 +42,81 @@ 🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="25" +{!> ../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="23" +{!> ../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 🤚 👩‍💻 `get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="19-22 26-27" +{!> ../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="17-20 24-25" +{!> ../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 💉 ⏮️ 👩‍💻 🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="31" +{!> ../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="29" +{!> ../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// 👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`. 👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅. -!!! tip - 👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷. +/// tip + +👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷. + +📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`. - 📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`. +/// -!!! check - 🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷. +/// check - 👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽. +🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷. + +👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽. + +/// ## 🎏 🏷 @@ -128,17 +150,21 @@ & 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="30-32" +{!> ../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="28-30" +{!> ../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 🌃 diff --git a/docs/em/docs/tutorial/security/index.md b/docs/em/docs/tutorial/security/index.md index d76f7203f..1a47e5510 100644 --- a/docs/em/docs/tutorial/security/index.md +++ b/docs/em/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ Oauth2️⃣ 🔧 👈 🔬 📚 🌌 🍵 🤝 & ✔. Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮️ 🇺🇸🔍. -!!! tip - 📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜. +/// tip +📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜. + +/// ## 👩‍💻 🔗 @@ -87,10 +89,13 @@ Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮ * 👉 🏧 🔍 ⚫️❔ 🔬 👩‍💻 🔗 🔧. -!!! tip - 🛠️ 🎏 🤝/✔ 🐕‍🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩. +/// tip + +🛠️ 🎏 🤝/✔ 🐕‍🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩. + +🌅 🏗 ⚠ 🏗 🤝/✔ 🐕‍🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋‍♂ 👆. - 🌅 🏗 ⚠ 🏗 🤝/✔ 🐕‍🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋‍♂ 👆. +/// ## **FastAPI** 🚙 diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index bc3c943f8..95fa58f71 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -44,10 +44,13 @@ $ pip install "python-jose[cryptography]" 📥 👥 ⚙️ 👍 1️⃣: )/⚛. -!!! tip - 👉 🔰 ⏪ ⚙️ PyJWT. +/// tip - ✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰. +👉 🔰 ⏪ ⚙️ PyJWT. + +✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰. + +/// ## 🔐 🔁 @@ -83,12 +86,15 @@ $ pip install "passlib[bcrypt]" -!!! tip - ⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂‍♂ 🔌-⚖️ 📚 🎏. +/// tip + +⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂‍♂ 🔌-⚖️ 📚 🎏. + +, 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽. - , 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽. + & 👆 👩‍💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰. - & 👆 👩‍💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰. +/// ## #️⃣ & ✔ 🔐 @@ -96,12 +102,15 @@ $ pip install "passlib[bcrypt]" ✍ 🇸🇲 "🔑". 👉 ⚫️❔ 🔜 ⚙️ #️⃣ & ✔ 🔐. -!!! tip - 🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️. +/// tip - 🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡. +🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️. - & 🔗 ⏮️ 🌐 👫 🎏 🕰. +🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡. + + & 🔗 ⏮️ 🌐 👫 🎏 🕰. + +/// ✍ 🚙 🔢 #️⃣ 🔐 👟 ⚪️➡️ 👩‍💻. @@ -109,20 +118,27 @@ $ pip install "passlib[bcrypt]" & ➕1️⃣ 1️⃣ 🔓 & 📨 👩‍💻. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="7 48 55-56 59-60 69-75" +{!> ../../docs_src/security/tutorial004.py!} +``` + +//// - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="6 47 54-55 58-59 68-74" +{!> ../../docs_src/security/tutorial004_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="6 47 54-55 58-59 68-74" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +/// note -!!! note - 🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. +🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +/// ## 🍵 🥙 🤝 @@ -152,17 +168,21 @@ $ openssl rand -hex 32 ✍ 🚙 🔢 🏗 🆕 🔐 🤝. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="6 12-14 28-30 78-86" +{!> ../../docs_src/security/tutorial004.py!} +``` + +//// - ```Python hl_lines="6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="5 11-13 27-29 77-85" +{!> ../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="5 11-13 27-29 77-85" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// ## ℹ 🔗 @@ -172,17 +192,21 @@ $ openssl rand -hex 32 🚥 🤝 ❌, 📨 🇺🇸🔍 ❌ ▶️️ ↖️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +```Python hl_lines="89-106" +{!> ../../docs_src/security/tutorial004.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="88-105" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="88-105" +{!> ../../docs_src/security/tutorial004_py310.py!} +``` + +//// ## ℹ `/token` *➡ 🛠️* @@ -190,17 +214,21 @@ $ openssl rand -hex 32 ✍ 🎰 🥙 🔐 🤝 & 📨 ⚫️. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="115-130" +{!> ../../docs_src/security/tutorial004.py!} +``` + +//// - ```Python hl_lines="115-130" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="114-129" +{!> ../../docs_src/security/tutorial004_py310.py!} +``` - ```Python hl_lines="114-129" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +//// ### 📡 ℹ 🔃 🥙 "📄" `sub` @@ -239,8 +267,11 @@ $ openssl rand -hex 32 🆔: `johndoe` 🔐: `secret` -!!! check - 👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬. +/// check + +👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬. + +/// @@ -261,8 +292,11 @@ $ openssl rand -hex 32 -!!! note - 👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `. +/// note + +👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `. + +/// ## 🏧 ⚙️ ⏮️ `scopes` diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md index 765d94039..43d928ce7 100644 --- a/docs/em/docs/tutorial/security/simple-oauth2.md +++ b/docs/em/docs/tutorial/security/simple-oauth2.md @@ -32,14 +32,17 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ * `instagram_basic` ⚙️ 👱📔 / 👱📔. * `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍. -!!! info - Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. +/// info - ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. +Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. - 👈 ℹ 🛠️ 🎯. +⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. - Oauth2️⃣ 👫 🎻. +👈 ℹ 🛠️ 🎯. + +Oauth2️⃣ 👫 🎻. + +/// ## 📟 🤚 `username` & `password` @@ -49,17 +52,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ 🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="4 76" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="4 76" +{!> ../../docs_src/security/tutorial003.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="2 74" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="2 74" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// `OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️: @@ -68,29 +75,38 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ * 📦 `scope` 🏑 🦏 🎻, ✍ 🎻 🎏 🚀. * 📦 `grant_type`. -!!! tip - Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️. +/// tip + +Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️. - 🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`. +🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`. + +/// * 📦 `client_id` (👥 🚫 💪 ⚫️ 👆 🖼). * 📦 `client_secret` (👥 🚫 💪 ⚫️ 👆 🖼). -!!! info - `OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`. +/// info + +`OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`. - `OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂‍♂ ⚖. ⚫️ 🚮 👈 🌌 🗄. +`OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂‍♂ ⚖. ⚫️ 🚮 👈 🌌 🗄. - ✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗. +✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗. - ✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩. +✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩. + +/// ### ⚙️ 📨 💽 -!!! tip - 👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨. +/// tip + +👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨. + +👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️. - 👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️. +/// 🔜, 🤚 👩‍💻 📊 ⚪️➡️ (❌) 💽, ⚙️ `username` ⚪️➡️ 📨 🏑. @@ -98,17 +114,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ ❌, 👥 ⚙️ ⚠ `HTTPException`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3 77-79" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +```Python hl_lines="3 77-79" +{!> ../../docs_src/security/tutorial003.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1 75-77" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1 75-77" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// ### ✅ 🔐 @@ -134,17 +154,21 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ , 🧙‍♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩‍💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠). -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="80-83" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// - ```Python hl_lines="80-83" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="78-81" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="78-81" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +//// #### 🔃 `**user_dict` @@ -162,8 +186,11 @@ UserInDB( ) ``` -!!! info - 🌅 🏁 🔑 `**👩‍💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#about-user_indict){.internal-link target=_blank}. +/// info + +🌅 🏁 🔑 `**👩‍💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}. + +/// ## 📨 🤝 @@ -175,31 +202,41 @@ UserInDB( 👉 🙅 🖼, 👥 🔜 🍕 😟 & 📨 🎏 `username` 🤝. -!!! tip - ⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝. +/// tip + +⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝. + +✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪. + +/// + +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="85" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// - ✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪. +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.6️⃣ & 🔛" +```Python hl_lines="83" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="85" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="83" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼. -!!! tip - 🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼. +👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑. - 👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑. +⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧. - ⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧. +🎂, **FastAPI** 🍵 ⚫️ 👆. - 🎂, **FastAPI** 🍵 ⚫️ 👆. +/// ## ℹ 🔗 @@ -213,32 +250,39 @@ UserInDB( , 👆 🔗, 👥 🔜 🕴 🤚 👩‍💻 🚥 👩‍💻 🔀, ☑ 🔓, & 🦁: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="58-66 69-72 90" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="55-64 67-70 88" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` - ```Python hl_lines="58-66 69-72 90" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="55-64 67-70 88" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌. -!!! info - 🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌. +🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚. - 🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚. +💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`. - 💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`. +👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷. - 👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷. +✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧. - ✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧. +, 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩‍💻, 🔜 ⚖️ 🔮. - , 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩‍💻, 🔜 ⚖️ 🔮. +👈 💰 🐩... - 👈 💰 🐩... +/// ## 👀 ⚫️ 🎯 diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index ef08fcf4b..49162dd62 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -18,13 +18,19 @@ ⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**. -!!! tip - 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql +/// tip -!!! note - 👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️. +📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql - **FastAPI** 🎯 📟 🤪 🕧. +/// + +/// note + +👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️. + + **FastAPI** 🎯 📟 🤪 🕧. + +/// ## 🐜 @@ -58,8 +64,11 @@ 🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜. -!!! tip - 📤 🌓 📄 ⚙️ 🏒 📥 🩺. +/// tip + +📤 🌓 📄 ⚙️ 🏒 📥 🩺. + +/// ## 📁 📊 @@ -101,13 +110,13 @@ $ pip install sqlalchemy ### 🗄 🇸🇲 🍕 ```Python hl_lines="1-3" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### ✍ 💽 📛 🇸🇲 ```Python hl_lines="5-6" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` 👉 🖼, 👥 "🔗" 🗄 💽 (📂 📁 ⏮️ 🗄 💽). @@ -124,9 +133,11 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" ...& 🛠️ ⚫️ ⏮️ 👆 💽 📊 & 🎓 (📊 ✳, ✳ ⚖️ 🙆 🎏). -!!! tip +/// tip - 👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽. +👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽. + +/// ### ✍ 🇸🇲 `engine` @@ -135,7 +146,7 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" 👥 🔜 ⏪ ⚙️ 👉 `engine` 🎏 🥉. ```Python hl_lines="8-10" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` #### 🗒 @@ -148,15 +159,17 @@ connect_args={"check_same_thread": False} ...💪 🕴 `SQLite`. ⚫️ 🚫 💪 🎏 💽. -!!! info "📡 ℹ" +/// info | 📡 ℹ + +🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. - 🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. +👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨). - 👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨). +✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`. - ✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`. +, 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅‍♂ 💪 👈 🔢 🛠️. - , 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅‍♂ 💪 👈 🔢 🛠️. +/// ### ✍ `SessionLocal` 🎓 @@ -171,7 +184,7 @@ connect_args={"check_same_thread": False} ✍ `SessionLocal` 🎓, ⚙️ 🔢 `sessionmaker`: ```Python hl_lines="11" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### ✍ `Base` 🎓 @@ -181,7 +194,7 @@ connect_args={"check_same_thread": False} ⏪ 👥 🔜 😖 ⚪️➡️ 👉 🎓 ✍ 🔠 💽 🏷 ⚖️ 🎓 (🐜 🏷): ```Python hl_lines="13" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ## ✍ 💽 🏷 @@ -192,10 +205,13 @@ connect_args={"check_same_thread": False} 👥 🔜 ⚙️ 👉 `Base` 🎓 👥 ✍ ⏭ ✍ 🇸🇲 🏷. -!!! tip - 🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. +/// tip + +🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. +✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. + +/// 🗄 `Base` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛). @@ -204,7 +220,7 @@ connect_args={"check_same_thread": False} 👫 🎓 🇸🇲 🏷. ```Python hl_lines="4 7-8 18-19" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` `__tablename__` 🔢 💬 🇸🇲 📛 🏓 ⚙️ 💽 🔠 👫 🏷. @@ -220,7 +236,7 @@ connect_args={"check_same_thread": False} & 👥 🚶‍♀️ 🇸🇲 🎓 "🆎", `Integer`, `String`, & `Boolean`, 👈 🔬 🆎 💽, ❌. ```Python hl_lines="1 10-13 21-24" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` ### ✍ 💛 @@ -232,7 +248,7 @@ connect_args={"check_same_thread": False} 👉 🔜 ▶️️, 🌅 ⚖️ 🌘, "🎱" 🔢 👈 🔜 🔌 💲 ⚪️➡️ 🎏 🏓 🔗 👉 1️⃣. ```Python hl_lines="2 15 26" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` 🕐❔ 🔐 🔢 `items` `User`, `my_user.items`, ⚫️ 🔜 ✔️ 📇 `Item` 🇸🇲 🏷 (⚪️➡️ `items` 🏓) 👈 ✔️ 💱 🔑 ☝ 👉 ⏺ `users` 🏓. @@ -245,12 +261,15 @@ connect_args={"check_same_thread": False} 🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. -!!! tip - ❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. +/// tip + +❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. + +👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). +👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. - 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. +/// ### ✍ ▶️ Pydantic *🏷* / 🔗 @@ -262,23 +281,29 @@ connect_args={"check_same_thread": False} ✋️ 💂‍♂, `password` 🏆 🚫 🎏 Pydantic *🏷*, 🖼, ⚫️ 🏆 🚫 📨 ⚪️➡️ 🛠️ 🕐❔ 👂 👩‍💻. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1 4-6 9-10 21-22 25-26" +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python hl_lines="1 4-6 9-10 21-22 25-26" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// #### 🇸🇲 👗 & Pydantic 👗 @@ -306,26 +331,35 @@ name: str 🚫 🕴 🆔 📚 🏬, ✋️ 🌐 💽 👈 👥 🔬 Pydantic *🏷* 👂 🏬: `Item`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15-17 31-34" +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="15-17 31-34" +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="13-15 29-32" +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="13-15 29-32" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩‍💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`. -!!! tip - 👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩‍💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`. +/// ### ⚙️ Pydantic `orm_mode` @@ -335,32 +369,41 @@ name: str `Config` 🎓, ⚒ 🔢 `orm_mode = True`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15 19-20 31 36-37" +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python hl_lines="15 19-20 31 36-37" +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="13 17-18 29 34-35" +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="13 17-18 29 34-35" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖: -!!! tip - 👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖: +`orm_mode = True` - `orm_mode = True` +⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭. - ⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭. +👉 ⚒ 📁 💲, 🚫 📣 🆎. - 👉 ⚒ 📁 💲, 🚫 📣 🆎. +/// Pydantic `orm_mode` 🔜 💬 Pydantic *🏷* ✍ 💽 🚥 ⚫️ 🚫 `dict`, ✋️ 🐜 🏷 (⚖️ 🙆 🎏 ❌ 🎚 ⏮️ 🔢). @@ -423,11 +466,14 @@ current_user.items * ✍ 💗 🏬. ```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - 🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩‍💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫. +/// tip + +🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩‍💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫. + +/// ### ✍ 💽 @@ -441,37 +487,46 @@ current_user.items * `refresh` 👆 👐 (👈 ⚫️ 🔌 🙆 🆕 📊 ⚪️➡️ 💽, 💖 🏗 🆔). ```Python hl_lines="18-24 31-36" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - 🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐. +/// tip - ✋️ ⚫️❔ 🛠️ 👩‍💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸. +🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐. - & ⤴️ 🚶‍♀️ `hashed_password` ❌ ⏮️ 💲 🖊. +✋️ ⚫️❔ 🛠️ 👩‍💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸. -!!! warning - 👉 🖼 🚫 🔐, 🔐 🚫#️⃣. + & ⤴️ 🚶‍♀️ `hashed_password` ❌ ⏮️ 💲 🖊. - 🎰 👨‍❤‍👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢. +/// - 🌅 ℹ, 🚶 🔙 💂‍♂ 📄 🔰. +/// warning - 📥 👥 🎯 🕴 🔛 🧰 & 👨‍🔧 💽. +👉 🖼 🚫 🔐, 🔐 🚫#️⃣. -!!! tip - ↩️ 🚶‍♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️: +🎰 👨‍❤‍👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢. - `item.dict()` +🌅 ℹ, 🚶 🔙 💂‍♂ 📄 🔰. - & ⤴️ 👥 🚶‍♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️: +📥 👥 🎯 🕴 🔛 🧰 & 👨‍🔧 💽. - `Item(**item.dict())` +/// - & ⤴️ 👥 🚶‍♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️: +/// tip - `Item(**item.dict(), owner_id=user_id)` +↩️ 🚶‍♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️: + +`item.dict()` + + & ⤴️ 👥 🚶‍♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️: + +`Item(**item.dict())` + + & ⤴️ 👥 🚶‍♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️: + +`Item(**item.dict(), owner_id=user_id)` + +/// ## 👑 **FastAPI** 📱 @@ -481,17 +536,21 @@ current_user.items 📶 🙃 🌌 ✍ 💽 🏓: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="9" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="7" +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// #### ⚗ 🗒 @@ -501,7 +560,7 @@ current_user.items "🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️. -👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. +👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. ### ✍ 🔗 @@ -515,63 +574,81 @@ current_user.items 👆 🔗 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 👈 🔜 ⚙️ 👁 📨, & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="15-20" +{!> ../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="13-18" +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="15-20" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info - ```Python hl_lines="13-18" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. -!!! info - 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. + & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. +👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. +✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank} - ✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](./dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} +/// & ⤴️, 🕐❔ ⚙️ 🔗 *➡ 🛠️ 🔢*, 👥 📣 ⚫️ ⏮️ 🆎 `Session` 👥 🗄 🔗 ⚪️➡️ 🇸🇲. 👉 🔜 ⤴️ 🤝 👥 👍 👨‍🎨 🐕‍🦺 🔘 *➡ 🛠️ 🔢*, ↩️ 👨‍🎨 🔜 💭 👈 `db` 🔢 🆎 `Session`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="24 32 38 47 53" +{!> ../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="22 30 36 45 51" +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="24 32 38 47 53" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info | 📡 ℹ - ```Python hl_lines="22 30 36 45 51" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨‍🎨 🚫 🤙 💭 ⚫️❔ 👩‍🔬 🚚. -!!! info "📡 ℹ" - 🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨‍🎨 🚫 🤙 💭 ⚫️❔ 👩‍🔬 🚚. +✋️ 📣 🆎 `Session`, 👨‍🎨 🔜 💪 💭 💪 👩‍🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕‍🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚. - ✋️ 📣 🆎 `Session`, 👨‍🎨 🔜 💪 💭 💪 👩‍🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕‍🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚. +/// ### ✍ 👆 **FastAPI** *➡ 🛠️* 🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="23-28 31-34 37-42 45-49 52-55" +{!> ../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// - ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="21-26 29-32 35-40 43-47 50-53" +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// 👥 🏗 💽 🎉 ⏭ 🔠 📨 🔗 ⏮️ `yield`, & ⤴️ 📪 ⚫️ ⏮️. @@ -579,15 +656,21 @@ current_user.items ⏮️ 👈, 👥 💪 🤙 `crud.get_user` 🔗 ⚪️➡️ 🔘 *➡ 🛠️ 🔢* & ⚙️ 👈 🎉. -!!! tip - 👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷. +/// tip + +👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷. + +✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩‍💻, ⏮️ 🌐 😐 ⛽ & 🔬. + +/// + +/// tip - ✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩‍💻, ⏮️ 🌐 😐 ⛽ & 🔬. +👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`. -!!! tip - 👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`. +✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩‍💻 🛎, 🍵 ⚠. - ✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩‍💻 🛎, 🍵 ⚠. +/// ### 🔃 `def` 🆚 `async def` @@ -616,11 +699,17 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ... ``` -!!! info - 🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. +/// info -!!! note "📶 📡 ℹ" - 🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#very-technical-details){.internal-link target=_blank} 🩺. +🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. + +/// + +/// note | 📶 📡 ℹ + +🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺. + +/// ## 🛠️ @@ -643,62 +732,74 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/database.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` * `sql_app/models.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` * `sql_app/schemas.py`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +```Python +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// * `sql_app/crud.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` * `sql_app/main.py`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python +{!> ../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// ## ✅ ⚫️ 👆 💪 📁 👉 📟 & ⚙️ ⚫️. -!!! info +/// info + +👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺. - 👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺. +/// ⤴️ 👆 💪 🏃 ⚫️ ⏮️ Uvicorn: @@ -739,24 +840,31 @@ $ uvicorn sql_app.main:app --reload 🛠️ 👥 🔜 🚮 (🔢) 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 🔠 📨, 🚮 ⚫️ 📨 & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="14-22" +{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - ```Python hl_lines="14-22" - {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} - ``` +```Python hl_lines="12-20" +{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info - ```Python hl_lines="12-20" - {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} - ``` +👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. -!!! info - 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. + & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. +👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. +/// ### 🔃 `request.state` @@ -777,10 +885,16 @@ $ uvicorn sql_app.main:app --reload * , 🔗 🔜 ✍ 🔠 📨. * 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽. -!!! tip - ⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼. +/// tip + +⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼. + +/// + +/// info + +🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**. -!!! info - 🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**. +⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾. - ⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾. +/// diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md index 6090c5338..c9bb9ff6a 100644 --- a/docs/em/docs/tutorial/static-files.md +++ b/docs/em/docs/tutorial/static-files.md @@ -8,13 +8,16 @@ * "🗻" `StaticFiles()` 👐 🎯 ➡. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`. +/// note | 📡 ℹ - **FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩‍💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`. + +**FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩‍💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃. + +/// ### ⚫️❔ "🗜" diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 999d67cd3..27cf9f16e 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## ⚙️ `TestClient` -!!! info - ⚙️ `TestClient`, 🥇 ❎ `httpx`. +/// info - 🤶 Ⓜ. `pip install httpx`. +⚙️ `TestClient`, 🥇 ❎ `httpx`. + +🤶 Ⓜ. `pip install httpx`. + +/// 🗄 `TestClient`. @@ -24,23 +27,32 @@ ✍ 🙅 `assert` 📄 ⏮️ 🐩 🐍 🧬 👈 👆 💪 ✅ (🔄, 🐩 `pytest`). ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip - 👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`. +/// tip + +👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`. + + & 🤙 👩‍💻 😐 🤙, 🚫 ⚙️ `await`. + +👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢. + +/// + +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.testclient import TestClient`. - & 🤙 👩‍💻 😐 🤙, 🚫 ⚙️ `await`. +**FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - 👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢. +/// -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.testclient import TestClient`. +/// tip - **FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰. -!!! tip - 🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰. +/// ## 🎏 💯 @@ -50,7 +62,7 @@ ### **FastAPI** 📱 📁 -➡️ 💬 👆 ✔️ 📁 📊 🔬 [🦏 🈸](./bigger-applications.md){.internal-link target=_blank}: +➡️ 💬 👆 ✔️ 📁 📊 🔬 [🦏 🈸](bigger-applications.md){.internal-link target=_blank}: ``` . @@ -63,7 +75,7 @@ ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### 🔬 📁 @@ -81,7 +93,7 @@ ↩️ 👉 📁 🎏 📦, 👆 💪 ⚙️ ⚖ 🗄 🗄 🎚 `app` ⚪️➡️ `main` 🕹 (`main.py`): ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ...& ✔️ 📟 💯 💖 ⏭. @@ -110,24 +122,28 @@ 👯‍♂️ *➡ 🛠️* 🚚 `X-Token` 🎚. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// ### ↔ 🔬 📁 👆 💪 ⤴️ ℹ `test_main.py` ⏮️ ↔ 💯: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` 🕐❔ 👆 💪 👩‍💻 🚶‍♀️ ℹ 📨 & 👆 🚫 💭 ❔, 👆 💪 🔎 (🇺🇸🔍) ❔ ⚫️ `httpx`, ⚖️ ❔ ⚫️ ⏮️ `requests`, 🇸🇲 🔧 ⚓️ 🔛 📨' 🔧. @@ -144,10 +160,13 @@ 🌖 ℹ 🔃 ❔ 🚶‍♀️ 💽 👩‍💻 (⚙️ `httpx` ⚖️ `TestClient`) ✅ 🇸🇲 🧾. -!!! info - 🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷. +/// info + +🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷. + +🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}. - 🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}. +/// ## 🏃 ⚫️ diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 827581de5..9e411a631 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,12 @@ Articles: English: + - author: Balthazar Rouberol + author_link: https://balthazar-rouberol.com + link: https://blog.balthazar-rouberol.com/how-to-profile-a-fastapi-asynchronous-request + title: How to profile a FastAPI asynchronous request + - author: Stephen Siegert - Neon + link: https://neon.tech/blog/deploy-a-serverless-fastapi-app-with-neon-postgres-and-aws-app-runner-at-any-scale + title: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale - author: Kurtis Pykes - NVIDIA link: https://developer.nvidia.com/blog/building-a-machine-learning-microservice-with-fastapi/ title: Building a Machine Learning Microservice with FastAPI @@ -24,7 +31,7 @@ Articles: - author: Nicoló Lino author_link: https://www.nlino.com link: https://github.com/softwarebloat/python-tracing-demo - title: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo + title: Instrument FastAPI with OpenTelemetry tracing and visualize traces in Grafana Tempo. - author: Mikhail Rozhkov, Elena Samuylova author_link: https://www.linkedin.com/in/mnrozhkov/ link: https://www.evidentlyai.com/blog/fastapi-tutorial @@ -257,6 +264,18 @@ Articles: author_link: https://medium.com/@krishnardt365 link: https://medium.com/@krishnardt365/fastapi-docker-and-postgres-91943e71be92 title: Fastapi, Docker(Docker compose) and Postgres + - author: Devon Ray + author_link: https://devonray.com + link: https://devonray.com/blog/deploying-a-fastapi-project-using-aws-lambda-aurora-cdk + title: Deployment using Docker, Lambda, Aurora, CDK & GH Actions + - author: Shubhendra Kushwaha + author_link: https://www.linkedin.com/in/theshubhendra/ + link: https://theshubhendra.medium.com/mastering-soft-delete-advanced-sqlalchemy-techniques-4678f4738947 + title: 'Mastering Soft Delete: Advanced SQLAlchemy Techniques' + - author: Shubhendra Kushwaha + author_link: https://www.linkedin.com/in/theshubhendra/ + link: https://theshubhendra.medium.com/role-based-row-filtering-advanced-sqlalchemy-techniques-733e6b1328f6 + title: 'Role based row filtering: Advanced SQLAlchemy Techniques' German: - author: Marcel Sander (actidoo) author_link: https://www.actidoo.com @@ -320,6 +339,10 @@ Articles: link: https://qiita.com/mtitg/items/47770e9a562dd150631d title: FastAPI|DB接続してCRUDするPython製APIサーバーを構築 Portuguese: + - author: Eduardo Mendes + author_link: https://bolha.us/@dunossauro + link: https://fastapidozero.dunossauro.com/ + title: FastAPI do ZERO - author: Jessica Temporal author_link: https://jtemporal.com/socials link: https://jtemporal.com/dicas-para-migrar-de-flask-para-fastapi-e-vice-versa/ @@ -347,6 +370,11 @@ Articles: author_link: http://editor.leonh.space/ link: https://editor.leonh.space/2022/tortoise/ title: 'Tortoise ORM / FastAPI 整合快速筆記' + Spanish: + - author: Eduardo Zepeda + author_link: https://coffeebytes.dev/en/authors/eduardo-zepeda/ + link: https://coffeebytes.dev/es/python-fastapi-el-mejor-framework-de-python/ + title: 'Tutorial de FastAPI, ¿el mejor framework de Python?' Podcasts: English: - author: Real Python diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index fb690708f..5f0be61c2 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -2,9 +2,6 @@ sponsors: - - login: bump-sh avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 url: https://github.com/bump-sh - - login: Alek99 - avatarUrl: https://avatars.githubusercontent.com/u/38776361?u=bd6c163fe787c2de1a26c881598e54b67e2482dd&v=4 - url: https://github.com/Alek99 - login: porter-dev avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 url: https://github.com/porter-dev @@ -14,9 +11,15 @@ sponsors: - login: zanfaruqui avatarUrl: https://avatars.githubusercontent.com/u/104461687?v=4 url: https://github.com/zanfaruqui + - login: Alek99 + avatarUrl: https://avatars.githubusercontent.com/u/38776361?u=bd6c163fe787c2de1a26c881598e54b67e2482dd&v=4 + url: https://github.com/Alek99 - login: cryptapi avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4 url: https://github.com/cryptapi + - login: Kong + avatarUrl: https://avatars.githubusercontent.com/u/962416?v=4 + url: https://github.com/Kong - login: codacy avatarUrl: https://avatars.githubusercontent.com/u/1834093?v=4 url: https://github.com/codacy @@ -48,7 +51,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/74335107?v=4 url: https://github.com/xoflare - login: marvin-robot - avatarUrl: https://avatars.githubusercontent.com/u/41086007?u=091c5cb75af363123d66f58194805a97220ee1a7&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/41086007?u=b9fcab402d0cd0aec738b6574fe60855cb0cd36d&v=4 url: https://github.com/marvin-robot - login: BoostryJP avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4 @@ -62,21 +65,12 @@ sponsors: - - login: americanair avatarUrl: https://avatars.githubusercontent.com/u/12281813?v=4 url: https://github.com/americanair - - login: 84adam - avatarUrl: https://avatars.githubusercontent.com/u/13172004?u=293f3cc6bb7e6f6ecfcdd64489a3202468321254&v=4 - url: https://github.com/84adam - login: CanoaPBC avatarUrl: https://avatars.githubusercontent.com/u/64223768?v=4 url: https://github.com/CanoaPBC - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries - - login: doseiai - avatarUrl: https://avatars.githubusercontent.com/u/57115726?v=4 - url: https://github.com/doseiai - - login: AccentDesign - avatarUrl: https://avatars.githubusercontent.com/u/2429332?v=4 - url: https://github.com/AccentDesign - login: mangualero avatarUrl: https://avatars.githubusercontent.com/u/3422968?u=c59272d7b5a912d6126fd6c6f17db71e20f506eb&v=4 url: https://github.com/mangualero @@ -92,7 +86,10 @@ sponsors: - login: povilasb avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 url: https://github.com/povilasb -- - login: upciti +- - login: jhundman + avatarUrl: https://avatars.githubusercontent.com/u/24263908?v=4 + url: https://github.com/jhundman + - login: upciti avatarUrl: https://avatars.githubusercontent.com/u/43346262?v=4 url: https://github.com/upciti - - login: samuelcolvin @@ -101,18 +98,18 @@ sponsors: - login: Kludex avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - - login: koconder - avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 - url: https://github.com/koconder + - login: b-rad-c + avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4 + url: https://github.com/b-rad-c - login: ehaca avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 url: https://github.com/ehaca + - login: raphaellaude + avatarUrl: https://avatars.githubusercontent.com/u/28026311?u=9ae4b158c0d2cb29ebd46df6b6edb7de08a67566&v=4 + url: https://github.com/raphaellaude - login: timlrx avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 url: https://github.com/timlrx - - login: mattmalcher - avatarUrl: https://avatars.githubusercontent.com/u/31312775?v=4 - url: https://github.com/mattmalcher - login: Leay15 avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 url: https://github.com/Leay15 @@ -122,6 +119,9 @@ sponsors: - login: ProteinQure avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 url: https://github.com/ProteinQure + - login: catherinenelson1 + avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 + url: https://github.com/catherinenelson1 - login: jsoques avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4 url: https://github.com/jsoques @@ -137,21 +137,18 @@ sponsors: - login: mjohnsey avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 url: https://github.com/mjohnsey + - login: ashi-agrawal + avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4 + url: https://github.com/ashi-agrawal + - login: sepsi77 + avatarUrl: https://avatars.githubusercontent.com/u/18682303?v=4 + url: https://github.com/sepsi77 - login: wedwardbeck avatarUrl: https://avatars.githubusercontent.com/u/19333237?u=1de4ae2bf8d59eb4c013f21d863cbe0f2010575f&v=4 url: https://github.com/wedwardbeck - login: RaamEEIL avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4 url: https://github.com/RaamEEIL - - login: Filimoa - avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4 - url: https://github.com/Filimoa - - login: b-rad-c - avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4 - url: https://github.com/b-rad-c - - login: patsatsia - avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 - url: https://github.com/patsatsia - login: anthonycepeda avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 url: https://github.com/anthonycepeda @@ -164,12 +161,18 @@ sponsors: - login: DelfinaCare avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 url: https://github.com/DelfinaCare + - login: Eruditis + avatarUrl: https://avatars.githubusercontent.com/u/95244703?v=4 + url: https://github.com/Eruditis + - login: jugeeem + avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4 + url: https://github.com/jugeeem - login: apitally avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4 url: https://github.com/apitally - - login: thenickben - avatarUrl: https://avatars.githubusercontent.com/u/40610922?u=1e907d904041b7c91213951a3cb344cd37c14aaf&v=4 - url: https://github.com/thenickben + - login: logic-automation + avatarUrl: https://avatars.githubusercontent.com/u/144732884?v=4 + url: https://github.com/logic-automation - login: ddilidili avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 url: https://github.com/ddilidili @@ -182,15 +185,12 @@ sponsors: - login: prodhype avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 url: https://github.com/prodhype - - login: yakkonaut - avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4 - url: https://github.com/yakkonaut + - login: patsatsia + avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 + url: https://github.com/patsatsia - login: tcsmith avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 url: https://github.com/tcsmith - - login: mickaelandrieu - avatarUrl: https://avatars.githubusercontent.com/u/1247388?u=599f6e73e452a9453f2bd91e5c3100750e731ad4&v=4 - url: https://github.com/mickaelandrieu - login: dodo5522 avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 url: https://github.com/dodo5522 @@ -209,12 +209,27 @@ sponsors: - login: dblackrun avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4 url: https://github.com/dblackrun + - login: zsinx6 + avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 + url: https://github.com/zsinx6 + - login: kennywakeland + avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4 + url: https://github.com/kennywakeland + - login: simw + avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 + url: https://github.com/simw + - login: koconder + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 + url: https://github.com/koconder - login: jstanden avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 url: https://github.com/jstanden - login: andreaso avatarUrl: https://avatars.githubusercontent.com/u/285964?u=837265cc7562c0685f25b2d81cd9de0434fe107c&v=4 url: https://github.com/andreaso + - login: robintw + avatarUrl: https://avatars.githubusercontent.com/u/296686?v=4 + url: https://github.com/robintw - login: pamelafox avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4 url: https://github.com/pamelafox @@ -233,9 +248,6 @@ sponsors: - login: mintuhouse avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 url: https://github.com/mintuhouse - - login: simw - avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 - url: https://github.com/simw - login: Rehket avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4 url: https://github.com/Rehket @@ -248,15 +260,6 @@ sponsors: - login: wdwinslow avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 url: https://github.com/wdwinslow - - login: drcat101 - avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 - url: https://github.com/drcat101 - - login: zsinx6 - avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 - url: https://github.com/zsinx6 - - login: kennywakeland - avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4 - url: https://github.com/kennywakeland - login: aacayaco avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4 url: https://github.com/aacayaco @@ -266,6 +269,9 @@ sponsors: - login: jgreys avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=096820d1ef89877d57d0f68e669ead8b0fde84df&v=4 url: https://github.com/jgreys + - login: Ryandaydev + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 + url: https://github.com/Ryandaydev - login: jaredtrog avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4 url: https://github.com/jaredtrog @@ -276,14 +282,11 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/5300907?u=5b5452725ddb391b2caaebf34e05aba873591c3a&v=4 url: https://github.com/ennui93 - login: ternaus - avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=fabc8d75c921b3380126adb5a931c5da6e7db04f&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=513a26b02a39e7a28d587cd37c6cc877ea368e6e&v=4 url: https://github.com/ternaus - login: eseglem avatarUrl: https://avatars.githubusercontent.com/u/5920492?u=208d419cf667b8ac594c82a8db01932c7e50d057&v=4 url: https://github.com/eseglem - - login: Yaleesa - avatarUrl: https://avatars.githubusercontent.com/u/6135475?v=4 - url: https://github.com/Yaleesa - login: FernandoCelmer avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4 url: https://github.com/FernandoCelmer @@ -293,6 +296,12 @@ sponsors: - - login: pawamoy avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 url: https://github.com/pawamoy + - login: SebTota + avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 + url: https://github.com/SebTota + - login: nisutec + avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 + url: https://github.com/nisutec - login: hoenie-ams avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4 url: https://github.com/hoenie-ams @@ -302,21 +311,18 @@ sponsors: - login: rlnchow avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 url: https://github.com/rlnchow - - login: HosamAlmoghraby - avatarUrl: https://avatars.githubusercontent.com/u/32025281?u=aa1b09feabccbf9dc506b81c71155f32d126cefa&v=4 - url: https://github.com/HosamAlmoghraby - - login: dvlpjrs - avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 - url: https://github.com/dvlpjrs - login: engineerjoe440 avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 url: https://github.com/engineerjoe440 - login: bnkc - avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&v=4 url: https://github.com/bnkc - - login: curegit - avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 - url: https://github.com/curegit + - login: DevOpsKev + avatarUrl: https://avatars.githubusercontent.com/u/36336550?u=6ccd5978fdaab06f37e22f2a14a7439341df7f67&v=4 + url: https://github.com/DevOpsKev + - login: petercool + avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4 + url: https://github.com/petercool - login: JimFawkes avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 url: https://github.com/JimFawkes @@ -332,42 +338,33 @@ sponsors: - login: jangia avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4 url: https://github.com/jangia + - login: jackleeio + avatarUrl: https://avatars.githubusercontent.com/u/20477587?u=c5184dab6d021733d10c8f975b20e391856303d6&v=4 + url: https://github.com/jackleeio - login: shuheng-liu avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4 url: https://github.com/shuheng-liu - login: pers0n4 avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4 url: https://github.com/pers0n4 - - login: SebTota - avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 - url: https://github.com/SebTota - - login: nisutec - avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 - url: https://github.com/nisutec - - login: 0417taehyun - avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 - url: https://github.com/0417taehyun + - login: curegit + avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 + url: https://github.com/curegit - login: fernandosmither - avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=a76a037b5d674938a75d2cff862fb6dfd63ec214&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=f79753eb207d01cca5bbb91ac62db6123e7622d1&v=4 url: https://github.com/fernandosmither - - login: romabozhanovgithub - avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 - url: https://github.com/romabozhanovgithub + - login: PunRabbit + avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4 + url: https://github.com/PunRabbit - login: PelicanQ avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 url: https://github.com/PelicanQ - - login: tim-habitat - avatarUrl: https://avatars.githubusercontent.com/u/86600518?u=7389dd77fe6a0eb8d13933356120b7d2b32d7bb4&v=4 - url: https://github.com/tim-habitat - - login: jugeeem - avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4 - url: https://github.com/jugeeem - login: tahmarrrr23 avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4 url: https://github.com/tahmarrrr23 - - login: lukzmu - avatarUrl: https://avatars.githubusercontent.com/u/155924127?u=2e52e40b3134bef370b52bf2e40a524f307c2a05&v=4 - url: https://github.com/lukzmu + - login: zk-Call + avatarUrl: https://avatars.githubusercontent.com/u/147117264?v=4 + url: https://github.com/zk-Call - login: kristiangronberg avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4 url: https://github.com/kristiangronberg @@ -377,21 +374,27 @@ sponsors: - login: arrrrrmin avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=36a3880a6eb29309c19e6cadbb173bafbe91deb1&v=4 url: https://github.com/arrrrrmin - - login: rbtrsv - avatarUrl: https://avatars.githubusercontent.com/u/43938206?u=09955f324da271485a7edaf9241f449e88a1388a&v=4 - url: https://github.com/rbtrsv - login: mobyw avatarUrl: https://avatars.githubusercontent.com/u/44370805?v=4 url: https://github.com/mobyw - login: ArtyomVancyan avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 url: https://github.com/ArtyomVancyan + - login: harol97 + avatarUrl: https://avatars.githubusercontent.com/u/49042862?u=2b18e115ab73f5f09a280be2850f93c58a12e3d2&v=4 + url: https://github.com/harol97 - login: hgalytoby - avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=62c7ff3519858423579676cd0efbd7e3f1ffe63a&v=4 url: https://github.com/hgalytoby - login: conservative-dude avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 url: https://github.com/conservative-dude + - login: Joaopcamposs + avatarUrl: https://avatars.githubusercontent.com/u/57376574?u=699d5ba5ee66af1d089df6b5e532b97169e73650&v=4 + url: https://github.com/Joaopcamposs + - login: browniebroke + avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 + url: https://github.com/browniebroke - login: miguelgr avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4 url: https://github.com/miguelgr @@ -407,9 +410,6 @@ sponsors: - login: cbonoz avatarUrl: https://avatars.githubusercontent.com/u/2351087?u=fd3e8030b2cc9fbfbb54a65e9890c548a016f58b&v=4 url: https://github.com/cbonoz - - login: anthonycorletti - avatarUrl: https://avatars.githubusercontent.com/u/3477132?u=dfe51d2080fbd3fee81e05911cd8d50da9dcc709&v=4 - url: https://github.com/anthonycorletti - login: ddanier avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 url: https://github.com/ddanier @@ -434,9 +434,6 @@ sponsors: - login: tochikuji avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 url: https://github.com/tochikuji - - login: browniebroke - avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 - url: https://github.com/browniebroke - login: KentShikama avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4 url: https://github.com/KentShikama @@ -452,8 +449,11 @@ sponsors: - login: moonape1226 avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 url: https://github.com/moonape1226 + - login: msehnout + avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 + url: https://github.com/msehnout - login: xncbf - avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=ee91e210ae93b9cdd8f248b21cb028316cc0b747&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=2ef1ede118a72c170805f50b9ad07341fd16a354&v=4 url: https://github.com/xncbf - login: DMantis avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 @@ -476,9 +476,15 @@ sponsors: - login: dzoladz avatarUrl: https://avatars.githubusercontent.com/u/10561752?u=5ee314d54aa79592c18566827ad8914debd5630d&v=4 url: https://github.com/dzoladz + - login: Zuzah + avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4 + url: https://github.com/Zuzah - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa + - login: Graeme22 + avatarUrl: https://avatars.githubusercontent.com/u/4185684?u=498182a42300d7bcd4de1215190cb17eb501136c&v=4 + url: https://github.com/Graeme22 - login: danielunderwood avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 url: https://github.com/danielunderwood @@ -489,7 +495,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/5250987?u=4ed9a120c89805a8aefda1cbdc0cf6512e64d1b4&v=4 url: https://github.com/sdevkota - login: brizzbuzz - avatarUrl: https://avatars.githubusercontent.com/u/5607577?u=1ffbf39f5bb8736b75c0d235707d6e8f803725c5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/5607577?u=58d5aae33bc97e52f11f334d2702e8710314b5c1&v=4 url: https://github.com/brizzbuzz - login: Baghdady92 avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4 @@ -497,21 +503,30 @@ sponsors: - login: jakeecolution avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4 url: https://github.com/jakeecolution + - login: stephane-rbn + avatarUrl: https://avatars.githubusercontent.com/u/5939522?u=eb7ffe768fa3bcbcd04de14fe4a47444cc00ec4c&v=4 + url: https://github.com/stephane-rbn - - login: danburonline avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 url: https://github.com/danburonline + - login: AliYmn + avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=0de5a262e8b4dc0a08d065f30f7a39941e246530&v=4 + url: https://github.com/AliYmn - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu + - login: tran-hai-long + avatarUrl: https://avatars.githubusercontent.com/u/119793901?u=3b173a845dcf099b275bdc9713a69cbbc36040ce&v=4 + url: https://github.com/tran-hai-long - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd - - login: Patechoc - avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 - url: https://github.com/Patechoc - login: ssbarnea avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c2efbf6fea2737e21dfc6b1113c4edc9644e9eaa&v=4 url: https://github.com/ssbarnea - login: yuawn avatarUrl: https://avatars.githubusercontent.com/u/5111198?u=5315576f3fe1a70fd2d0f02181588f4eea5d353d&v=4 url: https://github.com/yuawn + - login: dongzhenye + avatarUrl: https://avatars.githubusercontent.com/u/5765843?u=fe420c9a4c41e5b060faaf44029f5485616b470d&v=4 + url: https://github.com/dongzhenye diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml new file mode 100644 index 000000000..a3a6b912d --- /dev/null +++ b/docs/en/data/members.yml @@ -0,0 +1,22 @@ +members: +- login: tiangolo + avatar_url: https://avatars.githubusercontent.com/u/1326112 + url: https://github.com/tiangolo +- login: Kludex + avatar_url: https://avatars.githubusercontent.com/u/7353520 + url: https://github.com/Kludex +- login: alejsdev + avatar_url: https://avatars.githubusercontent.com/u/90076947 + url: https://github.com/alejsdev +- login: svlandeg + avatar_url: https://avatars.githubusercontent.com/u/8796347 + url: https://github.com/svlandeg +- login: YuriiMotov + avatar_url: https://avatars.githubusercontent.com/u/109919500 + url: https://github.com/YuriiMotov +- login: estebanx64 + avatar_url: https://avatars.githubusercontent.com/u/10840422 + url: https://github.com/estebanx64 +- login: patrick91 + avatar_url: https://avatars.githubusercontent.com/u/667029 + url: https://github.com/patrick91 diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 710c650fd..02d1779e0 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,12 +1,12 @@ maintainers: - login: tiangolo - answers: 1878 - prs: 550 + answers: 1885 + prs: 577 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 596 + count: 608 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu @@ -14,7 +14,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu - login: jgould22 - count: 232 + count: 241 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: Mause @@ -23,7 +23,7 @@ experts: url: https://github.com/Mause - login: ycd count: 217 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: JarroVGIT count: 193 @@ -41,42 +41,50 @@ experts: count: 126 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 +- login: YuriiMotov + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: raphaelauv count: 83 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 url: https://github.com/raphaelauv -- login: ghandic - count: 71 - avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 - url: https://github.com/ghandic - login: ArcLightSlavik count: 71 avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 url: https://github.com/ArcLightSlavik +- login: ghandic + count: 71 + avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 + url: https://github.com/ghandic +- login: JavierSanchezCastro + count: 64 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: falkben count: 59 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben -- login: JavierSanchezCastro - count: 52 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: n8sty - count: 52 + count: 56 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty +- login: acidjunk + count: 50 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: yinziyan1206 + count: 49 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 - login: sm-Fifteen count: 49 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen -- login: yinziyan1206 - count: 48 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: acidjunk - count: 47 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk +- login: insomnes + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 + url: https://github.com/insomnes - login: Dustyposa count: 45 avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 @@ -85,10 +93,6 @@ experts: count: 45 avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 url: https://github.com/adriangb -- login: insomnes - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 - url: https://github.com/insomnes - login: frankie567 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 @@ -121,6 +125,10 @@ experts: count: 28 avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4 url: https://github.com/prostomarkeloff +- login: hasansezertasan + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: dbanty count: 26 avatarUrl: https://avatars.githubusercontent.com/u/43723790?u=9bcce836bbce55835291c5b2ac93a4e311f4b3c3&v=4 @@ -129,10 +137,6 @@ experts: count: 25 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes -- login: YuriiMotov - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov - login: acnebs count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 @@ -141,14 +145,14 @@ experts: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 url: https://github.com/SirTelemak +- login: nymous + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous - login: chrisK824 count: 22 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 -- login: nymous - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous - login: rafsaf count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 @@ -165,10 +169,6 @@ experts: count: 20 avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 url: https://github.com/chris-allnutt -- login: hasansezertasan - count: 19 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan - login: retnikt count: 18 avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 @@ -177,6 +177,10 @@ experts: count: 18 avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 url: https://github.com/zoliknemet +- login: nkhitrov + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=66ee21316275ef356081c2efc4ed7a4572e690dc&v=4 + url: https://github.com/nkhitrov - login: Hultner count: 17 avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4 @@ -185,301 +189,257 @@ experts: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/1765494?u=5b1ab7c582db4b4016fa31affe977d10af108ad4&v=4 url: https://github.com/harunyasar -- login: nkhitrov - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=66ee21316275ef356081c2efc4ed7a4572e690dc&v=4 - url: https://github.com/nkhitrov - login: caeser1996 count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 url: https://github.com/caeser1996 -- login: jonatasoli +- login: dstlny count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 - url: https://github.com/jonatasoli + avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 + url: https://github.com/dstlny last_month_experts: - login: YuriiMotov - count: 24 + count: 29 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: killjoy1221 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 - login: Kludex - count: 17 + count: 7 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: JavierSanchezCastro - count: 13 + count: 5 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro -- login: jgould22 - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 -- login: GodMoonGoodman - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 - url: https://github.com/GodMoonGoodman +- login: hasansezertasan + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: PhysicallyActive + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive - login: n8sty - count: 4 + count: 2 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty -- login: flo-at - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 - url: https://github.com/flo-at -- login: estebanx64 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 -- login: ahmedabdou14 +- login: pedroconceicao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 -- login: chrisK824 + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao +- login: PREPONDERANCE count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: ThirVondukr - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: richin13 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: aanchlia count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 - url: https://github.com/richin13 -- login: hussein-awala + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: 0sahil count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 - url: https://github.com/hussein-awala -- login: admo1 + avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 + url: https://github.com/0sahil +- login: jgould22 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 - url: https://github.com/admo1 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 three_months_experts: -- login: Kludex - count: 90 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex +- login: YuriiMotov + count: 101 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: JavierSanchezCastro - count: 28 + count: 20 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro +- login: Kludex + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex - login: jgould22 - count: 28 + count: 14 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: YuriiMotov - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov -- login: n8sty - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty +- login: killjoy1221 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 - login: hasansezertasan - count: 12 + count: 8 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -- login: dolfinus - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 - url: https://github.com/dolfinus -- login: aanchlia +- login: PhysicallyActive count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia -- login: Ventura94 - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 - url: https://github.com/Ventura94 -- login: shashstormer + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: n8sty count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 - url: https://github.com/shashstormer -- login: GodMoonGoodman + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: sehraramiz count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 - url: https://github.com/GodMoonGoodman -- login: flo-at + avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + url: https://github.com/sehraramiz +- login: acidjunk count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 - url: https://github.com/flo-at + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk - login: estebanx64 - count: 4 + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 -- login: ahmedabdou14 +- login: PREPONDERANCE count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE - login: chrisK824 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 -- login: fmelihh +- login: ryanisn count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 - url: https://github.com/fmelihh -- login: acidjunk - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk -- login: agn-7 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14202344?u=a1d05998ceaf4d06d1063575a7c4ef6e7ae5890e&v=4 - url: https://github.com/agn-7 -- login: ThirVondukr - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: richin13 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 - url: https://github.com/richin13 -- login: hussein-awala - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 - url: https://github.com/hussein-awala -- login: JoshYuJump - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump -- login: bhumkong - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 - url: https://github.com/bhumkong -- login: falkben + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn +- login: pythonweb2 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: omarcruzpantoja + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja +- login: mskrip count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 - url: https://github.com/falkben -- login: mielvds + avatarUrl: https://avatars.githubusercontent.com/u/17459600?u=10019d5c38ae3374dd4a6743b0223e56a78d4855&v=4 + url: https://github.com/mskrip +- login: pedroconceicao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 - url: https://github.com/mielvds -- login: admo1 + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao +- login: Jackiexiao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 - url: https://github.com/admo1 -- login: pbasista + avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 + url: https://github.com/Jackiexiao +- login: aanchlia count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1535892?u=e9a8bd5b3b2f95340cfeb4bc97886e9334911669&v=4 - url: https://github.com/pbasista -- login: bogdan-coman-uv + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: moreno-p count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 - url: https://github.com/bogdan-coman-uv -- login: leonidktoto + avatarUrl: https://avatars.githubusercontent.com/u/164261630?v=4 + url: https://github.com/moreno-p +- login: 0sahil count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 - url: https://github.com/leonidktoto -- login: DJoepie + avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 + url: https://github.com/0sahil +- login: patrick91 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/78362619?u=fe6e8d05f94d8d4c0679a4da943955a686f96177&v=4 - url: https://github.com/DJoepie -- login: alex-pobeditel-2004 + avatarUrl: https://avatars.githubusercontent.com/u/667029?u=e35958a75ac1f99c81b4bc99e22db8cd665ae7f0&v=4 + url: https://github.com/patrick91 +- login: pprunty count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 - url: https://github.com/alex-pobeditel-2004 -- login: binbjz + avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 + url: https://github.com/pprunty +- login: angely-dev count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz -- login: JonnyBootsNpants + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev +- login: mastizada count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 - url: https://github.com/JonnyBootsNpants -- login: TarasKuzyo + avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 + url: https://github.com/mastizada +- login: sm-Fifteen count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/7178184?v=4 - url: https://github.com/TarasKuzyo -- login: kiraware + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen +- login: methane count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/117554978?v=4 - url: https://github.com/kiraware -- login: iudeen + avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 + url: https://github.com/methane +- login: konstantinos1981 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen -- login: msehnout + avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4 + url: https://github.com/konstantinos1981 +- login: druidance count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 - url: https://github.com/msehnout -- login: rafalkrupinski + avatarUrl: https://avatars.githubusercontent.com/u/160344534?v=4 + url: https://github.com/druidance +- login: fabianfalon count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3732079?u=929e95d40d524301cb481da05208a25ed059400d&v=4 - url: https://github.com/rafalkrupinski -- login: morian + avatarUrl: https://avatars.githubusercontent.com/u/3700760?u=95f69e31280b17ac22299cdcd345323b142fe0af&v=4 + url: https://github.com/fabianfalon +- login: VatsalJagani count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1735308?u=8ef15491399b040bd95e2675bb8c8f2462e977b0&v=4 - url: https://github.com/morian -- login: garg10may + avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 + url: https://github.com/VatsalJagani +- login: khaledadrani count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 - url: https://github.com/garg10may -- login: taegyunum + avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 + url: https://github.com/khaledadrani +- login: ThirVondukr count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/16094650?v=4 - url: https://github.com/taegyunum + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr six_months_experts: +- login: YuriiMotov + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: Kludex - count: 112 + count: 104 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: jgould22 - count: 66 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 - login: JavierSanchezCastro - count: 32 + count: 40 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro -- login: YuriiMotov - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov -- login: n8sty - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty +- login: jgould22 + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: hasansezertasan - count: 19 + count: 21 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -- login: WilliamStam +- login: n8sty + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: killjoy1221 count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 - url: https://github.com/WilliamStam -- login: iudeen + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 +- login: aanchlia + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: estebanx64 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: PhysicallyActive count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive - login: dolfinus count: 6 avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 url: https://github.com/dolfinus -- login: aanchlia - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia - login: Ventura94 count: 6 avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 url: https://github.com/Ventura94 -- login: nymous - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous -- login: White-Mask - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 - url: https://github.com/White-Mask -- login: chrisK824 +- login: sehraramiz count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: alex-pobeditel-2004 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + url: https://github.com/sehraramiz +- login: acidjunk count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 - url: https://github.com/alex-pobeditel-2004 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk - login: shashstormer count: 5 avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 @@ -488,215 +448,223 @@ six_months_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 url: https://github.com/GodMoonGoodman -- login: JoshYuJump - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump - login: flo-at count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 url: https://github.com/flo-at -- login: ebottos94 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 -- login: estebanx64 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 -- login: pythonweb2 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: ahmedabdou14 +- login: PREPONDERANCE count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: chrisK824 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: angely-dev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev - login: fmelihh count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=671117dba9022db2237e3da7a39cbc2efc838db0&v=4 url: https://github.com/fmelihh -- login: binbjz +- login: ryanisn count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz -- login: theobouwman - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 - url: https://github.com/theobouwman -- login: Ryandaydev + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn +- login: JoshYuJump count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 - url: https://github.com/Ryandaydev -- login: sriram-kondakindi + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump +- login: pythonweb2 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/32274323?v=4 - url: https://github.com/sriram-kondakindi -- login: NeilBotelho + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: omarcruzpantoja count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/39030675?u=16fea2ff90a5c67b974744528a38832a6d1bb4f7&v=4 - url: https://github.com/NeilBotelho -- login: yinziyan1206 + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja +- login: bogdan-coman-uv count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: pcorvoh + avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 + url: https://github.com/bogdan-coman-uv +- login: ahmedabdou14 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/48502122?u=89fe3e55f3cfd15d34ffac239b32af358cca6481&v=4 - url: https://github.com/pcorvoh -- login: acidjunk + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: mskrip count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk -- login: shashiwtt + avatarUrl: https://avatars.githubusercontent.com/u/17459600?u=10019d5c38ae3374dd4a6743b0223e56a78d4855&v=4 + url: https://github.com/mskrip +- login: leonidktoto count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/87797476?v=4 - url: https://github.com/shashiwtt -- login: yavuzakyazici + avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 + url: https://github.com/leonidktoto +- login: pedroconceicao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/148442912?u=1d2d150172c53daf82020b950c6483a6c6a77b7e&v=4 - url: https://github.com/yavuzakyazici -- login: AntonioBarral + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao +- login: hwong557 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/22151181?u=64416447a37a420e6dfd16e675cf74f66c9f204d&v=4 - url: https://github.com/AntonioBarral -- login: agn-7 + avatarUrl: https://avatars.githubusercontent.com/u/460259?u=7d2f1b33ea5bda4d8e177ab3cb924a673d53087e&v=4 + url: https://github.com/hwong557 +- login: Jackiexiao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14202344?u=a1d05998ceaf4d06d1063575a7c4ef6e7ae5890e&v=4 - url: https://github.com/agn-7 -- login: ThirVondukr + avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 + url: https://github.com/Jackiexiao +- login: admo1 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: richin13 + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 +- login: binbjz count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 - url: https://github.com/richin13 -- login: hussein-awala + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz +- login: nameer count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 - url: https://github.com/hussein-awala -- login: jcphlux + avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 + url: https://github.com/nameer +- login: moreno-p count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/996689?v=4 - url: https://github.com/jcphlux -- login: Matthieu-LAURENT39 + avatarUrl: https://avatars.githubusercontent.com/u/164261630?v=4 + url: https://github.com/moreno-p +- login: 0sahil count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/91389613?v=4 - url: https://github.com/Matthieu-LAURENT39 -- login: bhumkong + avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 + url: https://github.com/0sahil +- login: nymous count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 - url: https://github.com/bhumkong -- login: falkben + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: patrick91 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 - url: https://github.com/falkben -- login: mielvds + avatarUrl: https://avatars.githubusercontent.com/u/667029?u=e35958a75ac1f99c81b4bc99e22db8cd665ae7f0&v=4 + url: https://github.com/patrick91 +- login: pprunty count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 - url: https://github.com/mielvds -- login: admo1 + avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 + url: https://github.com/pprunty +- login: JonnyBootsNpants count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 - url: https://github.com/admo1 -- login: pbasista + avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 + url: https://github.com/JonnyBootsNpants +- login: richin13 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1535892?u=e9a8bd5b3b2f95340cfeb4bc97886e9334911669&v=4 - url: https://github.com/pbasista -- login: osangu + avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 + url: https://github.com/richin13 +- login: mastizada count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/80697064?u=de9bae685e2228bffd4e202274e1df1afaf54a0d&v=4 - url: https://github.com/osangu -- login: bogdan-coman-uv + avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 + url: https://github.com/mastizada +- login: sm-Fifteen count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 - url: https://github.com/bogdan-coman-uv -- login: leonidktoto + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen +- login: amacfie count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 - url: https://github.com/leonidktoto + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie +- login: garg10may + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 + url: https://github.com/garg10may +- login: methane + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 + url: https://github.com/methane +- login: konstantinos1981 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4 + url: https://github.com/konstantinos1981 +- login: druidance + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/160344534?v=4 + url: https://github.com/druidance one_year_experts: - login: Kludex - count: 231 + count: 207 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: jgould22 - count: 132 + count: 118 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 +- login: YuriiMotov + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: JavierSanchezCastro - count: 52 + count: 59 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro - login: n8sty - count: 39 + count: 40 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty -- login: YuriiMotov - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov -- login: chrisK824 - count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 - login: hasansezertasan - count: 19 + count: 27 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -- login: abhint - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 - url: https://github.com/abhint +- login: chrisK824 + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 - login: ahmedabdou14 count: 13 avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 url: https://github.com/ahmedabdou14 -- login: nymous - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous -- login: iudeen - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen - login: arjwilliams count: 12 avatarUrl: https://avatars.githubusercontent.com/u/22227620?v=4 url: https://github.com/arjwilliams -- login: ebottos94 - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 -- login: Viicos +- login: killjoy1221 count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/65306057?u=fcd677dc1b9bef12aa103613e5ccb3f8ce305af9&v=4 - url: https://github.com/Viicos + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 - login: WilliamStam count: 10 avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 url: https://github.com/WilliamStam -- login: yinziyan1206 +- login: iudeen count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: mateoradman - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/48420316?u=066f36b8e8e263b0d90798113b0f291d3266db7c&v=4 - url: https://github.com/mateoradman -- login: dolfinus - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 - url: https://github.com/dolfinus + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +- login: nymous + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous - login: aanchlia - count: 6 + count: 8 avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 url: https://github.com/aanchlia +- login: estebanx64 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: pythonweb2 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 - login: romabozhanovgithub count: 6 avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 url: https://github.com/romabozhanovgithub +- login: PhysicallyActive + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: mikeedjones + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4 + url: https://github.com/mikeedjones +- login: dolfinus + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 + url: https://github.com/dolfinus +- login: ebottos94 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 - login: Ventura94 count: 6 avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 @@ -705,18 +673,18 @@ one_year_experts: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 url: https://github.com/White-Mask -- login: mikeedjones - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4 - url: https://github.com/mikeedjones -- login: ThirVondukr +- login: sehraramiz count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: dmontagu + avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + url: https://github.com/sehraramiz +- login: acidjunk count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 - url: https://github.com/dmontagu + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: JoshYuJump + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump - login: alex-pobeditel-2004 count: 5 avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 @@ -725,101 +693,97 @@ one_year_experts: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 url: https://github.com/shashstormer -- login: nzig - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/7372858?u=e769add36ed73c778cdb136eb10bf96b1e119671&v=4 - url: https://github.com/nzig - login: wu-clan count: 5 avatarUrl: https://avatars.githubusercontent.com/u/52145145?u=f8c9e5c8c259d248e1683fedf5027b4ee08a0967&v=4 url: https://github.com/wu-clan -- login: adriangb - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 - url: https://github.com/adriangb -- login: 8thgencore +- login: abhint count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/30128845?u=a747e840f751a1d196d70d0ecf6d07a530d412a1&v=4 - url: https://github.com/8thgencore -- login: acidjunk + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint +- login: anthonycepeda count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk + avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 + url: https://github.com/anthonycepeda - login: GodMoonGoodman count: 4 avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 url: https://github.com/GodMoonGoodman -- login: JoshYuJump - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump - login: flo-at count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 url: https://github.com/flo-at +- login: yinziyan1206 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 +- login: amacfie + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie - login: commonism count: 4 avatarUrl: https://avatars.githubusercontent.com/u/164513?v=4 url: https://github.com/commonism -- login: estebanx64 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 -- login: djimontyp +- login: dmontagu count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/53098395?u=583bade70950b277c322d35f1be2b75c7b0f189c&v=4 - url: https://github.com/djimontyp + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 + url: https://github.com/dmontagu - login: sanzoghenzo count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/977953?u=d94445b7b87b7096a92a2d4b652ca6c560f34039&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/977953?v=4 url: https://github.com/sanzoghenzo -- login: hochstibe - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/48712216?u=1862e0265e06be7ff710f7dc12094250c0616313&v=4 - url: https://github.com/hochstibe -- login: pythonweb2 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 +- login: lucasgadams + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/36425095?v=4 + url: https://github.com/lucasgadams +- login: NeilBotelho + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/39030675?u=16fea2ff90a5c67b974744528a38832a6d1bb4f7&v=4 + url: https://github.com/NeilBotelho +- login: hhartzer + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/100533792?v=4 + url: https://github.com/hhartzer +- login: binbjz + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz +- login: PREPONDERANCE + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE - login: nameer - count: 4 + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 url: https://github.com/nameer -- login: anthonycepeda - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 - url: https://github.com/anthonycepeda -- login: 9en9i - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/44907258?u=297d0f31ea99c22b718118c1deec82001690cadb&v=4 - url: https://github.com/9en9i -- login: AlexanderPodorov - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/54511144?v=4 - url: https://github.com/AlexanderPodorov -- login: sharonyogev - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/31185192?u=b13ea64b3cdaf3903390c555793aba4aff45c5e6&v=4 - url: https://github.com/sharonyogev +- login: angely-dev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev - login: fmelihh count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=671117dba9022db2237e3da7a39cbc2efc838db0&v=4 url: https://github.com/fmelihh -- login: jinluyang +- login: ryanisn + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn +- login: theobouwman count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15670327?v=4 - url: https://github.com/jinluyang -- login: mht2953658596 + avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 + url: https://github.com/theobouwman +- login: methane count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/59814105?v=4 - url: https://github.com/mht2953658596 + avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 + url: https://github.com/methane top_contributors: - login: nilslindemann - count: 30 + count: 130 avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 url: https://github.com/nilslindemann - login: jaystone776 - count: 27 + count: 49 avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 url: https://github.com/jaystone776 - login: waynerv @@ -827,17 +791,21 @@ top_contributors: avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 url: https://github.com/waynerv - login: tokusumi - count: 23 + count: 24 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi +- login: SwftAlpc + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 + url: https://github.com/SwftAlpc - login: Kludex count: 22 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: SwftAlpc - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 - url: https://github.com/SwftAlpc +- login: hasansezertasan + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: dmontagu count: 17 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 @@ -854,25 +822,25 @@ top_contributors: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 url: https://github.com/mariacamilagl -- login: hasansezertasan +- login: AlertRED count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED - login: Smlep count: 11 avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 url: https://github.com/Smlep -- login: AlertRED +- login: alejsdev count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 - url: https://github.com/AlertRED + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=9ca449ad5161af12766ddd1a22988e9b14315f5c&v=4 + url: https://github.com/alejsdev - login: hard-coders count: 10 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders - login: KaniKim count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=d8ff6fca8542d22f94388cd2c4292e76e3898584&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=40f8f7f3f36d5f2365ba2ad0b40693e60958ce70&v=4 url: https://github.com/KaniKim - login: xzmeng count: 9 @@ -906,10 +874,6 @@ top_contributors: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 url: https://github.com/batlopes -- login: alejsdev - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 - url: https://github.com/alejsdev - login: wshayes count: 5 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 @@ -924,7 +888,7 @@ top_contributors: url: https://github.com/Attsun1031 - login: ComicShrimp count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 url: https://github.com/ComicShrimp - login: rostik1410 count: 5 @@ -944,7 +908,7 @@ top_contributors: url: https://github.com/jfunez - login: ycd count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: komtaki count: 4 @@ -1000,7 +964,7 @@ top_contributors: url: https://github.com/pawamoy top_reviewers: - login: Kludex - count: 155 + count: 158 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: BilalAlpaslan @@ -1008,7 +972,7 @@ top_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 url: https://github.com/BilalAlpaslan - login: yezz123 - count: 84 + count: 85 avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 url: https://github.com/yezz123 - login: iudeen @@ -1023,6 +987,10 @@ top_reviewers: count: 50 avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 url: https://github.com/Xewus +- login: hasansezertasan + count: 50 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: waynerv count: 47 avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 @@ -1033,19 +1001,15 @@ top_reviewers: url: https://github.com/Laineyzhang55 - login: ycd count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: cikay count: 41 avatarUrl: https://avatars.githubusercontent.com/u/24587499?u=e772190a051ab0eaa9c8542fcff1892471638f2b&v=4 url: https://github.com/cikay -- login: hasansezertasan - count: 41 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan - login: alejsdev - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 + count: 38 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=9ca449ad5161af12766ddd1a22988e9b14315f5c&v=4 url: https://github.com/alejsdev - login: JarroVGIT count: 34 @@ -1071,6 +1035,10 @@ top_reviewers: count: 27 avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki +- login: YuriiMotov + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: Ryandaydev count: 25 avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 @@ -1091,10 +1059,6 @@ top_reviewers: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders -- login: YuriiMotov - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov - login: rjNemo count: 21 avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 @@ -1107,6 +1071,10 @@ top_reviewers: count: 19 avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 url: https://github.com/0417taehyun +- login: JavierSanchezCastro + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: Smlep count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 @@ -1115,6 +1083,10 @@ top_reviewers: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 url: https://github.com/zy7y +- login: junah201 + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 + url: https://github.com/junah201 - login: peidrao count: 17 avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 @@ -1131,6 +1103,10 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 url: https://github.com/axel584 +- login: codespearhead + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/72931357?u=0fce6b82219b604d58adb614a761556425579cb5&v=4 + url: https://github.com/codespearhead - login: Alexandrhub count: 16 avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 @@ -1139,6 +1115,14 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 url: https://github.com/DevDae +- login: Aruelius + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 + url: https://github.com/Aruelius +- login: OzgunCaglarArslan + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4 + url: https://github.com/OzgunCaglarArslan - login: pedabraham count: 15 avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 @@ -1147,26 +1131,18 @@ top_reviewers: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 url: https://github.com/delhi09 -- login: Aruelius +- login: wdh99 count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 - url: https://github.com/Aruelius + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 - login: sh0nk count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 url: https://github.com/sh0nk -- login: wdh99 - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 - login: r0b2g1t count: 13 avatarUrl: https://avatars.githubusercontent.com/u/5357541?u=6428442d875d5d71aaa1bb38bb11c4be1a526bc2&v=4 url: https://github.com/r0b2g1t -- login: JavierSanchezCastro - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: RunningIkkyu count: 12 avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 @@ -1183,33 +1159,21 @@ top_reviewers: count: 11 avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 url: https://github.com/solomein-sv -- login: dpinezich - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 - url: https://github.com/dpinezich -- login: mariacamilagl - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 - url: https://github.com/mariacamilagl -- login: raphaelauv - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 - url: https://github.com/raphaelauv top_translations_reviewers: +- login: s111d + count: 146 + avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 + url: https://github.com/s111d - login: Xewus count: 128 avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 url: https://github.com/Xewus -- login: s111d - count: 122 - avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 - url: https://github.com/s111d - login: tokusumi count: 104 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi - login: hasansezertasan - count: 84 + count: 91 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan - login: AlertRED @@ -1240,6 +1204,10 @@ top_translations_reviewers: count: 45 avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki +- login: alperiox + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 + url: https://github.com/alperiox - login: Winand count: 40 avatarUrl: https://avatars.githubusercontent.com/u/53390?u=bb0e71a2fc3910a8e0ee66da67c33de40ea695f8&v=4 @@ -1248,10 +1216,6 @@ top_translations_reviewers: count: 38 avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 url: https://github.com/solomein-sv -- login: alperiox - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=0688c1dc00988150a82d299106062c062ed1ba13&v=4 - url: https://github.com/alperiox - login: lsglucas count: 36 avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 @@ -1276,6 +1240,10 @@ top_translations_reviewers: count: 32 avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 url: https://github.com/romashevchenko +- login: wdh99 + count: 31 + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 - login: LorhanSohaky count: 30 avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 @@ -1284,10 +1252,6 @@ top_translations_reviewers: count: 29 avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 url: https://github.com/cassiobotaro -- login: wdh99 - count: 29 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 - login: pedabraham count: 28 avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 @@ -1300,6 +1264,10 @@ top_translations_reviewers: count: 28 avatarUrl: https://avatars.githubusercontent.com/u/26196675?u=e2966887124e67932853df4f10f86cb526edc7b0&v=4 url: https://github.com/dedkot01 +- login: hsuanchi + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=0b094ae292292fee093818e37ceb645c114d2bff&v=4 + url: https://github.com/hsuanchi - login: dpinezich count: 28 avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 @@ -1336,13 +1304,17 @@ top_translations_reviewers: count: 21 avatarUrl: https://avatars.githubusercontent.com/u/86262613?u=3c21606ab8d210a061a1673decff1e7d5592b380&v=4 url: https://github.com/AGolicyn +- login: OzgunCaglarArslan + count: 21 + avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4 + url: https://github.com/OzgunCaglarArslan - login: Attsun1031 count: 20 avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 url: https://github.com/Attsun1031 - login: ycd count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: delhi09 count: 20 @@ -1362,8 +1334,12 @@ top_translations_reviewers: url: https://github.com/sattosan - login: ComicShrimp count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 url: https://github.com/ComicShrimp +- login: junah201 + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 + url: https://github.com/junah201 - login: simatheone count: 18 avatarUrl: https://avatars.githubusercontent.com/u/78508673?u=1b9658d9ee0bde33f56130dd52275493ddd38690&v=4 @@ -1372,23 +1348,11 @@ top_translations_reviewers: count: 18 avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 url: https://github.com/ivan-abc +- login: JavierSanchezCastro + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: bezaca count: 17 avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 url: https://github.com/bezaca -- login: lbmendes - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/80999926?u=646619e2f07ac5a7c3f65fe7834197461a4fff9f&v=4 - url: https://github.com/lbmendes -- login: rostik1410 - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 - url: https://github.com/rostik1410 -- login: spacesphere - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/34628304?u=cde91f6002dd33156e1bf8005f11a7a3ed76b790&v=4 - url: https://github.com/spacesphere -- login: panko - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/1569515?u=a84a5d255621ed82f8e1ca052f5f2eeb75997da2&v=4 - url: https://github.com/panko diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 85ac30d6d..1c83579e2 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -11,32 +11,35 @@ gold: - url: https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor title: Automate FastAPI documentation generation with Bump.sh img: https://fastapi.tiangolo.com/img/sponsors/bump-sh.svg - - url: https://reflex.dev - title: Reflex - img: https://fastapi.tiangolo.com/img/sponsors/reflex.png - url: https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge title: "Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files" img: https://fastapi.tiangolo.com/img/sponsors/scalar.svg - url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge title: Auth, user management and more for your B2B product img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png - - url: https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=banner%20january%2024 + - url: https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=website title: Coherence img: https://fastapi.tiangolo.com/img/sponsors/coherence.png - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral title: Simplify Full Stack Development with FastAPI & MongoDB img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png + - url: https://zuplo.link/fastapi-gh + title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI' + img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png + - url: https://liblab.com?utm_source=fastapi + title: liblab - Generate SDKs from FastAPI + img: https://fastapi.tiangolo.com/img/sponsors/liblab.png + - url: https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi + title: Deploy & scale any full-stack web app on Render. Focus on building apps, not infra. + img: https://fastapi.tiangolo.com/img/sponsors/render.svg silver: - - url: https://training.talkpython.fm/fastapi-courses - title: FastAPI video courses on demand from people you trust - img: https://fastapi.tiangolo.com/img/sponsors/talkpython-v2.jpg - url: https://github.com/deepset-ai/haystack/ title: Build powerful search from composable, open source building blocks img: https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg - url: https://databento.com/ title: Pay as you go for market data img: https://fastapi.tiangolo.com/img/sponsors/databento.svg - - url: https://speakeasyapi.dev?utm_source=fastapi+repo&utm_medium=github+sponsorship + - url: https://speakeasy.com?utm_source=fastapi+repo&utm_medium=github+sponsorship title: SDKs for your API | Speakeasy img: https://fastapi.tiangolo.com/img/sponsors/speakeasy.png - url: https://www.svix.com/ @@ -45,6 +48,9 @@ silver: - url: https://www.codacy.com/?utm_source=github&utm_medium=sponsors&utm_id=pioneers title: Take code reviews from hours to minutes img: https://fastapi.tiangolo.com/img/sponsors/codacy.png + - url: https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral + title: Stainless | Generate best-in-class SDKs + img: https://fastapi.tiangolo.com/img/sponsors/stainless.png bronze: - url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source title: Biosecurity risk assessments made easy. diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index 00cbec7d2..7470b0238 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -28,3 +28,7 @@ logins: - bump-sh - andrew-propelauth - svix + - zuplo-oss + - Kong + - speakeasy-api + - jess-render diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 41b39c18e..03d48c2a7 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Additional Responses in OpenAPI -!!! warning - This is a rather advanced topic. +/// warning - If you are starting with **FastAPI**, you might not need this. +This is a rather advanced topic. + +If you are starting with **FastAPI**, you might not need this. + +/// You can declare additional responses, with additional status codes, media types, descriptions, etc. @@ -15,7 +18,7 @@ But for those additional responses you have to make sure you return a `Response` You can pass to your *path operation decorators* a parameter `responses`. -It receives a `dict`, the keys are status codes for each response, like `200`, and the values are other `dict`s with the information for each of them. +It receives a `dict`: the keys are status codes for each response (like `200`), and the values are other `dict`s with the information for each of them. Each of those response `dict`s can have a key `model`, containing a Pydantic model, just like `response_model`. @@ -23,24 +26,28 @@ Each of those response `dict`s can have a key `model`, containing a Pydantic mod For example, to declare another response with a status code `404` and a Pydantic model `Message`, you can write: -```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note + +Keep in mind that you have to return the `JSONResponse` directly. + +/// + +/// info -!!! note - Keep in mind that you have to return the `JSONResponse` directly. +The `model` key is not part of OpenAPI. -!!! info - The `model` key is not part of OpenAPI. +**FastAPI** will take the Pydantic model from there, generate the JSON Schema, and put it in the correct place. - **FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place. +The correct place is: - The correct place is: +* In the key `content`, that has as value another JSON object (`dict`) that contains: + * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains: + * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place. + * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc. - * In the key `content`, that has as value another JSON object (`dict`) that contains: - * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains: - * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place. - * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc. +/// The generated responses in the OpenAPI for this *path operation* will be: @@ -168,17 +175,21 @@ You can use this same `responses` parameter to add different media types for the For example, you can add an additional media type of `image/png`, declaring that your *path operation* can return a JSON object (with media type `application/json`) or a PNG image: -```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note + +Notice that you have to return the image using a `FileResponse` directly. + +/// -!!! note - Notice that you have to return the image using a `FileResponse` directly. +/// info -!!! info - Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`). +Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`). - But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model. +But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model. + +/// ## Combining information @@ -192,9 +203,7 @@ For example, you can declare a response with a status code `404` that uses a Pyd And a response with a status code `200` that uses your `response_model`, but includes a custom `example`: -```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} It will all be combined and included in your OpenAPI, and shown in the API docs: @@ -224,17 +233,15 @@ Here, `new_dict` will contain all the key-value pairs from `old_dict` plus the n } ``` -You can use that technique to re-use some predefined responses in your *path operations* and combine them with additional custom ones. +You can use that technique to reuse some predefined responses in your *path operations* and combine them with additional custom ones. For example: -```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## More information about OpenAPI responses To see what exactly you can include in the responses, you can check these sections in the OpenAPI specification: -* OpenAPI Responses Object, it includes the `Response Object`. -* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`. +* OpenAPI Responses Object, it includes the `Response Object`. +* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`. diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md index 0ce275343..077a00488 100644 --- a/docs/en/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -14,53 +14,25 @@ But you also want it to accept new items. And when the items didn't exist before To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want: -=== "Python 3.10+" +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} - ``` +/// warning -=== "Python 3.9+" +When you return a `Response` directly, like in the example above, it will be returned directly. - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} - ``` +It won't be serialized with a model, etc. -=== "Python 3.8+" +Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`). - ```Python hl_lines="4 26" - {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +/// note | Technical Details - !!! tip - Prefer to use the `Annotated` version if possible. +You could also use `from starlette.responses import JSONResponse`. - ```Python hl_lines="2 23" - {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} - ``` +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`. -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001.py!} - ``` - -!!! warning - When you return a `Response` directly, like in the example above, it will be returned directly. - - It won't be serialized with a model, etc. - - Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`). - -!!! note "Technical Details" - You could also use `from starlette.responses import JSONResponse`. - - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`. +/// ## OpenAPI and API docs diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md index 0cffab56d..f933fd264 100644 --- a/docs/en/docs/advanced/advanced-dependencies.md +++ b/docs/en/docs/advanced/advanced-dependencies.md @@ -18,26 +18,7 @@ Not the class itself (which is already a callable), but an instance of that clas To do that, we declare a method `__call__`: -=== "Python 3.9+" - - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later. @@ -45,26 +26,7 @@ In this case, this `__call__` is what **FastAPI** will use to check for addition And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency: -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code. @@ -72,26 +34,7 @@ In this case, **FastAPI** won't ever touch or care about `__init__`, we will use We could create an instance of this class with: -=== "Python 3.9+" - - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`. @@ -107,32 +50,16 @@ checker(q="somequery") ...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`: -=== "Python 3.9+" - - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="21" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +All this might seem contrived. And it might not be very clear how is it useful yet. -!!! tip - All this might seem contrived. And it might not be very clear how is it useful yet. +These examples are intentionally simple, but show how it all works. - These examples are intentionally simple, but show how it all works. +In the chapters about security, there are utility functions that are implemented in this same way. - In the chapters about security, there are utility functions that are implemented in this same way. +If you understood all this, you already know how those utility tools for security work underneath. - If you understood all this, you already know how those utility tools for security work underneath. +/// diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index f9c82e6ab..8d6929222 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ For a simple example, let's consider a file structure similar to the one describ The file `main.py` would have: -```Python -{!../../../docs_src/async_tests/main.py!} -``` +{* ../../docs_src/async_tests/main.py *} The file `test_main.py` would have the tests for `main.py`, it could look like this now: -```Python -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py *} ## Run it @@ -60,18 +56,17 @@ $ pytest The marker `@pytest.mark.anyio` tells pytest that this test function should be called asynchronously: -```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip + +Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`. -!!! tip - Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`. +/// Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`. -```Python hl_lines="9-10" -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} This is the equivalent to: @@ -81,15 +76,24 @@ response = client.get('/') ...that we used to make our requests with the `TestClient`. -!!! tip - Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. +/// tip + +Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. + +/// + +/// warning -!!! warning - If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan. +If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan. + +/// ## Other Asynchronous Function Calls As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code. -!!! tip - If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback. +/// tip + +If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient), remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback. + +/// diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 4da2ddefc..1f0d0fd9f 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -18,11 +18,9 @@ In this case, the original path `/app` would actually be served at `/api/v1/app` Even though all your code is written assuming there's just `/app`. -```Python hl_lines="6" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *} -And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to Uvicorn, keeping your application convinced that it is being served at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`. +And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to the app server (probably Uvicorn via FastAPI CLI), keeping your application convinced that it is being served at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`. Up to here, everything would work as normally. @@ -43,8 +41,11 @@ browser --> proxy proxy --> server ``` -!!! tip - The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server. +/// tip + +The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server. + +/// The docs UI would also need the OpenAPI schema to declare that this API `server` is located at `/api/v1` (behind the proxy). For example: @@ -63,7 +64,7 @@ The docs UI would also need the OpenAPI schema to declare that this API `server` } ``` -In this example, the "Proxy" could be something like **Traefik**. And the server would be something like **Uvicorn**, running your FastAPI application. +In this example, the "Proxy" could be something like **Traefik**. And the server would be something like FastAPI CLI with **Uvicorn**, running your FastAPI application. ### Providing the `root_path` @@ -72,7 +73,7 @@ To achieve this, you can use the command line option `--root-path` like:
```console -$ uvicorn main:app --root-path /api/v1 +$ fastapi run main.py --root-path /api/v1 INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -81,10 +82,13 @@ $ uvicorn main:app --root-path /api/v1 If you use Hypercorn, it also has the option `--root-path`. -!!! note "Technical Details" - The ASGI specification defines a `root_path` for this use case. +/// note | Technical Details + +The ASGI specification defines a `root_path` for this use case. + +And the `--root-path` command line option provides that `root_path`. - And the `--root-path` command line option provides that `root_path`. +/// ### Checking the current `root_path` @@ -92,16 +96,14 @@ You can get the current `root_path` used by your application for each request, i Here we are including it in the message just for demonstration purposes. -```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} Then, if you start Uvicorn with:
```console -$ uvicorn main:app --root-path /api/v1 +$ fastapi run main.py --root-path /api/v1 INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -121,9 +123,7 @@ The response would be something like: Alternatively, if you don't have a way to provide a command line option like `--root-path` or equivalent, you can set the `root_path` parameter when creating your FastAPI app: -```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn. @@ -172,8 +172,11 @@ Then create a file `traefik.toml` with: This tells Traefik to listen on port 9999 and to use another file `routes.toml`. -!!! tip - We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges. +/// tip + +We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges. + +/// Now create that other file `routes.toml`: @@ -202,7 +205,7 @@ Now create that other file `routes.toml`: This file configures Traefik to use the path prefix `/api/v1`. -And then it will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`. +And then Traefik will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`. Now start Traefik: @@ -216,12 +219,12 @@ INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml
-And now start your app with Uvicorn, using the `--root-path` option: +And now start your app, using the `--root-path` option:
```console -$ uvicorn main:app --root-path /api/v1 +$ fastapi run main.py --root-path /api/v1 INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -239,8 +242,11 @@ Now, if you go to the URL with the port for Uvicorn: http://127.0.0.1:9999/api/v1/app. @@ -283,20 +289,21 @@ This is because FastAPI uses this `root_path` to create the default `server` in ## Additional servers -!!! warning - This is a more advanced use case. Feel free to skip it. +/// warning + +This is a more advanced use case. Feel free to skip it. + +/// By default, **FastAPI** will create a `server` in the OpenAPI schema with the URL for the `root_path`. -But you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with a staging and production environments. +But you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with both a staging and a production environment. If you pass a custom list of `servers` and there's a `root_path` (because your API lives behind a proxy), **FastAPI** will insert a "server" with this `root_path` at the beginning of the list. For example: -```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} Will generate an OpenAPI schema like: @@ -323,28 +330,32 @@ Will generate an OpenAPI schema like: } ``` -!!! tip - Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`. +/// tip + +Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`. + +/// In the docs UI at http://127.0.0.1:9999/api/v1/docs it would look like: -!!! tip - The docs UI will interact with the server that you select. +/// tip + +The docs UI will interact with the server that you select. + +/// ### Disable automatic server from `root_path` If you don't want **FastAPI** to include an automatic server using the `root_path`, you can use the parameter `root_path_in_servers=False`: -```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} and then it won't include it in the OpenAPI schema. ## Mounting a sub-application -If you need to mount a sub-application (as described in [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}) while also using a proxy with `root_path`, you can do it normally, as you would expect. +If you need to mount a sub-application (as described in [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}) while also using a proxy with `root_path`, you can do it normally, as you would expect. FastAPI will internally use the `root_path` smartly, so it will just work. ✨ diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 827776f5e..8268dd81a 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -4,16 +4,19 @@ By default, **FastAPI** will return the responses using `JSONResponse`. You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}. -But if you return a `Response` directly, the data won't be automatically converted, and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI). +But if you return a `Response` directly (or any subclass, like `JSONResponse`), the data won't be automatically converted (even if you declare a `response_model`), and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI). -But you can also declare the `Response` that you want to be used, in the *path operation decorator*. +But you can also declare the `Response` that you want to be used (e.g. any `Response` subclass), in the *path operation decorator* using the `response_class` parameter. The contents that you return from your *path operation function* will be put inside of that `Response`. And if that `Response` has a JSON media type (`application/json`), like is the case with the `JSONResponse` and `UJSONResponse`, the data you return will be automatically converted (and filtered) with any Pydantic `response_model` that you declared in the *path operation decorator*. -!!! note - If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs. +/// note + +If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs. + +/// ## Use `ORJSONResponse` @@ -23,23 +26,27 @@ Import the `Response` class (sub-class) you want to use and declare it in the *p For large responses, returning a `Response` directly is much faster than returning a dictionary. -This is because by default, FastAPI will inspect every item inside and make sure it is serializable with JSON, using the same [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} explained in the tutorial. This is what allows you to return **arbitrary objects**, for example database models. +This is because by default, FastAPI will inspect every item inside and make sure it is serializable as JSON, using the same [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} explained in the tutorial. This is what allows you to return **arbitrary objects**, for example database models. But if you are certain that the content that you are returning is **serializable with JSON**, you can pass it directly to the response class and avoid the extra overhead that FastAPI would have by passing your return content through the `jsonable_encoder` before passing it to the response class. -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info + +The parameter `response_class` will also be used to define the "media type" of the response. + +In this case, the HTTP header `Content-Type` will be set to `application/json`. -!!! info - The parameter `response_class` will also be used to define the "media type" of the response. +And it will be documented as such in OpenAPI. - In this case, the HTTP header `Content-Type` will be set to `application/json`. +/// - And it will be documented as such in OpenAPI. +/// tip -!!! tip - The `ORJSONResponse` is currently only available in FastAPI, not in Starlette. +The `ORJSONResponse` is only available in FastAPI, not in Starlette. + +/// ## HTML Response @@ -48,16 +55,17 @@ To return a response with HTML directly from **FastAPI**, use `HTMLResponse`. * Import `HTMLResponse`. * Pass `HTMLResponse` as the parameter `response_class` of your *path operation decorator*. -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info -!!! info - The parameter `response_class` will also be used to define the "media type" of the response. +The parameter `response_class` will also be used to define the "media type" of the response. - In this case, the HTTP header `Content-Type` will be set to `text/html`. +In this case, the HTTP header `Content-Type` will be set to `text/html`. - And it will be documented as such in OpenAPI. +And it will be documented as such in OpenAPI. + +/// ### Return a `Response` @@ -65,15 +73,19 @@ As seen in [Return a Response directly](response-directly.md){.internal-link tar The same example from above, returning an `HTMLResponse`, could look like: -```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} -!!! warning - A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs. +/// warning -!!! info - Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object your returned. +A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs. + +/// + +/// info + +Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned. + +/// ### Document in OpenAPI and override `Response` @@ -85,9 +97,7 @@ The `response_class` will then be used only to document the OpenAPI *path operat For example, it could be something like: -```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} In this example, the function `generate_html_response()` already generates and returns a `Response` instead of returning the HTML in a `str`. @@ -103,10 +113,13 @@ Here are some of the available responses. Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class. -!!! note "Technical Details" - You could also use `from starlette.responses import HTMLResponse`. +/// note | Technical Details + +You could also use `from starlette.responses import HTMLResponse`. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. + +/// ### `Response` @@ -121,11 +134,9 @@ It accepts the following parameters: * `headers` - A `dict` of strings. * `media_type` - A `str` giving the media type. E.g. `"text/html"`. -FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the media_type and appending a charset for text types. +FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the `media_type` and appending a charset for text types. -```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -133,11 +144,9 @@ Takes some text or bytes and returns an HTML response, as you read above. ### `PlainTextResponse` -Takes some text or bytes and returns an plain text response. +Takes some text or bytes and returns a plain text response. -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -149,19 +158,35 @@ This is the default response used in **FastAPI**, as you read above. A fast alternative JSON response using `orjson`, as you read above. +/// info + +This requires installing `orjson` for example with `pip install orjson`. + +/// + ### `UJSONResponse` An alternative JSON response using `ujson`. -!!! warning - `ujson` is less careful than Python's built-in implementation in how it handles some edge-cases. +/// info -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} -``` +This requires installing `ujson` for example with `pip install ujson`. + +/// + +/// warning + +`ujson` is less careful than Python's built-in implementation in how it handles some edge-cases. + +/// -!!! tip - It's possible that `ORJSONResponse` might be a faster alternative. +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} + +/// tip + +It's possible that `ORJSONResponse` might be a faster alternative. + +/// ### `RedirectResponse` @@ -169,18 +194,14 @@ Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default You can return a `RedirectResponse` directly: -```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- Or you can use it in the `response_class` parameter: -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} If you do that, then you can return the URL directly from your *path operation* function. @@ -190,17 +211,13 @@ In this case, the `status_code` used will be the default one for the `RedirectRe You can also use the `status_code` parameter combined with the `response_class` parameter: -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` Takes an async generator or a normal generator/iterator and streams the response body. -```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### Using `StreamingResponse` with file-like objects @@ -210,20 +227,21 @@ That way, you don't have to read it all first in memory, and you can pass that g This includes many libraries to interact with cloud storage, video processing, and others. -```{ .python .annotate hl_lines="2 10-12 14" } -{!../../../docs_src/custom_response/tutorial008.py!} -``` +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} 1. This is the generator function. It's a "generator function" because it contains `yield` statements inside. 2. By using a `with` block, we make sure that the file-like object is closed after the generator function is done. So, after it finishes sending the response. -3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function. +3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function (`iterfile`). So, it is a generator function that transfers the "generating" work to something else internally. - By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing. + By doing it this way, we can put it in a `with` block, and that way, ensure that the file-like object is closed after finishing. -!!! tip - Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`. +/// tip + +Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`. + +/// ### `FileResponse` @@ -231,22 +249,18 @@ Asynchronously streams a file as the response. Takes a different set of arguments to instantiate than the other response types: -* `path` - The filepath to the file to stream. +* `path` - The file path to the file to stream. * `headers` - Any custom headers to include, as a dictionary. * `media_type` - A string giving the media type. If unset, the filename or path will be used to infer a media type. * `filename` - If set, this will be included in the response `Content-Disposition`. File responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers. -```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} You can also use the `response_class` parameter: -```Python hl_lines="2 8 10" -{!../../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} In this case, you can return the file path directly from your *path operation* function. @@ -260,9 +274,7 @@ Let's say you want it to return indented and formatted JSON, so you want to use You could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`: -```Python hl_lines="9-14 17" -{!../../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} Now instead of returning: @@ -288,12 +300,13 @@ The parameter that defines this is `default_response_class`. In the example below, **FastAPI** will use `ORJSONResponse` by default, in all *path operations*, instead of `JSONResponse`. -```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip + +You can still override `response_class` in *path operations* as before. -!!! tip - You can still override `response_class` in *path operations* as before. +/// ## Additional documentation diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 481bf5e69..2936c6d5d 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI is built on top of **Pydantic**, and I have been showing you how to use But FastAPI also supports using `dataclasses` the same way: -```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`. @@ -20,20 +18,21 @@ And of course, it supports the same: This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic. -!!! info - Keep in mind that dataclasses can't do everything Pydantic models can do. +/// info - So, you might still need to use Pydantic models. +Keep in mind that dataclasses can't do everything Pydantic models can do. - But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓 +So, you might still need to use Pydantic models. + +But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓 + +/// ## Dataclasses in `response_model` You can also use `dataclasses` in the `response_model` parameter: -```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} The dataclass will be automatically converted to a Pydantic dataclass. @@ -49,9 +48,7 @@ In some cases, you might still have to use Pydantic's version of `dataclasses`. In that case, you can simply swap the standard `dataclasses` with `pydantic.dataclasses`, which is a drop-in replacement: -```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} -``` +{* ../../docs_src/dataclasses/tutorial003.py hl[1,5,8:11,14:17,23:25,28] *} 1. We still import `field` from standard `dataclasses`. @@ -77,7 +74,7 @@ In that case, you can simply swap the standard `dataclasses` with `pydantic.data As always, in FastAPI you can combine `def` and `async def` as needed. - If you need a refresher about when to use which, check out the section _"In a hurry?"_ in the docs about `async` and `await`. + If you need a refresher about when to use which, check out the section _"In a hurry?"_ in the docs about [`async` and `await`](../async.md#in-a-hurry){.internal-link target=_blank}. 9. This *path operation function* is not returning dataclasses (although it could), but a list of dictionaries with internal data. diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index ca9d86ae4..19465d891 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -30,26 +30,25 @@ Let's start with an example and then see it in detail. We create an async function `lifespan()` with `yield` like this: -```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} Here we are simulating the expensive *startup* operation of loading the model by putting the (fake) model function in the dictionary with machine learning models before the `yield`. This code will be executed **before** the application **starts taking requests**, during the *startup*. And then, right after the `yield`, we unload the model. This code will be executed **after** the application **finishes handling requests**, right before the *shutdown*. This could, for example, release resources like memory or a GPU. -!!! tip - The `shutdown` would happen when you are **stopping** the application. +/// tip + +The `shutdown` would happen when you are **stopping** the application. - Maybe you need to start a new version, or you just got tired of running it. 🤷 +Maybe you need to start a new version, or you just got tired of running it. 🤷 + +/// ### Lifespan function The first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`. -```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} The first part of the function, before the `yield`, will be executed **before** the application starts. @@ -61,9 +60,7 @@ If you check, the function is decorated with an `@asynccontextmanager`. That converts the function into something called an "**async context manager**". -```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} A **context manager** in Python is something that you can use in a `with` statement, for example, `open()` can be used as a context manager: @@ -85,16 +82,17 @@ In our code example above, we don't use it directly, but we pass it to FastAPI f The `lifespan` parameter of the `FastAPI` app takes an **async context manager**, so we can pass our new `lifespan` async context manager to it. -```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## Alternative Events (deprecated) -!!! warning - The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. +/// warning + +The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. + +You can probably skip this part. - You can probably skip this part. +/// There's an alternative way to define this logic to be executed during *startup* and during *shutdown*. @@ -106,9 +104,7 @@ These functions can be declared with `async def` or normal `def`. To add a function that should be run before the application starts, declare it with the event `"startup"`: -```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values. @@ -120,23 +116,27 @@ And your application won't start receiving requests until all the `startup` even To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`: -```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`. -!!! info - In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents. +/// info + +In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents. + +/// -!!! tip - Notice that in this case we are using a standard Python `open()` function that interacts with a file. +/// tip - So, it involves I/O (input/output), that requires "waiting" for things to be written to disk. +Notice that in this case we are using a standard Python `open()` function that interacts with a file. - But `open()` doesn't use `async` and `await`. +So, it involves I/O (input/output), that requires "waiting" for things to be written to disk. - So, we declare the event handler function with standard `def` instead of `async def`. +But `open()` doesn't use `async` and `await`. + +So, we declare the event handler function with standard `def` instead of `async def`. + +/// ### `startup` and `shutdown` together @@ -152,11 +152,14 @@ Just a technical detail for the curious nerds. 🤓 Underneath, in the ASGI technical specification, this is part of the Lifespan Protocol, and it defines events called `startup` and `shutdown`. -!!! info - You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs. +/// info + +You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs. + +Including how to handle lifespan state that can be used in other areas of your code. - Including how to handle lifespan state that can be used in other areas of your code. +/// ## Sub Applications -🚨 Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}. +🚨 Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index 3a810baee..fe4194ac7 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -10,7 +10,7 @@ There are many tools to generate clients from **OpenAPI**. A common tool is OpenAPI Generator. -If you are building a **frontend**, a very interesting alternative is openapi-typescript-codegen. +If you are building a **frontend**, a very interesting alternative is openapi-ts. ## Client and SDK Generators - Sponsor @@ -20,7 +20,11 @@ Some of them also ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-autho And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇 -For example, you might want to try Speakeasy. +For example, you might want to try: + +* Speakeasy +* Stainless +* liblab There are also several other companies offering similar services that you can search and find online. 🤓 @@ -28,17 +32,7 @@ There are also several other companies offering similar services that you can se Let's start with a simple FastAPI application: -=== "Python 3.9+" - - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`. @@ -58,14 +52,14 @@ And that same information from the models that is included in OpenAPI is what ca Now that we have the app with the models, we can generate the client code for the frontend. -#### Install `openapi-typescript-codegen` +#### Install `openapi-ts` -You can install `openapi-typescript-codegen` in your frontend code with: +You can install `openapi-ts` in your frontend code with:
```console -$ npm install openapi-typescript-codegen --save-dev +$ npm install @hey-api/openapi-ts --save-dev ---> 100% ``` @@ -74,7 +68,7 @@ $ npm install openapi-typescript-codegen --save-dev #### Generate Client Code -To generate the client code you can use the command line application `openapi` that would now be installed. +To generate the client code you can use the command line application `openapi-ts` that would now be installed. Because it is installed in the local project, you probably wouldn't be able to call that command directly, but you would put it on your `package.json` file. @@ -87,12 +81,12 @@ It could look like this: "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -106,7 +100,7 @@ After having that NPM `generate-client` script there, you can run it with: $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios ```
@@ -123,8 +117,11 @@ You will also get autocompletion for the payload to send: -!!! tip - Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model. +/// tip + +Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model. + +/// You will have inline errors for the data that you send: @@ -140,17 +137,7 @@ In many cases your FastAPI app will be bigger, and you will probably use tags to For example, you could have a section for **items** and another section for **users**, and they could be separated by tags: -=== "Python 3.9+" - - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### Generate a TypeScript Client with Tags @@ -197,17 +184,7 @@ For example, here it is using the first tag (you will probably have only one tag You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter: -=== "Python 3.9+" - - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### Generate a TypeScript Client with Custom Operation IDs @@ -229,17 +206,21 @@ But for the generated client we could **modify** the OpenAPI operation IDs right We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this: -=== "Python" +//// tab | Python - ```Python - {!> ../../../docs_src/generate_clients/tutorial004.py!} - ``` +```Python +{!> ../../docs_src/generate_clients/tutorial004.py!} +``` + +//// -=== "Node.js" +//// tab | Node.js + +```Javascript +{!> ../../docs_src/generate_clients/tutorial004.js!} +``` - ```Python - {!> ../../../docs_src/generate_clients/tutorial004.js!} - ``` +//// With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names. @@ -254,12 +235,12 @@ Now as the end result is in a file `openapi.json`, you would modify the `package "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -271,7 +252,7 @@ After generating the new client, you would now have **clean method names**, with ## Benefits -When using the automatically generated clients you would **autocompletion** for: +When using the automatically generated clients you would get **autocompletion** for: * Methods. * Request payloads in the body, query parameters, etc. diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md index 86e42fba0..36f0720c0 100644 --- a/docs/en/docs/advanced/index.md +++ b/docs/en/docs/advanced/index.md @@ -6,10 +6,13 @@ The main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_bl In the next sections you will see other options, configurations, and additional features. -!!! tip - The next sections are **not necessarily "advanced"**. +/// tip - And it's possible that for your use case, the solution is in one of them. +The next sections are **not necessarily "advanced"**. + +And it's possible that for your use case, the solution is in one of them. + +/// ## Read the Tutorial first diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 9219f1d2c..1d40b1c8f 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -24,7 +24,7 @@ app = SomeASGIApp() new_app = UnicornMiddleware(app, some_config="rainbow") ``` -But FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares to handle server errors and custom exception handlers work properly. +But FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares handle server errors and custom exception handlers work properly. For that, you use `app.add_middleware()` (as in the example for CORS). @@ -43,28 +43,27 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** includes several middlewares for common use cases, we'll see next how to use them. -!!! note "Technical Details" - For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`. +/// note | Technical Details - **FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. +For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. + +/// ## `HTTPSRedirectMiddleware` Enforces that all incoming requests must either be `https` or `wss`. -Any incoming requests to `http` or `ws` will be redirected to the secure scheme instead. +Any incoming request to `http` or `ws` will be redirected to the secure scheme instead. -```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` Enforces that all incoming requests have a correctly set `Host` header, in order to guard against HTTP Host Header attacks. -```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} The following arguments are supported: @@ -78,13 +77,12 @@ Handles GZip responses for any request that includes `"gzip"` in the `Accept-Enc The middleware will handle both standard and streaming responses. -```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} The following arguments are supported: * `minimum_size` - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to `500`. +* `compresslevel` - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to `9`. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes. ## Other middlewares @@ -92,7 +90,6 @@ There are many other ASGI middlewares. For example: -* Sentry * Uvicorn's `ProxyHeadersMiddleware` * MessagePack diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index fb7a6d917..ca9065a89 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -31,12 +31,13 @@ It will have a *path operation* that will receive an `Invoice` body, and a query This part is pretty normal, most of the code is probably already familiar to you: -```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} + +/// tip -!!! tip - The `callback_url` query parameter uses a Pydantic URL type. +The `callback_url` query parameter uses a Pydantic Url type. + +/// The only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. @@ -61,10 +62,13 @@ That documentation will show up in the Swagger UI at `/docs` in your API, and it This example doesn't implement the callback itself (that could be just a line of code), only the documentation part. -!!! tip - The actual callback is just an HTTP request. +/// tip + +The actual callback is just an HTTP request. - When implementing the callback yourself, you could use something like HTTPX or Requests. +When implementing the callback yourself, you could use something like HTTPX or Requests. + +/// ## Write the callback documentation code @@ -74,18 +78,19 @@ But, you already know how to easily create automatic documentation for an API wi So we are going to use that same knowledge to document how the *external API* should look like... by creating the *path operation(s)* that the external API should implement (the ones your API will call). -!!! tip - When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*. +/// tip + +When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*. + +Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*. - Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*. +/// ### Create a callback `APIRouter` First create a new `APIRouter` that will contain one or more callbacks. -```Python hl_lines="3 25" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### Create the callback *path operation* @@ -96,9 +101,7 @@ It should look just like a normal FastAPI *path operation*: * It should probably have a declaration of the body it should receive, e.g. `body: InvoiceEvent`. * And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} There are 2 main differences from a normal *path operation*: @@ -131,7 +134,7 @@ with a JSON body of: } ``` -Then *your API* will process the invoice, and at some point later, send a callback request to the `callback_url` (the *external API*): +then *your API* will process the invoice, and at some point later, send a callback request to the `callback_url` (the *external API*): ``` https://www.external.org/events/invoices/2expen51ve @@ -154,8 +157,11 @@ and it would expect a response from that *external API* with a JSON body like: } ``` -!!! tip - Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`). +/// tip + +Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`). + +/// ### Add the callback router @@ -163,17 +169,18 @@ At this point you have the *callback path operation(s)* needed (the one(s) that Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router: -```Python hl_lines="35" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} + +/// tip + +Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`. -!!! tip - Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`. +/// ### Check the docs -Now you can start your app with Uvicorn and go to http://127.0.0.1:8000/docs. +Now you can start your app and go to http://127.0.0.1:8000/docs. -You will see your docs including a "Callback" section for your *path operation* that shows how the *external API* should look like: +You will see your docs including a "Callbacks" section for your *path operation* that shows how the *external API* should look like: diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md index 63cbdc610..97aaa41af 100644 --- a/docs/en/docs/advanced/openapi-webhooks.md +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -22,21 +22,25 @@ With **FastAPI**, using OpenAPI, you can define the names of these webhooks, the This can make it a lot easier for your users to **implement their APIs** to receive your **webhook** requests, they might even be able to autogenerate some of their own API code. -!!! info - Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above. +/// info + +Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above. + +/// ## An app with webhooks When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`. -```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_webhooks/tutorial001.py!} -``` +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. -!!! info - The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files. +/// info + +The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files. + +/// Notice that with webhooks you are actually not declaring a *path* (like `/items/`), the text you pass there is just an **identifier** of the webhook (the name of the event), for example in `@app.webhooks.post("new-subscription")`, the webhook name is `new-subscription`. @@ -44,7 +48,7 @@ This is because it is expected that **your users** would define the actual **URL ### Check the docs -Now you can start your app with Uvicorn and go to http://127.0.0.1:8000/docs. +Now you can start your app and go to http://127.0.0.1:8000/docs. You will see your docs have the normal *path operations* and now also some **webhooks**: diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index 8b79bfe22..c4814ebd2 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -2,16 +2,17 @@ ## OpenAPI operationId -!!! warning - If you are not an "expert" in OpenAPI, you probably don't need this. +/// warning + +If you are not an "expert" in OpenAPI, you probably don't need this. + +/// You can set the OpenAPI `operationId` to be used in your *path operation* with the parameter `operation_id`. You would have to make sure that it is unique for each operation. -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Using the *path operation function* name as the operationId @@ -19,25 +20,27 @@ If you want to use your APIs' function names as `operationId`s, you can iterate You should do it after adding all your *path operations*. -```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2, 12:21, 24] *} + +/// tip + +If you manually call `app.openapi()`, you should update the `operationId`s before that. + +/// -!!! tip - If you manually call `app.openapi()`, you should update the `operationId`s before that. +/// warning -!!! warning - If you do this, you have to make sure each one of your *path operation functions* has a unique name. +If you do this, you have to make sure each one of your *path operation functions* has a unique name. - Even if they are in different modules (Python files). +Even if they are in different modules (Python files). + +/// ## Exclude from OpenAPI To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`: -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Advanced description from docstring @@ -47,9 +50,7 @@ Adding an `\f` (an escaped "form feed" character) causes **FastAPI** to truncate It won't show up in the documentation, but other tools (such as Sphinx) will be able to use the rest. -```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## Additional Responses @@ -59,14 +60,17 @@ That defines the metadata about the main response of a *path operation*. You can also declare additional responses with their models, status codes, etc. -There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}. +There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. ## OpenAPI Extra When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema. -!!! note "Technical details" - In the OpenAPI specification it is called the Operation Object. +/// note | Technical details + +In the OpenAPI specification it is called the Operation Object. + +/// It has all the information about the *path operation* and is used to generate the automatic documentation. @@ -74,10 +78,13 @@ It includes the `tags`, `parameters`, `requestBody`, `responses`, etc. This *path operation*-specific OpenAPI schema is normally generated automatically by **FastAPI**, but you can also extend it. -!!! tip - This is a low level extension point. +/// tip + +This is a low level extension point. - If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}. +If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`. @@ -85,9 +92,7 @@ You can extend the OpenAPI schema for a *path operation* using the parameter `op This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} If you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*. @@ -134,9 +139,7 @@ For example, you could decide to read and validate the request with your own cod You could do that with `openapi_extra`: -```Python hl_lines="20-37 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36, 39:40] *} In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way. @@ -150,20 +153,23 @@ And you could do this even if the data type in the request is not JSON. For example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON: -=== "Pydantic v2" +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22, 24] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22, 24] *} - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +//// -=== "Pydantic v1" +/// info - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. -!!! info - In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. +/// Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML. @@ -171,22 +177,28 @@ Then we use the request directly, and extract the body as `bytes`. This means th And then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content: -=== "Pydantic v2" +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} + +//// + +/// info - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`. -=== "Pydantic v1" +/// - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +/// tip -!!! info - In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`. +Here we reuse the same Pydantic model. -!!! tip - Here we re-use the same Pydantic model. +But the same way, we could have validated it in some other way. - But the same way, we could have validated it in some other way. +/// diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md index b88d74a8a..6d3f9f3e8 100644 --- a/docs/en/docs/advanced/response-change-status-code.md +++ b/docs/en/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set the `status_code` in that *temporal* response object. -```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index d53985dbb..f6d17f35d 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set cookies in that *temporal* response object. -```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). @@ -26,24 +24,28 @@ To do that, you can create a response as described in [Return a Response Directl Then set Cookies in it, and then return it: -```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} -!!! tip - Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. +/// tip - So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`. +Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. - And also that you are not sending any data that should have been filtered by a `response_model`. +So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`. + +And also that you are not sending any data that should have been filtered by a `response_model`. + +/// ### More info -!!! note "Technical Details" - You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. +/// note | Technical Details + +You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. - And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. +/// To see all the available parameters and options, check the documentation in Starlette. diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 8836140ec..691b1e7cd 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ It might be useful, for example, to return custom headers or cookies. In fact, you can return any `Response` or any sub-class of it. -!!! tip - `JSONResponse` itself is a sub-class of `Response`. +/// tip + +`JSONResponse` itself is a sub-class of `Response`. + +/// And when you return a `Response`, **FastAPI** will pass it directly. @@ -25,20 +28,21 @@ This gives you a lot of flexibility. You can return any data type, override any ## Using the `jsonable_encoder` in a `Response` -Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure it's contents are ready for it. +Because **FastAPI** doesn't make any changes to a `Response` you return, you have to make sure its contents are ready for it. For example, you cannot put a Pydantic model in a `JSONResponse` without first converting it to a `dict` with all the data types (like `datetime`, `UUID`, etc) converted to JSON-compatible types. For those cases, you can use the `jsonable_encoder` to convert your data before passing it to a response: -```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | Technical Details + +You could also use `from starlette.responses import JSONResponse`. -!!! note "Technical Details" - You could also use `from starlette.responses import JSONResponse`. +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +/// ## Returning a custom `Response` @@ -48,11 +52,9 @@ Now, let's see how you could use that to return a custom response. Let's say that you want to return an XML response. -You could put your XML content in a string, put it in a `Response`, and return it: +You could put your XML content in a string, put that in a `Response`, and return it: -```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## Notes diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md index 49b5fe476..97e888983 100644 --- a/docs/en/docs/advanced/response-headers.md +++ b/docs/en/docs/advanced/response-headers.md @@ -6,9 +6,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set headers in that *temporal* response object. -```Python hl_lines="1 7-8" -{!../../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1, 7:8] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). @@ -24,16 +22,17 @@ You can also add headers when you return a `Response` directly. Create a response as described in [Return a Response Directly](response-directly.md){.internal-link target=_blank} and pass the headers as an additional parameter: -```Python hl_lines="10-12" -{!../../../docs_src/response_headers/tutorial001.py!} -``` +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} -!!! note "Technical Details" - You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. +/// note | Technical Details - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. - And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. + +And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. + +/// ## Custom Headers diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md index 680f4dff5..234e2f940 100644 --- a/docs/en/docs/advanced/security/http-basic-auth.md +++ b/docs/en/docs/advanced/security/http-basic-auth.md @@ -20,26 +20,7 @@ Then, when you type that username and password, the browser sends them in the he * It returns an object of type `HTTPBasicCredentials`: * It contains the `username` and `password` sent. -=== "Python 3.9+" - - ```Python hl_lines="4 8 12" - {!> ../../../docs_src/security/tutorial006_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="2 7 11" - {!> ../../../docs_src/security/tutorial006_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="2 6 10" - {!> ../../../docs_src/security/tutorial006.py!} - ``` +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password: @@ -59,26 +40,7 @@ To handle that, we first convert the `username` and `password` to `bytes` encodi Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. -=== "Python 3.9+" - - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="1 11-21" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} This would be similar to: @@ -126,7 +88,7 @@ And then they can try again knowing that it's probably something more similar to #### A "professional" attack -Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And would get just one extra correct letter at a time. +Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And they would get just one extra correct letter at a time. But doing that, in some minutes or hours the attackers would have guessed the correct username and password, with the "help" of our application, just using the time taken to answer. @@ -142,23 +104,4 @@ That way, using `secrets.compare_digest()` in your application code, it will be After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again: -=== "Python 3.9+" - - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="23-27" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/en/docs/advanced/security/index.md b/docs/en/docs/advanced/security/index.md index c9ede4231..edb42132e 100644 --- a/docs/en/docs/advanced/security/index.md +++ b/docs/en/docs/advanced/security/index.md @@ -4,10 +4,13 @@ There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}. -!!! tip - The next sections are **not necessarily "advanced"**. +/// tip - And it's possible that for your use case, the solution is in one of them. +The next sections are **not necessarily "advanced"**. + +And it's possible that for your use case, the solution is in one of them. + +/// ## Read the Tutorial first diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index b93d2991c..4cb0b39bc 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -10,18 +10,21 @@ Every time you "log in with" Facebook, Google, GitHub, Microsoft, Twitter, that In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application. -!!! warning - This is a more or less advanced section. If you are just starting, you can skip it. +/// warning - You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want. +This is a more or less advanced section. If you are just starting, you can skip it. - But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs. +You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want. - Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code. +But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs. - In many cases, OAuth2 with scopes can be an overkill. +Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code. - But if you know you need it, or you are curious, keep reading. +In many cases, OAuth2 with scopes can be an overkill. + +But if you know you need it, or you are curious, keep reading. + +/// ## OAuth2 scopes and OpenAPI @@ -43,63 +46,23 @@ They are normally used to declare specific security permissions, for example: * `instagram_basic` is used by Facebook / Instagram. * `https://www.googleapis.com/auth/drive` is used by Google. -!!! info - In OAuth2 a "scope" is just a string that declares a specific permission required. - - It doesn't matter if it has other characters like `:` or if it is a URL. - - Those details are implementation specific. - - For OAuth2 they are just strings. - -## Global view - -First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes: - -=== "Python 3.10+" - - ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +/// info -=== "Python 3.10+ non-Annotated" +In OAuth2 a "scope" is just a string that declares a specific permission required. - !!! tip - Prefer to use the `Annotated` version if possible. +It doesn't matter if it has other characters like `:` or if it is a URL. - ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +Those details are implementation specific. -=== "Python 3.9+ non-Annotated" +For OAuth2 they are just strings. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" +## Global view - !!! tip - Prefer to use the `Annotated` version if possible. +First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes: - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:125,129:135,140,156] *} Now let's review those changes step by step. @@ -109,51 +72,7 @@ The first change is that now we are declaring the OAuth2 security scheme with tw The `scopes` parameter receives a `dict` with each scope as a key and the description as the value: -=== "Python 3.10+" - - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="61-64" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - - -=== "Python 3.9+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *} Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize. @@ -171,55 +90,15 @@ We are still using the same `OAuth2PasswordRequestForm`. It includes a property And we return the scopes as part of the JWT token. -!!! danger - For simplicity, here we are just adding the scopes received directly to the token. - - But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined. - -=== "Python 3.10+" - - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="154" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - -=== "Python 3.9+ non-Annotated" +/// danger - !!! tip - Prefer to use the `Annotated` version if possible. +For simplicity, here we are just adding the scopes received directly to the token. - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[156] *} ## Declare scopes in *path operations* and dependencies @@ -237,62 +116,25 @@ And the dependency function `get_current_active_user` can also declare sub-depen In this case, it requires the scope `me` (it could require more than one scope). -!!! note - You don't necessarily need to add different scopes in different places. - - We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels. - -=== "Python 3.10+" - - ```Python hl_lines="4 139 170" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="4 139 170" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" +/// note - ```Python hl_lines="4 140 171" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +You don't necessarily need to add different scopes in different places. -=== "Python 3.10+ non-Annotated" +We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="3 138 167" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *} -=== "Python 3.9+ non-Annotated" +/// info | Technical Details - !!! tip - Prefer to use the `Annotated` version if possible. +`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later. - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI. -=== "Python 3.8+ non-Annotated" +But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes. - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005.py!} - ``` - -!!! info "Technical Details" - `Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later. - - But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI. - - But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes. +/// ## Use `SecurityScopes` @@ -300,7 +142,7 @@ Now update the dependency `get_current_user`. This is the one used by the dependencies above. -Here's were we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`. +Here's where we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`. Because this dependency function doesn't have any scope requirements itself, we can use `Depends` with `oauth2_scheme`, we don't have to use `Security` when we don't need to specify security scopes. @@ -308,50 +150,7 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly). -=== "Python 3.10+" - - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8 106" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="7 104" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - -=== "Python 3.9+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *} ## Use the `scopes` @@ -361,54 +160,11 @@ It will have a property `scopes` with a list containing all the scopes required The `security_scopes` object (of class `SecurityScopes`) also provides a `scope_str` attribute with a single string, containing those scopes separated by spaces (we are going to use it). -We create an `HTTPException` that we can re-use (`raise`) later at several points. +We create an `HTTPException` that we can reuse (`raise`) later at several points. In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec). -=== "Python 3.10+" - - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="104 106-114" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - -=== "Python 3.9+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *} ## Verify the `username` and data shape @@ -424,50 +180,7 @@ Instead of, for example, a `dict`, or something else, as it could break the appl We also verify that we have a user with that username, and if not, we raise that same exception we created before. -=== "Python 3.10+" - - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="45 115-126" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - -=== "Python 3.9+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:128] *} ## Verify the `scopes` @@ -475,50 +188,7 @@ We now verify that all the scopes required, by this dependency and all the depen For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`. -=== "Python 3.10+" - - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="127-133" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - -=== "Python 3.9+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[129:135] *} ## Dependency tree and scopes @@ -543,12 +213,15 @@ Here's how the hierarchy of dependencies and scopes looks like: * This `security_scopes` parameter has a property `scopes` with a `list` containing all these scopes declared above, so: * `security_scopes.scopes` will contain `["me", "items"]` for the *path operation* `read_own_items`. * `security_scopes.scopes` will contain `["me"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`. - * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scope` either. + * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scopes` either. + +/// tip -!!! tip - The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*. +The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*. - All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*. +All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*. + +/// ## More details about `SecurityScopes` @@ -584,12 +257,15 @@ But if you are building an OAuth2 application that others would connect to (i.e. The most common is the implicit flow. -The most secure is the code flow, but is more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow. +The most secure is the code flow, but it's more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow. + +/// note + +It's common that each authentication provider names their flows in a different way, to make it part of their brand. -!!! note - It's common that each authentication provider names their flows in a different way, to make it part of their brand. +But in the end, they are implementing the same OAuth2 standard. - But in the end, they are implementing the same OAuth2 standard. +/// **FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`. diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index f6db8d2b1..01810c438 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -6,130 +6,25 @@ Most of these settings are variable (can change), like database URLs. And many c For this reason it's common to provide them in environment variables that are read by the application. -## Environment Variables +/// tip -!!! tip - If you already know what "environment variables" are and how to use them, feel free to skip to the next section below. +To understand environment variables you can read [Environment Variables](../environment-variables.md){.internal-link target=_blank}. -An environment variable (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well). +/// -You can create and use environment variables in the shell, without needing Python: - -=== "Linux, macOS, Windows Bash" - -
- - ```console - // You could create an env var MY_NAME with - $ export MY_NAME="Wade Wilson" - - // Then you could use it with other programs, like - $ echo "Hello $MY_NAME" - - Hello Wade Wilson - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - // Create an env var MY_NAME - $ $Env:MY_NAME = "Wade Wilson" - - // Use it with other programs, like - $ echo "Hello $Env:MY_NAME" - - Hello Wade Wilson - ``` - -
- -### Read env vars in Python - -You could also create environment variables outside of Python, in the terminal (or with any other method), and then read them in Python. - -For example you could have a file `main.py` with: - -```Python hl_lines="3" -import os - -name = os.getenv("MY_NAME", "World") -print(f"Hello {name} from Python") -``` - -!!! tip - The second argument to `os.getenv()` is the default value to return. - - If not provided, it's `None` by default, here we provide `"World"` as the default value to use. - -Then you could call that Python program: - -
- -```console -// Here we don't set the env var yet -$ python main.py - -// As we didn't set the env var, we get the default value - -Hello World from Python - -// But if we create an environment variable first -$ export MY_NAME="Wade Wilson" - -// And then call the program again -$ python main.py - -// Now it can read the environment variable - -Hello Wade Wilson from Python -``` - -
- -As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or settings. - -You can also create an environment variable only for a specific program invocation, that is only available to that program, and only for its duration. - -To do that, create it right before the program itself, on the same line: - -
- -```console -// Create an env var MY_NAME in line for this program call -$ MY_NAME="Wade Wilson" python main.py - -// Now it can read the environment variable - -Hello Wade Wilson from Python - -// The env var no longer exists afterwards -$ python main.py - -Hello World from Python -``` - -
- -!!! tip - You can read more about it at The Twelve-Factor App: Config. - -### Types and validation +## Types and validation These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). -That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or validation has to be done in code. +That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code. ## Pydantic `Settings` -Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with Pydantic: Settings management. +Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with Pydantic: Settings management. ### Install `pydantic-settings` -First, install the `pydantic-settings` package: +First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install the `pydantic-settings` package:
@@ -151,8 +46,11 @@ $ pip install "fastapi[all]"
-!!! info - In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality. +/// info + +In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality. + +/// ### Create the `Settings` object @@ -162,23 +60,33 @@ The same way as with Pydantic models, you declare class attributes with type ann You can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`. -=== "Pydantic v2" +//// tab | Pydantic v2 - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001.py!} - ``` +```Python hl_lines="2 5-8 11" +{!> ../../docs_src/settings/tutorial001.py!} +``` + +//// + +//// tab | Pydantic v1 + +/// info -=== "Pydantic v1" +In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`. + +/// + +```Python hl_lines="2 5-8 11" +{!> ../../docs_src/settings/tutorial001_pv1.py!} +``` - !!! info - In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`. +//// - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001_pv1.py!} - ``` +/// tip -!!! tip - If you want something quick to copy and paste, don't use this example, use the last one below. +If you want something quick to copy and paste, don't use this example, use the last one below. + +/// Then, when you create an instance of that `Settings` class (in this case, in the `settings` object), Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable `APP_NAME` will still be read for the attribute `app_name`. @@ -189,7 +97,7 @@ Next it will convert and validate the data. So, when you use that `settings` obj Then you can use the new `settings` object in your application: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### Run the server @@ -199,15 +107,18 @@ Next, you would run the server passing the configurations as environment variabl
```console -$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ```
-!!! tip - To set multiple env vars for a single command just separate them with a space, and put them all before the command. +/// tip + +To set multiple env vars for a single command just separate them with a space, and put them all before the command. + +/// And then the `admin_email` setting would be set to `"deadpool@example.com"`. @@ -222,17 +133,20 @@ You could put those settings in another module file as you saw in [Bigger Applic For example, you could have a file `config.py` with: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` And then use it in a file `main.py`: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` -!!! tip - You would also need a file `__init__.py` as you saw on [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. +/// tip + +You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. + +/// ## Settings in a dependency @@ -245,7 +159,7 @@ This could be especially useful during testing, as it's very easy to override a Coming from the previous example, your `config.py` file could look like: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` Notice that now we don't create a default instance `settings = Settings()`. @@ -254,61 +168,82 @@ Notice that now we don't create a default instance `settings = Settings()`. Now we create a dependency that returns a new `config.Settings()`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6 12-13" +{!> ../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="6 12-13" +{!> ../../docs_src/settings/app02_an/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="5 11-12" +{!> ../../docs_src/settings/app02/main.py!} +``` - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +//// -!!! tip - We'll discuss the `@lru_cache` in a bit. +/// tip - For now you can assume `get_settings()` is a normal function. +We'll discuss the `@lru_cache` in a bit. + +For now you can assume `get_settings()` is a normal function. + +/// And then we can require it from the *path operation function* as a dependency and use it anywhere we need it. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="17 19-21" +{!> ../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="16 18-20" +{!> ../../docs_src/settings/app02/main.py!} +``` - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +//// ### Settings and testing Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` In the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object. @@ -321,15 +256,21 @@ If you have many settings that possibly change a lot, maybe in different environ This practice is common enough that it has a name, these environment variables are commonly placed in a file `.env`, and the file is called a "dotenv". -!!! tip - A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS. +/// tip - But a dotenv file doesn't really have to have that exact filename. +A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS. + +But a dotenv file doesn't really have to have that exact filename. + +/// Pydantic has support for reading from these types of files using an external library. You can read more at Pydantic Settings: Dotenv (.env) support. -!!! tip - For this to work, you need to `pip install python-dotenv`. +/// tip + +For this to work, you need to `pip install python-dotenv`. + +/// ### The `.env` file @@ -344,32 +285,45 @@ APP_NAME="ChimichangApp" And then update your `config.py` with: -=== "Pydantic v2" +//// tab | Pydantic v2 + +```Python hl_lines="9" +{!> ../../docs_src/settings/app03_an/config.py!} +``` + +/// tip + +The `model_config` attribute is used just for Pydantic configuration. You can read more at Pydantic: Concepts: Configuration. + +/// - ```Python hl_lines="9" - {!> ../../../docs_src/settings/app03_an/config.py!} - ``` +//// - !!! tip - The `model_config` attribute is used just for Pydantic configuration. You can read more at Pydantic Model Config. +//// tab | Pydantic v1 -=== "Pydantic v1" +```Python hl_lines="9-10" +{!> ../../docs_src/settings/app03_an/config_pv1.py!} +``` + +/// tip + +The `Config` class is used just for Pydantic configuration. You can read more at Pydantic Model Config. + +/// - ```Python hl_lines="9-10" - {!> ../../../docs_src/settings/app03_an/config_pv1.py!} - ``` +//// - !!! tip - The `Config` class is used just for Pydantic configuration. You can read more at Pydantic Model Config. +/// info -!!! info - In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`. +In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`. + +/// Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use. ### Creating the `Settings` only once with `lru_cache` -Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then re-use the same settings object, instead of reading it for each request. +Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then reuse the same settings object, instead of reading it for each request. But every time we do: @@ -390,28 +344,37 @@ we would create that object for each request, and we would be reading the `.env` But as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +```Python hl_lines="1 11" +{!> ../../docs_src/settings/app03_an_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ non-Annotated" +```Python hl_lines="1 11" +{!> ../../docs_src/settings/app03_an/main.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 10" +{!> ../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// -Then for any subsequent calls of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. +Then for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. #### `lru_cache` Technical Details diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md index a089632ac..48e329fc1 100644 --- a/docs/en/docs/advanced/sub-applications.md +++ b/docs/en/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ If you need to have two independent FastAPI applications, with their own indepen First, create the main, top-level, **FastAPI** application, and its *path operations*: -```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3, 6:8] *} ### Sub-application @@ -20,9 +18,7 @@ Then, create your sub-application, and its *path operations*. This sub-application is just another standard FastAPI application, but this is the one that will be "mounted": -```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11, 14:16] *} ### Mount the sub-application @@ -30,18 +26,16 @@ In your top-level application, `app`, mount the sub-application, `subapi`. In this case, it will be mounted at the path `/subapi`: -```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11, 19] *} ### Check the automatic API docs -Now, run `uvicorn` with the main app, if your file is `main.py`, it would be: +Now, run the `fastapi` command with your file:
```console -$ uvicorn main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -70,4 +64,4 @@ That way, the sub-application will know to use that path prefix for the docs UI. And the sub-application could also have its own mounted sub-applications and everything would work correctly, because FastAPI handles all these `root_path`s automatically. -You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}. +You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 6055b3017..76f0ef1de 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -8,7 +8,7 @@ There are utilities to configure it easily that you can use directly in your **F ## Install dependencies -Install `jinja2`: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `jinja2`:
@@ -23,33 +23,42 @@ $ pip install jinja2 ## Using `Jinja2Templates` * Import `Jinja2Templates`. -* Create a `templates` object that you can re-use later. +* Create a `templates` object that you can reuse later. * Declare a `Request` parameter in the *path operation* that will return a template. * Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template. ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` -!!! note - Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. +/// note - Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. +Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. -!!! tip - By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. +Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. -!!! note "Technical Details" - You could also use `from starlette.templating import Jinja2Templates`. +/// - **FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`. +/// tip + +By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. + +/// + +/// note | Technical Details + +You could also use `from starlette.templating import Jinja2Templates`. + +**FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`. + +/// ## Writing templates Then you can write a template at `templates/item.html` with, for example: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### Template Context Values @@ -103,13 +112,13 @@ For example, with an ID of `42`, this would render: You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` In this example, it would link to a CSS file at `static/styles.css` with: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` And because you are using `StaticFiles`, that CSS file would be served automatically by your **FastAPI** application at the URL `/static/styles.css`. diff --git a/docs/en/docs/advanced/testing-database.md b/docs/en/docs/advanced/testing-database.md deleted file mode 100644 index 1c0669b9c..000000000 --- a/docs/en/docs/advanced/testing-database.md +++ /dev/null @@ -1,102 +0,0 @@ -# Testing a Database - -!!! info - These docs are about to be updated. 🎉 - - The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. - - The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. - -You can use the same dependency overrides from [Testing Dependencies with Overrides](testing-dependencies.md){.internal-link target=_blank} to alter a database for testing. - -You could want to set up a different database for testing, rollback the data after the tests, pre-fill it with some testing data, etc. - -The main idea is exactly the same you saw in that previous chapter. - -## Add tests for the SQL app - -Let's update the example from [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} to use a testing database. - -All the app code is the same, you can go back to that chapter check how it was. - -The only changes here are in the new testing file. - -Your normal dependency `get_db()` would return a database session. - -In the test, you could use a dependency override to return your *custom* database session instead of the one that would be used normally. - -In this example we'll create a temporary database only for the tests. - -## File structure - -We create a new file at `sql_app/tests/test_sql_app.py`. - -So the new file structure looks like: - -``` hl_lines="9-11" -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - ├── schemas.py - └── tests - ├── __init__.py - └── test_sql_app.py -``` - -## Create the new database session - -First, we create a new database session with the new database. - -We'll use an in-memory database that persists during the tests instead of the local file `sql_app.db`. - -But the rest of the session code is more or less the same, we just copy it. - -```Python hl_lines="8-13" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -!!! tip - You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`. - - For simplicity and to focus on the specific testing code, we are just copying it. - -## Create the database - -Because now we are going to use a new database in a new file, we need to make sure we create the database with: - -```Python -Base.metadata.create_all(bind=engine) -``` - -That is normally called in `main.py`, but the line in `main.py` uses the database file `sql_app.db`, and we need to make sure we create `test.db` for the tests. - -So we add that line here, with the new file. - -```Python hl_lines="16" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -## Dependency override - -Now we create the dependency override and add it to the overrides for our app. - -```Python hl_lines="19-24 27" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -!!! tip - The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead. - -## Test the app - -Then we can just test the app as normally. - -```Python hl_lines="32-47" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -And all the modifications we made in the database during the tests will be in the `test.db` database instead of the main `sql_app.db`. diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md index 57dd87f56..1cc4313a1 100644 --- a/docs/en/docs/advanced/testing-dependencies.md +++ b/docs/en/docs/advanced/testing-dependencies.md @@ -28,48 +28,67 @@ To override a dependency for testing, you put as a key the original dependency ( And then **FastAPI** will call that override instead of the original dependency. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="26-27 30" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} - ``` +```Python hl_lines="26-27 30" +{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="28-29 32" +{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="29-30 33" +{!> ../../docs_src/dependency_testing/tutorial001_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python hl_lines="29-30 33" - {!> ../../../docs_src/dependency_testing/tutorial001_an.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.10+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="24-25 28" +{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="24-25 28" - {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Prefer to use the `Annotated` version if possible. - !!! tip - Prefer to use the `Annotated` version if possible. +/// + +```Python hl_lines="28-29 32" +{!> ../../docs_src/dependency_testing/tutorial001.py!} +``` - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001.py!} - ``` +//// -!!! tip - You can set a dependency override for a dependency used anywhere in your **FastAPI** application. +/// tip - The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc. +You can set a dependency override for a dependency used anywhere in your **FastAPI** application. - FastAPI will still be able to override it. +The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc. + +FastAPI will still be able to override it. + +/// Then you can reset your overrides (remove them) by setting `app.dependency_overrides` to be an empty `dict`: @@ -77,5 +96,8 @@ Then you can reset your overrides (remove them) by setting `app.dependency_overr app.dependency_overrides = {} ``` -!!! tip - If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function). +/// tip + +If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function). + +/// diff --git a/docs/en/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md index b24a2ccfe..f48907c7c 100644 --- a/docs/en/docs/advanced/testing-events.md +++ b/docs/en/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement: ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/en/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md index 4101e5a16..60dfdc343 100644 --- a/docs/en/docs/advanced/testing-websockets.md +++ b/docs/en/docs/advanced/testing-websockets.md @@ -4,9 +4,10 @@ You can use the same `TestClient` to test WebSockets. For this, you use the `TestClient` in a `with` statement, connecting to the WebSocket: -```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} -!!! note - For more details, check Starlette's documentation for testing WebSockets. +/// note + +For more details, check Starlette's documentation for testing WebSockets. + +/// diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md index 500afa34b..2f88c8f20 100644 --- a/docs/en/docs/advanced/using-request-directly.md +++ b/docs/en/docs/advanced/using-request-directly.md @@ -29,24 +29,28 @@ Let's imagine you want to get the client's IP address/host inside of your *path For that you need to access the request directly. -```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter. -!!! tip - Note that in this case, we are declaring a path parameter beside the request parameter. +/// tip - So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI. +Note that in this case, we are declaring a path parameter beside the request parameter. - The same way, you can declare any other parameter as normally, and additionally, get the `Request` too. +So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI. + +The same way, you can declare any other parameter as normally, and additionally, get the `Request` too. + +/// ## `Request` documentation You can read more details about the `Request` object in the official Starlette documentation site. -!!! note "Technical Details" - You could also use `from starlette.requests import Request`. +/// note | Technical Details + +You could also use `from starlette.requests import Request`. + +**FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette. - **FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette. +/// diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index b8dfab1d1..ee8e901df 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -4,7 +4,7 @@ You can use @@ -38,30 +38,27 @@ In production you would have one of the options above. But it's the simplest way to focus on the server-side of WebSockets and have a working example: -```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## Create a `websocket` In your **FastAPI** application, create a `websocket`: -```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | Technical Details -!!! note "Technical Details" - You could also use `from starlette.websockets import WebSocket`. +You could also use `from starlette.websockets import WebSocket`. - **FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette. +**FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette. + +/// ## Await for messages and send messages In your WebSocket route you can `await` for messages and send messages. -```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} You can receive and send binary, text, and JSON data. @@ -72,7 +69,7 @@ If your file is named `main.py`, run your application with:
```console -$ uvicorn main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -112,46 +109,15 @@ In WebSocket endpoints you can import from `fastapi` and use: They work the same way as for other FastAPI endpoints/*path operations*: -=== "Python 3.10+" - - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} - !!! tip - Prefer to use the `Annotated` version if possible. +/// info - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`. -=== "Python 3.8+ non-Annotated" +You can use a closing code from the valid codes defined in the specification. - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` - -!!! info - As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`. - - You can use a closing code from the valid codes defined in the specification. +/// ### Try the WebSockets with dependencies @@ -160,7 +126,7 @@ If your file is named `main.py`, run your application with:
```console -$ uvicorn main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -174,8 +140,11 @@ There you can set: * The "Item ID", used in the path. * The "Token" used as a query parameter. -!!! tip - Notice that the query `token` will be handled by a dependency. +/// tip + +Notice that the query `token` will be handled by a dependency. + +/// With that you can connect the WebSocket and then send and receive messages: @@ -185,17 +154,7 @@ With that you can connect the WebSocket and then send and receive messages: When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example. -=== "Python 3.9+" - - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} To try it out: @@ -209,12 +168,15 @@ That will raise the `WebSocketDisconnect` exception, and all the other clients w Client #1596980209979 left the chat ``` -!!! tip - The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. +/// tip + +The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. + +But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. - But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. +If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster. - If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster. +/// ## More info diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md index cfe3c78c1..296eb1364 100644 --- a/docs/en/docs/advanced/wsgi.md +++ b/docs/en/docs/advanced/wsgi.md @@ -1,6 +1,6 @@ # Including WSGI - Flask, Django, others -You can mount WSGI applications as you saw with [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}. +You can mount WSGI applications as you saw with [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}. For that, you can use the `WSGIMiddleware` and use it to wrap your WSGI application, for example, Flask, Django, etc. @@ -12,9 +12,7 @@ Then wrap the WSGI (e.g. Flask) app with the middleware. And then mount that under a path. -```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,3] *} ## Check it @@ -22,7 +20,7 @@ Now, every request under the path `/v1/` will be handled by the Flask applicatio And the rest will be handled by **FastAPI**. -If you run it with Uvicorn and go to http://localhost:8000/v1/ you will see the response from Flask: +If you run it and go to http://localhost:8000/v1/ you will see the response from Flask: ```txt Hello, World from Flask! diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index d351c4e0b..326f0dbe1 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -1,6 +1,6 @@ # Alternatives, Inspiration and Comparisons -What inspired **FastAPI**, how it compares to other alternatives and what it learned from them. +What inspired **FastAPI**, how it compares to alternatives and what it learned from them. ## Intro @@ -30,12 +30,17 @@ It is used by many companies including Mozilla, Red Hat and Eventbrite. It was one of the first examples of **automatic API documentation**, and this was specifically one of the first ideas that inspired "the search for" **FastAPI**. -!!! note - Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based. +/// note +Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based. -!!! check "Inspired **FastAPI** to" - Have an automatic API documentation web user interface. +/// + +/// check | Inspired **FastAPI** to + +Have an automatic API documentation web user interface. + +/// ### Flask @@ -51,11 +56,13 @@ This decoupling of parts, and being a "microframework" that could be extended to Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask. -!!! check "Inspired **FastAPI** to" - Be a micro-framework. Making it easy to mix and match the tools and parts needed. +/// check | Inspired **FastAPI** to - Have a simple and easy to use routing system. +Be a micro-framework. Making it easy to mix and match the tools and parts needed. +Have a simple and easy to use routing system. + +/// ### Requests @@ -91,11 +98,13 @@ def read_url(): See the similarities in `requests.get(...)` and `@app.get(...)`. -!!! check "Inspired **FastAPI** to" - * Have a simple and intuitive API. - * Use HTTP method names (operations) directly, in a straightforward and intuitive way. - * Have sensible defaults, but powerful customizations. +/// check | Inspired **FastAPI** to + +* Have a simple and intuitive API. +* Use HTTP method names (operations) directly, in a straightforward and intuitive way. +* Have sensible defaults, but powerful customizations. +/// ### Swagger / OpenAPI @@ -109,15 +118,18 @@ At some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI. That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI". -!!! check "Inspired **FastAPI** to" - Adopt and use an open standard for API specifications, instead of a custom schema. +/// check | Inspired **FastAPI** to + +Adopt and use an open standard for API specifications, instead of a custom schema. - And integrate standards-based user interface tools: +And integrate standards-based user interface tools: - * Swagger UI - * ReDoc +* Swagger UI +* ReDoc - These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of additional alternative user interfaces for OpenAPI (that you can use with **FastAPI**). +These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**). + +/// ### Flask REST frameworks @@ -135,8 +147,11 @@ These features are what Marshmallow was built to provide. It is a great library, But it was created before there existed Python type hints. So, to define every schema you need to use specific utils and classes provided by Marshmallow. -!!! check "Inspired **FastAPI** to" - Use code to define "schemas" that provide data types and validation, automatically. +/// check | Inspired **FastAPI** to + +Use code to define "schemas" that provide data types and validation, automatically. + +/// ### Webargs @@ -148,11 +163,17 @@ It uses Marshmallow underneath to do the data validation. And it was created by It's a great tool and I have used it a lot too, before having **FastAPI**. -!!! info - Webargs was created by the same Marshmallow developers. +/// info + +Webargs was created by the same Marshmallow developers. + +/// + +/// check | Inspired **FastAPI** to -!!! check "Inspired **FastAPI** to" - Have automatic validation of incoming request data. +Have automatic validation of incoming request data. + +/// ### APISpec @@ -172,12 +193,17 @@ But then, we have again the problem of having a micro-syntax, inside of a Python The editor can't help much with that. And if we modify parameters or Marshmallow schemas and forget to also modify that YAML docstring, the generated schema would be obsolete. -!!! info - APISpec was created by the same Marshmallow developers. +/// info + +APISpec was created by the same Marshmallow developers. + +/// +/// check | Inspired **FastAPI** to -!!! check "Inspired **FastAPI** to" - Support the open standard for APIs, OpenAPI. +Support the open standard for APIs, OpenAPI. + +/// ### Flask-apispec @@ -199,11 +225,17 @@ Using it led to the creation of several Flask full-stack generators. These are t And these same full-stack generators were the base of the [**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec was created by the same Marshmallow developers. +/// info + +Flask-apispec was created by the same Marshmallow developers. + +/// -!!! check "Inspired **FastAPI** to" - Generate the OpenAPI schema automatically, from the same code that defines serialization and validation. +/// check | Inspired **FastAPI** to + +Generate the OpenAPI schema automatically, from the same code that defines serialization and validation. + +/// ### NestJS (and Angular) @@ -219,24 +251,33 @@ But as TypeScript data is not preserved after compilation to JavaScript, it cann It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated. -!!! check "Inspired **FastAPI** to" - Use Python types to have great editor support. +/// check | Inspired **FastAPI** to + +Use Python types to have great editor support. - Have a powerful dependency injection system. Find a way to minimize code repetition. +Have a powerful dependency injection system. Find a way to minimize code repetition. + +/// ### Sanic It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask. -!!! note "Technical Details" - It used `uvloop` instead of the default Python `asyncio` loop. That's what made it so fast. +/// note | Technical Details + +It used `uvloop` instead of the default Python `asyncio` loop. That's what made it so fast. - It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks. +It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks. -!!! check "Inspired **FastAPI** to" - Find a way to have a crazy performance. +/// - That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks). +/// check | Inspired **FastAPI** to + +Find a way to have a crazy performance. + +That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks). + +/// ### Falcon @@ -246,12 +287,15 @@ It is designed to have functions that receive two parameters, one "request" and So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters. -!!! check "Inspired **FastAPI** to" - Find ways to get great performance. +/// check | Inspired **FastAPI** to - Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions. +Find ways to get great performance. - Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes. +Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions. + +Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes. + +/// ### Molten @@ -269,12 +313,15 @@ The dependency injection system requires pre-registration of the dependencies an Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled. -!!! check "Inspired **FastAPI** to" - Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before. +/// check | Inspired **FastAPI** to + +Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before. - This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic). +This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic). -### Hug +/// + +### Hug Hug was one of the first frameworks to implement the declaration of API parameter types using Python type hints. This was a great idea that inspired other tools to do the same. @@ -288,15 +335,21 @@ It has an interesting, uncommon feature: using the same framework, it's possible As it is based on the previous standard for synchronous Python web frameworks (WSGI), it can't handle Websockets and other things, although it still has high performance too. -!!! info - Hug was created by Timothy Crosley, the same creator of `isort`, a great tool to automatically sort imports in Python files. +/// info + +Hug was created by Timothy Crosley, the same creator of `isort`, a great tool to automatically sort imports in Python files. + +/// -!!! check "Ideas inspired in **FastAPI**" - Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar. +/// check | Ideas inspiring **FastAPI** - Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically. +Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar. - Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies. +Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically. + +Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies. + +/// ### APIStar (<= 0.5) @@ -322,23 +375,29 @@ It was no longer an API web framework, as the creator needed to focus on Starlet Now APIStar is a set of tools to validate OpenAPI specifications, not a web framework. -!!! info - APIStar was created by Tom Christie. The same guy that created: +/// info + +APIStar was created by Tom Christie. The same guy that created: - * Django REST Framework - * Starlette (in which **FastAPI** is based) - * Uvicorn (used by Starlette and **FastAPI**) +* Django REST Framework +* Starlette (in which **FastAPI** is based) +* Uvicorn (used by Starlette and **FastAPI**) -!!! check "Inspired **FastAPI** to" - Exist. +/// - The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea. +/// check | Inspired **FastAPI** to - And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available. +Exist. - Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**. +The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea. - I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools. +And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available. + +Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**. + +I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools. + +/// ## Used by **FastAPI** @@ -350,10 +409,13 @@ That makes it extremely intuitive. It is comparable to Marshmallow. Although it's faster than Marshmallow in benchmarks. And as it is based on the same Python type hints, the editor support is great. -!!! check "**FastAPI** uses it to" - Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema). +/// check | **FastAPI** uses it to - **FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does. +Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema). + +**FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does. + +/// ### Starlette @@ -382,17 +444,23 @@ But it doesn't provide automatic data validation, serialization or documentation That's one of the main things that **FastAPI** adds on top, all based on Python type hints (using Pydantic). That, plus the dependency injection system, security utilities, OpenAPI schema generation, etc. -!!! note "Technical Details" - ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that. +/// note | Technical Details + +ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that. - Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`. +Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`. -!!! check "**FastAPI** uses it to" - Handle all the core web parts. Adding features on top. +/// - The class `FastAPI` itself inherits directly from the class `Starlette`. +/// check | **FastAPI** uses it to - So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids. +Handle all the core web parts. Adding features on top. + +The class `FastAPI` itself inherits directly from the class `Starlette`. + +So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids. + +/// ### Uvicorn @@ -402,12 +470,15 @@ It is not a web framework, but a server. For example, it doesn't provide tools f It is the recommended server for Starlette and **FastAPI**. -!!! check "**FastAPI** recommends it as" - The main web server to run **FastAPI** applications. +/// check | **FastAPI** recommends it as + +The main web server to run **FastAPI** applications. + +You can also use the `--workers` command line option to have an asynchronous multi-process server. - You can combine it with Gunicorn, to have an asynchronous multi-process server. +Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. - Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. +/// ## Benchmarks and speed diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index ff322635a..63bd8ca68 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - You can only use `await` inside of functions created with `async def`. +/// note + +You can only use `await` inside of functions created with `async def`. + +/// --- @@ -136,8 +139,11 @@ You and your crush eat the burgers and have a nice time. ✨ -!!! info - Beautiful illustrations by Ketrina Thompson. 🎨 +/// info + +Beautiful illustrations by Ketrina Thompson. 🎨 + +/// --- @@ -199,8 +205,11 @@ You just eat them, and you are done. ⏹ There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞 -!!! info - Beautiful illustrations by Ketrina Thompson. 🎨 +/// info + +Beautiful illustrations by Ketrina Thompson. 🎨 + +/// --- @@ -222,7 +231,7 @@ All of the cashiers doing all the work with one client after the other 👨‍ And you have to wait 🕙 in the line for a long time or you lose your turn. -You probably wouldn't want to take your crush 😍 with you to do errands at the bank 🏦. +You probably wouldn't want to take your crush 😍 with you to run errands at the bank 🏦. ### Burger Conclusion @@ -283,7 +292,7 @@ For example: ### Concurrency + Parallelism: Web + Machine Learning -With **FastAPI** you can take the advantage of concurrency that is very common for web development (the same main attraction of NodeJS). +With **FastAPI** you can take advantage of concurrency that is very common for web development (the same main attraction of NodeJS). But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems. @@ -360,6 +369,8 @@ In particular, you can directly use AnyIO to be highly compatible and get its benefits (e.g. *structured concurrency*). +I created another library on top of AnyIO, as a thin layer on top, to improve a bit the type annotations and get better **autocompletion**, **inline errors**, etc. It also has a friendly introduction and tutorial to help you **understand** and write **your own async code**: Asyncer. It would be particularly useful if you need to **combine async code with regular** (blocking/synchronous) code. + ### Other forms of asynchronous code This style of using `async` and `await` is relatively new in the language. @@ -376,7 +387,7 @@ In previous versions of NodeJS / Browser JavaScript, you would have used "callba ## Coroutines -**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. +**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function, that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. But all this functionality of using asynchronous code with `async` and `await` is many times summarized as using "coroutines". It is comparable to the main key feature of Go, the "Goroutines". @@ -392,12 +403,15 @@ All that is what powers FastAPI (through Starlette) and what makes it have such ## Very Technical Details -!!! warning - You can probably skip this. +/// warning + +You can probably skip this. + +These are very technical details of how **FastAPI** works underneath. - These are very technical details of how **FastAPI** works underneath. +If you have quite some technical knowledge (coroutines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead. - If you have quite some technical knowledge (co-routines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead. +/// ### Path operation functions @@ -409,11 +423,11 @@ Still, in both situations, chances are that **FastAPI** will [still be faster](i ### Dependencies -The same applies for [dependencies](./tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool. +The same applies for [dependencies](tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool. ### Sub-dependencies -You can have multiple dependencies and [sub-dependencies](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited". +You can have multiple dependencies and [sub-dependencies](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited". ### Other utility functions diff --git a/docs/en/docs/benchmarks.md b/docs/en/docs/benchmarks.md index d746b6d7c..62266c449 100644 --- a/docs/en/docs/benchmarks.md +++ b/docs/en/docs/benchmarks.md @@ -1,6 +1,6 @@ # Benchmarks -Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*) +Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). But when checking benchmarks and comparisons you should keep the following in mind. diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 2d308a9db..3a25b4ed5 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -4,106 +4,15 @@ First, you might want to see the basic ways to [help FastAPI and get help](help- ## Developing -If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment. +If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment. -### Virtual environment with `venv` +### Virtual environment -You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is): - -
- -```console -$ python -m venv env -``` - -
- -That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment. - -### Activate the environment - -Activate the new environment with: - -=== "Linux, macOS" - -
- - ```console - $ source ./env/bin/activate - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ .\env\Scripts\Activate.ps1 - ``` - -
- -=== "Windows Bash" - - Or if you use Bash for Windows (e.g. Git Bash): - -
- - ```console - $ source ./env/Scripts/activate - ``` - -
- -To check it worked, use: - -=== "Linux, macOS, Windows Bash" - -
- - ```console - $ which pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ Get-Command pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 - -Make sure you have the latest pip version on your local environment to avoid errors on the next steps: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -!!! tip - Every time you install a new package with `pip` under that environment, activate the environment again. - - This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. +Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `fastapi`. ### Install requirements using pip -After activating the environment as described above: +After activating the environment, install the required packages:
@@ -125,10 +34,13 @@ And if you update that local FastAPI source code when you run that Python file a That way, you don't have to "install" your local version to be able to test every change. -!!! note "Technical Details" - This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. +/// note | Technical Details + +This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. - That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. +That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. + +/// ### Format the code @@ -144,7 +56,19 @@ $ bash scripts/format.sh It will also auto-sort all your imports. -For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above using `-e`. +## Tests + +There is a script that you can run locally to test all the code and generate coverage reports in HTML: + +
+ +```console +$ bash scripts/test-cov-html.sh +``` + +
+ +This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. ## Docs @@ -170,20 +94,23 @@ It will serve the documentation on `http://127.0.0.1:8008`. That way, you can edit the documentation/source files and see the changes live. -!!! tip - Alternatively, you can perform the same steps that scripts does manually. +/// tip + +Alternatively, you can perform the same steps that scripts does manually. + +Go into the language directory, for the main docs in English it's at `docs/en/`: - Go into the language directory, for the main docs in English it's at `docs/en/`: +```console +$ cd docs/en/ +``` - ```console - $ cd docs/en/ - ``` +Then run `mkdocs` in that directory: - Then run `mkdocs` in that directory: +```console +$ mkdocs serve --dev-addr 8008 +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +/// #### Typer CLI (optional) @@ -210,8 +137,11 @@ The documentation uses ```console -$ uvicorn tutorial001:app --reload +$ fastapi dev tutorial001.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -257,16 +187,19 @@ Here are the steps to help with translations. #### Tips and guidelines -* Check the currently existing pull requests for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is `lang-es`. +* Check the currently existing pull requests for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is `lang-es`. * Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging. -!!! tip - You can add comments with change suggestions to existing pull requests. +/// tip + +You can add comments with change suggestions to existing pull requests. - Check the docs about adding a pull request review to approve it or request changes. +Check the docs about adding a pull request review to approve it or request changes. -* Check if there's a GitHub Discussion to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. +/// + +* Check if there's a GitHub Discussion to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. * If you translate pages, add a single pull request per page translated. That will make it much easier for others to review it. @@ -278,8 +211,11 @@ Let's say you want to translate a page for a language that already has translati In the case of Spanish, the 2-letter code is `es`. So, the directory for Spanish translations is located at `docs/es/`. -!!! tip - The main ("official") language is English, located at `docs/en/`. +/// tip + +The main ("official") language is English, located at `docs/en/`. + +/// Now run the live server for the docs in Spanish: @@ -296,20 +232,23 @@ $ python ./scripts/docs.py live es
-!!! tip - Alternatively, you can perform the same steps that scripts does manually. +/// tip - Go into the language directory, for the Spanish translations it's at `docs/es/`: +Alternatively, you can perform the same steps that scripts does manually. - ```console - $ cd docs/es/ - ``` +Go into the language directory, for the Spanish translations it's at `docs/es/`: - Then run `mkdocs` in that directory: +```console +$ cd docs/es/ +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +Then run `mkdocs` in that directory: + +```console +$ mkdocs serve --dev-addr 8008 +``` + +/// Now you can go to http://127.0.0.1:8008 and see your changes live. @@ -329,13 +268,30 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - Notice that the only change in the path and file name is the language code, from `en` to `es`. +/// tip + +Notice that the only change in the path and file name is the language code, from `en` to `es`. + +/// If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉 Now you can translate it all and see how it looks as you save the file. +#### Don't Translate these Pages + +🚨 Don't translate: + +* Files under `reference/` +* `release-notes.md` +* `fastapi-people.md` +* `external-links.md` +* `newsletter.md` +* `management-tasks.md` +* `management.md` + +Some of these files are updated very frequently and a translation would always be behind, or they include the main content from English source files, etc. + #### New Language Let's say that you want to add translations for a language that is not yet translated, not even some pages. @@ -365,8 +321,11 @@ That command created a file `docs/ht/mkdocs.yml` with a simple config that inher INHERIT: ../en/mkdocs.yml ``` -!!! tip - You could also simply create that file with those contents manually. +/// tip + +You could also simply create that file with those contents manually. + +/// That command also created a dummy file `docs/ht/index.md` for the main page, you can start by translating that one. @@ -421,9 +380,9 @@ Serving at: http://127.0.0.1:8008 * Do not change anything enclosed in "``" (inline code). -* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged. +* In lines starting with `///` translate only the ` "... Text ..."` part. Leave the rest unchanged. -* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box. +* You can translate info boxes like `/// warning` with for example `/// warning | Achtung`. But do not change the word immediately after the `///`, it determines the color of the info box. * Do not change the paths in links to images, code files, Markdown documents. @@ -431,17 +390,3 @@ Serving at: http://127.0.0.1:8008 * Search for such links in the translated document using the regex `#[^# ]`. * Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files". * When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents. - -## Tests - -There is a script that you can run locally to test all the code and generate coverage reports in HTML: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. diff --git a/docs/en/docs/css/custom.css b/docs/en/docs/css/custom.css index 386aa9d7e..b192f6123 100644 --- a/docs/en/docs/css/custom.css +++ b/docs/en/docs/css/custom.css @@ -13,6 +13,10 @@ white-space: pre-wrap; } +.termy .linenos { + display: none; +} + a.external-link { /* For right to left languages */ direction: ltr; diff --git a/docs/en/docs/css/termynal.css b/docs/en/docs/css/termynal.css index 406c00897..8534f9102 100644 --- a/docs/en/docs/css/termynal.css +++ b/docs/en/docs/css/termynal.css @@ -26,6 +26,8 @@ position: relative; -webkit-box-sizing: border-box; box-sizing: border-box; + /* Custom line-height */ + line-height: 1.2; } [data-termynal]:before { diff --git a/docs/en/docs/deployment/cloud.md b/docs/en/docs/deployment/cloud.md index d34fbe2f7..471808851 100644 --- a/docs/en/docs/deployment/cloud.md +++ b/docs/en/docs/deployment/cloud.md @@ -14,4 +14,5 @@ You might want to try their services and follow their guides: * Platform.sh * Porter -* Coherence +* Coherence +* Render diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index cc01fb24e..e71a7487a 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -25,7 +25,7 @@ But for now, let's check these important **conceptual ideas**. These concepts al ## Security - HTTPS -In the [previous chapter about HTTPS](./https.md){.internal-link target=_blank} we learned about how HTTPS provides encryption for your API. +In the [previous chapter about HTTPS](https.md){.internal-link target=_blank} we learned about how HTTPS provides encryption for your API. We also saw that HTTPS is normally provided by a component **external** to your application server, a **TLS Termination Proxy**. @@ -94,7 +94,7 @@ In most cases, when you create a web API, you want it to be **always running**, ### In a Remote Server -When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is to run Uvicorn (or similar) manually, the same way you do when developing locally. +When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is use `fastapi run` (which uses Uvicorn) or something similar, manually, the same way you do when developing locally. And it will work and will be useful **during development**. @@ -151,10 +151,13 @@ And still, you would probably not want the application to stay dead because ther But in those cases with really bad errors that crash the running **process**, you would want an external component that is in charge of **restarting** the process, at least a couple of times... -!!! tip - ...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment. +/// tip - So let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it. +...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment. + +So let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it. + +/// You would probably want to have the thing in charge of restarting your application as an **external component**, because by that point, the same application with Uvicorn and Python already crashed, so there's nothing in the same code of the same app that could do anything about it. @@ -175,7 +178,7 @@ For example, this could be handled by: ## Replication - Processes and Memory -With a FastAPI application, using a server program like Uvicorn, running it once in **one process** can serve multiple clients concurrently. +With a FastAPI application, using a server program like the `fastapi` command that runs Uvicorn, running it once in **one process** can serve multiple clients concurrently. But in many cases, you will want to run several worker processes at the same time. @@ -187,7 +190,7 @@ When you run **multiple processes** of the same API program, they are commonly c ### Worker Processes and Ports -Remember from the docs [About HTTPS](./https.md){.internal-link target=_blank} that only one process can be listening on one combination of port and IP address in a server? +Remember from the docs [About HTTPS](https.md){.internal-link target=_blank} that only one process can be listening on one combination of port and IP address in a server? This is still true. @@ -229,19 +232,20 @@ The main constraint to consider is that there has to be a **single** component h Here are some possible combinations and strategies: -* **Gunicorn** managing **Uvicorn workers** - * Gunicorn would be the **process manager** listening on the **IP** and **port**, the replication would be by having **multiple Uvicorn worker processes** -* **Uvicorn** managing **Uvicorn workers** - * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes** +* **Uvicorn** with `--workers` + * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**. * **Kubernetes** and other distributed **container systems** - * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running + * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running. * **Cloud services** that handle this for you * The cloud service will probably **handle replication for you**. It would possibly let you define **a process to run**, or a **container image** to use, in any case, it would most probably be **a single Uvicorn process**, and the cloud service would be in charge of replicating it. -!!! tip - Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet. +/// tip + +Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet. + +I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. - I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank}. +/// ## Previous Steps Before Starting @@ -253,14 +257,17 @@ But in most cases, you will want to perform these steps only **once**. So, you will want to have a **single process** to perform those **previous steps**, before starting the application. -And you will have to make sure that it's a single process running those previous steps *even* if afterwards, you start **multiple processes** (multiple workers) for the application itself. If those steps were run by **multiple processes**, they would **duplicate** the work by running it on **parallel**, and if the steps were something delicate like a database migration, they could cause conflicts with each other. +And you will have to make sure that it's a single process running those previous steps *even* if afterwards, you start **multiple processes** (multiple workers) for the application itself. If those steps were run by **multiple processes**, they would **duplicate** the work by running it in **parallel**, and if the steps were something delicate like a database migration, they could cause conflicts with each other. Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle. -!!! tip - Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. +/// tip - In that case, you wouldn't have to worry about any of this. 🤷 +Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. + +In that case, you wouldn't have to worry about any of this. 🤷 + +/// ### Examples of Previous Steps Strategies @@ -272,8 +279,11 @@ Here are some possible ideas: * A bash script that runs the previous steps and then starts your application * You would still need a way to start/restart *that* bash script, detect errors, etc. -!!! tip - I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank}. +/// tip + +I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. + +/// ## Resource Utilization diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 8a542622e..b106f7ac3 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -4,8 +4,11 @@ When deploying FastAPI applications a common approach is to build a **Linux cont Using Linux containers has several advantages including **security**, **replicability**, **simplicity**, and others. -!!! tip - In a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi). +/// tip + +In a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi). + +///
Dockerfile Preview 👀 @@ -21,10 +24,10 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./app /code/app -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--port", "80"] # If running behind a proxy like Nginx or Traefik add --proxy-headers -# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +# CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"] ```
@@ -70,7 +73,7 @@ And there are many other images for different things like databases, for example By using a pre-made container image it's very easy to **combine** and use different tools. For example, to try out a new database. In most cases, you can use the **official images**, and just configure them with environment variables. -That way, in many cases you can learn about containers and Docker and re-use that knowledge with many different tools and components. +That way, in many cases you can learn about containers and Docker and reuse that knowledge with many different tools and components. So, you would run **multiple containers** with different things, like a database, a Python application, a web server with a React frontend application, and connect them together via their internal network. @@ -108,14 +111,13 @@ It would depend mainly on the tool you use to **install** those requirements. The most common way to do it is to have a file `requirements.txt` with the package names and their versions, one per line. -You would of course use the same ideas you read in [About FastAPI versions](./versions.md){.internal-link target=_blank} to set the ranges of versions. +You would of course use the same ideas you read in [About FastAPI versions](versions.md){.internal-link target=_blank} to set the ranges of versions. For example, your `requirements.txt` could look like: ``` -fastapi>=0.68.0,<0.69.0 -pydantic>=1.8.0,<2.0.0 -uvicorn>=0.15.0,<0.16.0 +fastapi[standard]>=0.113.0,<0.114.0 +pydantic>=2.7.0,<3.0.0 ``` And you would normally install those package dependencies with `pip`, for example: @@ -125,15 +127,16 @@ And you would normally install those package dependencies with `pip`, for exampl ```console $ pip install -r requirements.txt ---> 100% -Successfully installed fastapi pydantic uvicorn +Successfully installed fastapi pydantic ```
-!!! info - There are other formats and tools to define and install package dependencies. +/// info - I'll show you an example using Poetry later in a section below. 👇 +There are other formats and tools to define and install package dependencies. + +/// ### Create the **FastAPI** Code @@ -164,23 +167,23 @@ def read_item(item_id: int, q: Union[str, None] = None): Now in the same project directory create a file `Dockerfile` with: ```{ .dockerfile .annotate } -# (1) +# (1)! FROM python:3.9 -# (2) +# (2)! WORKDIR /code -# (3) +# (3)! COPY ./requirements.txt /code/requirements.txt -# (4) +# (4)! RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -# (5) +# (5)! COPY ./app /code/app -# (6) -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +# (6)! +CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` 1. Start from the official Python base image. @@ -199,8 +202,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] The `--no-cache-dir` option tells `pip` to not save the downloaded packages locally, as that is only if `pip` was going to be run again to install the same packages, but that's not the case when working with containers. - !!! note - The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers. + /// note + + The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers. + + /// The `--upgrade` option tells `pip` to upgrade the packages if they are already installed. @@ -214,16 +220,49 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] So, it's important to put this **near the end** of the `Dockerfile`, to optimize the container image build times. -6. Set the **command** to run the `uvicorn` server. +6. Set the **command** to use `fastapi run`, which uses Uvicorn underneath. `CMD` takes a list of strings, each of these strings is what you would type in the command line separated by spaces. This command will be run from the **current working directory**, the same `/code` directory you set above with `WORKDIR /code`. - Because the program will be started at `/code` and inside of it is the directory `./app` with your code, **Uvicorn** will be able to see and **import** `app` from `app.main`. +/// tip + +Review what each line does by clicking each number bubble in the code. 👆 + +/// + +/// warning + +Make sure to **always** use the **exec form** of the `CMD` instruction, as explained below. + +/// + +#### Use `CMD` - Exec Form + +The `CMD` Docker instruction can be written using two forms: + +✅ **Exec** form: + +```Dockerfile +# ✅ Do this +CMD ["fastapi", "run", "app/main.py", "--port", "80"] +``` + +⛔️ **Shell** form: + +```Dockerfile +# ⛔️ Don't do this +CMD fastapi run app/main.py --port 80 +``` + +Make sure to always use the **exec** form to ensure that FastAPI can shutdown gracefully and [lifespan events](../advanced/events.md){.internal-link target=_blank} are triggered. + +You can read more about it in the Docker docs for shell and exec form. + +This can be quite noticeable when using `docker compose`. See this Docker Compose FAQ section for more technical details: Why do my services take 10 seconds to recreate or stop?. -!!! tip - Review what each line does by clicking each number bubble in the code. 👆 +#### Directory Structure You should now have a directory structure like: @@ -238,10 +277,10 @@ You should now have a directory structure like: #### Behind a TLS Termination Proxy -If you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers`, this will tell Uvicorn to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc. +If you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers`, this will tell Uvicorn (through the FastAPI CLI) to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc. ```Dockerfile -CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"] ``` #### Docker Cache @@ -254,7 +293,7 @@ COPY ./requirements.txt /code/requirements.txt Docker and other tools **build** these container images **incrementally**, adding **one layer on top of the other**, starting from the top of the `Dockerfile` and adding any files created by each of the instructions of the `Dockerfile`. -Docker and similar tools also use an **internal cache** when building the image, if a file hasn't changed since the last time building the container image, then it will **re-use the same layer** created the last time, instead of copying the file again and creating a new layer from scratch. +Docker and similar tools also use an **internal cache** when building the image, if a file hasn't changed since the last time building the container image, then it will **reuse the same layer** created the last time, instead of copying the file again and creating a new layer from scratch. Just avoiding the copy of files doesn't necessarily improve things too much, but because it used the cache for that step, it can **use the cache for the next step**. For example, it could use the cache for the instruction that installs dependencies with: @@ -293,10 +332,13 @@ $ docker build -t myimage .
-!!! tip - Notice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image. +/// tip - In this case, it's the same current directory (`.`). +Notice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image. + +In this case, it's the same current directory (`.`). + +/// ### Start the Docker Container @@ -358,22 +400,22 @@ COPY ./requirements.txt /code/requirements.txt RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -# (1) +# (1)! COPY ./main.py /code/ -# (2) -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +# (2)! +CMD ["fastapi", "run", "main.py", "--port", "80"] ``` 1. Copy the `main.py` file to the `/code` directory directly (without any `./app` directory). -2. Run Uvicorn and tell it to import the `app` object from `main` (instead of importing from `app.main`). +2. Use `fastapi run` to serve your application in the single file `main.py`. -Then adjust the Uvicorn command to use the new module `main` instead of `app.main` to import the FastAPI object `app`. +When you pass the file to `fastapi run` it will detect automatically that it is a single file and not part of a package and will know how to import it and serve your FastAPI app. 😎 ## Deployment Concepts -Let's talk again about some of the same [Deployment Concepts](./concepts.md){.internal-link target=_blank} in terms of containers. +Let's talk again about some of the same [Deployment Concepts](concepts.md){.internal-link target=_blank} in terms of containers. Containers are mainly a tool to simplify the process of **building and deploying** an application, but they don't enforce a particular approach to handle these **deployment concepts**, and there are several possible strategies. @@ -394,8 +436,11 @@ If we focus just on the **container image** for a FastAPI application (and later It could be another container, for example with Traefik, handling **HTTPS** and **automatic** acquisition of **certificates**. -!!! tip - Traefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it. +/// tip + +Traefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it. + +/// Alternatively, HTTPS could be handled by a cloud provider as one of their services (while still running the application in a container). @@ -411,11 +456,11 @@ Without using containers, making applications run on startup and with restarts c ## Replication - Number of Processes -If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Gunicorn with workers) in each container. +If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Uvicorn with workers) in each container. One of those distributed container management systems like Kubernetes normally has some integrated way of handling **replication of containers** while still supporting **load balancing** for the incoming requests. All at the **cluster level**. -In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of running something like Gunicorn with Uvicorn workers. +In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of using multiple Uvicorn workers. ### Load Balancer @@ -423,8 +468,11 @@ When using containers, you would normally have some component **listening on the As this component would take the **load** of requests and distribute that among the workers in a (hopefully) **balanced** way, it is also commonly called a **Load Balancer**. -!!! tip - The same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**. +/// tip + +The same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**. + +/// And when working with containers, the same system you use to start and manage them would already have internal tools to transmit the **network communication** (e.g. HTTP requests) from that **load balancer** (that could also be a **TLS Termination Proxy**) to the container(s) with your app. @@ -442,37 +490,44 @@ And normally this **load balancer** would be able to handle requests that go to In this type of scenario, you probably would want to have **a single (Uvicorn) process per container**, as you would already be handling replication at the cluster level. -So, in this case, you **would not** want to have a process manager like Gunicorn with Uvicorn workers, or Uvicorn using its own Uvicorn workers. You would want to have just a **single Uvicorn process** per container (but probably multiple containers). +So, in this case, you **would not** want to have a multiple workers in the container, for example with the `--workers` command line option.You would want to have just a **single Uvicorn process** per container (but probably multiple containers). -Having another process manager inside the container (as would be with Gunicorn or Uvicorn managing Uvicorn workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system. +Having another process manager inside the container (as would be with multiple workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system. ### Containers with Multiple Processes and Special Cases -Of course, there are **special cases** where you could want to have **a container** with a **Gunicorn process manager** starting several **Uvicorn worker processes** inside. +Of course, there are **special cases** where you could want to have **a container** with several **Uvicorn worker processes** inside. -In those cases, you can use the **official Docker image** that includes **Gunicorn** as a process manager running multiple **Uvicorn worker processes**, and some default settings to adjust the number of workers based on the current CPU cores automatically. I'll tell you more about it below in [Official Docker Image with Gunicorn - Uvicorn](#official-docker-image-with-gunicorn-uvicorn). +In those cases, you can use the `--workers` command line option to set the number of workers that you want to run: -Here are some examples of when that could make sense: +```{ .dockerfile .annotate } +FROM python:3.9 -#### A Simple App +WORKDIR /code -You could want a process manager in the container if your application is **simple enough** that you don't need (at least not yet) to fine-tune the number of processes too much, and you can just use an automated default (with the official Docker image), and you are running it on a **single server**, not a cluster. +COPY ./requirements.txt /code/requirements.txt -#### Docker Compose +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**. +COPY ./app /code/app -Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside. +# (1)! +CMD ["fastapi", "run", "app/main.py", "--port", "80", "--workers", "4"] +``` -#### Prometheus and Other Reasons +1. Here we use the `--workers` command line option to set the number of workers to 4. -You could also have **other reasons** that would make it easier to have a **single container** with **multiple processes** instead of having **multiple containers** with **a single process** in each of them. +Here are some examples of when that could make sense: -For example (depending on your setup) you could have some tool like a Prometheus exporter in the same container that should have access to **each of the requests** that come. +#### A Simple App -In this case, if you had **multiple containers**, by default, when Prometheus came to **read the metrics**, it would get the ones for **a single container each time** (for the container that handled that particular request), instead of getting the **accumulated metrics** for all the replicated containers. +You could want a process manager in the container if your application is **simple enough** that can run it on a **single server**, not a cluster. -Then, in that case, it could be simpler to have **one container** with **multiple processes**, and a local tool (e.g. a Prometheus exporter) on the same container collecting Prometheus metrics for all the internal processes and exposing those metrics on that single container. +#### Docker Compose + +You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**. + +Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside. --- @@ -493,7 +548,7 @@ And then you can set those same memory limits and requirements in your configura If your application is **simple**, this will probably **not be a problem**, and you might not need to specify hard memory limits. But if you are **using a lot of memory** (for example with **machine learning** models), you should check how much memory you are consuming and adjust the **number of containers** that runs in **each machine** (and maybe add more machines to your cluster). -If you run **multiple processes per container** (for example with the official Docker image) you will have to make sure that the number of processes started doesn't **consume more memory** than what is available. +If you run **multiple processes per container** you will have to make sure that the number of processes started doesn't **consume more memory** than what is available. ## Previous Steps Before Starting and Containers @@ -503,80 +558,35 @@ If you are using containers (e.g. Docker, Kubernetes), then there are two main a If you have **multiple containers**, probably each one running a **single process** (for example, in a **Kubernetes** cluster), then you would probably want to have a **separate container** doing the work of the **previous steps** in a single container, running a single process, **before** running the replicated worker containers. -!!! info - If you are using Kubernetes, this would probably be an Init Container. - -If in your use case there's no problem in running those previous steps **multiple times in parallel** (for example if you are not running database migrations, but just checking if the database is ready yet), then you could also just put them in each container right before starting the main process. - -### Single Container - -If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. The official Docker image supports this internally. - -## Official Docker Image with Gunicorn - Uvicorn - -There is an official Docker image that includes Gunicorn running with Uvicorn workers, as detailed in a previous chapter: [Server Workers - Gunicorn with Uvicorn](./server-workers.md){.internal-link target=_blank}. - -This image would be useful mainly in the situations described above in: [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). - -* tiangolo/uvicorn-gunicorn-fastapi. - -!!! warning - There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). - -This image has an **auto-tuning** mechanism included to set the **number of worker processes** based on the CPU cores available. +/// info -It has **sensible defaults**, but you can still change and update all the configurations with **environment variables** or configuration files. +If you are using Kubernetes, this would probably be an Init Container. -It also supports running **previous steps before starting** with a script. +/// -!!! tip - To see all the configurations and options, go to the Docker image page: tiangolo/uvicorn-gunicorn-fastapi. - -### Number of Processes on the Official Docker Image - -The **number of processes** on this image is **computed automatically** from the CPU **cores** available. - -This means that it will try to **squeeze** as much **performance** from the CPU as possible. - -You can also adjust it with the configurations using **environment variables**, etc. - -But it also means that as the number of processes depends on the CPU the container is running, the **amount of memory consumed** will also depend on that. - -So, if your application consumes a lot of memory (for example with machine learning models), and your server has a lot of CPU cores **but little memory**, then your container could end up trying to use more memory than what is available, and degrading performance a lot (or even crashing). 🚨 - -### Create a `Dockerfile` - -Here's how you would create a `Dockerfile` based on this image: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 - -COPY ./requirements.txt /app/requirements.txt +If in your use case there's no problem in running those previous steps **multiple times in parallel** (for example if you are not running database migrations, but just checking if the database is ready yet), then you could also just put them in each container right before starting the main process. -RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt +### Single Container -COPY ./app /app -``` +If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. -### Bigger Applications +### Base Docker Image -If you followed the section about creating [Bigger Applications with Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}, your `Dockerfile` might instead look like: +There used to be an official FastAPI Docker image: tiangolo/uvicorn-gunicorn-fastapi. But it is now deprecated. ⛔️ -```Dockerfile hl_lines="7" -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 +You should probably **not** use this base Docker image (or any other similar one). -COPY ./requirements.txt /app/requirements.txt +If you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). -RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt +And if you need to have multiple workers, you can simply use the `--workers` command line option. -COPY ./app /app/app -``` +/// note | Technical Details -### When to Use +The Docker image was created when Uvicorn didn't support managing and restarting dead workers, so it was needed to use Gunicorn with Uvicorn, which added quite some complexity, just to have Gunicorn manage and restart the Uvicorn worker processes. -You should probably **not** use this official base image (or any other similar one) if you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). +But now that Uvicorn (and the `fastapi` command) support using `--workers`, there's no reason to use a base Docker image instead of building your own (it's pretty much the same amount of code 😅). -This image would be useful mainly in the special cases described above in [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). For example, if your application is **simple enough** that setting a default number of processes based on the CPU works well, you don't want to bother with manually configuring the replication at the cluster level, and you are not running more than one container with your app. Or if you are deploying with **Docker Compose**, running on a single server, etc. +/// ## Deploy the Container Image @@ -590,95 +600,9 @@ For example: * With another tool like Nomad * With a cloud service that takes your container image and deploys it -## Docker Image with Poetry +## Docker Image with `uv` -If you use Poetry to manage your project's dependencies, you could use Docker multi-stage building: - -```{ .dockerfile .annotate } -# (1) -FROM python:3.9 as requirements-stage - -# (2) -WORKDIR /tmp - -# (3) -RUN pip install poetry - -# (4) -COPY ./pyproject.toml ./poetry.lock* /tmp/ - -# (5) -RUN poetry export -f requirements.txt --output requirements.txt --without-hashes - -# (6) -FROM python:3.9 - -# (7) -WORKDIR /code - -# (8) -COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt - -# (9) -RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt - -# (10) -COPY ./app /code/app - -# (11) -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] -``` - -1. This is the first stage, it is named `requirements-stage`. - -2. Set `/tmp` as the current working directory. - - Here's where we will generate the file `requirements.txt` - -3. Install Poetry in this Docker stage. - -4. Copy the `pyproject.toml` and `poetry.lock` files to the `/tmp` directory. - - Because it uses `./poetry.lock*` (ending with a `*`), it won't crash if that file is not available yet. - -5. Generate the `requirements.txt` file. - -6. This is the final stage, anything here will be preserved in the final container image. - -7. Set the current working directory to `/code`. - -8. Copy the `requirements.txt` file to the `/code` directory. - - This file only lives in the previous Docker stage, that's why we use `--from-requirements-stage` to copy it. - -9. Install the package dependencies in the generated `requirements.txt` file. - -10. Copy the `app` directory to the `/code` directory. - -11. Run the `uvicorn` command, telling it to use the `app` object imported from `app.main`. - -!!! tip - Click the bubble numbers to see what each line does. - -A **Docker stage** is a part of a `Dockerfile` that works as a **temporary container image** that is only used to generate some files to be used later. - -The first stage will only be used to **install Poetry** and to **generate the `requirements.txt`** with your project dependencies from Poetry's `pyproject.toml` file. - -This `requirements.txt` file will be used with `pip` later in the **next stage**. - -In the final container image **only the final stage** is preserved. The previous stage(s) will be discarded. - -When using Poetry, it would make sense to use **Docker multi-stage builds** because you don't really need to have Poetry and its dependencies installed in the final container image, you **only need** to have the generated `requirements.txt` file to install your project dependencies. - -Then in the next (and final) stage you would build the image more or less in the same way as described before. - -### Behind a TLS Termination Proxy - Poetry - -Again, if you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers` to the command: - -```Dockerfile -CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] -``` +If you are using uv to install and manage your project, you can follow their uv Docker guide. ## Recap @@ -691,8 +615,6 @@ Using container systems (e.g. with **Docker** and **Kubernetes**) it becomes fai * Memory * Previous steps before starting -In most cases, you probably won't want to use any base image, and instead **build a container image from scratch** one based on the official Python Docker image. +In most cases, you probably won't want to use any base image, and instead **build a container image from scratch** based on the official Python Docker image. Taking care of the **order** of instructions in the `Dockerfile` and the **Docker cache** you can **minimize build times**, to maximize your productivity (and avoid boredom). 😎 - -In certain special cases, you might want to use the official Docker image for FastAPI. 🤓 diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md index 5cf76c111..46eda791e 100644 --- a/docs/en/docs/deployment/https.md +++ b/docs/en/docs/deployment/https.md @@ -4,8 +4,11 @@ It is easy to assume that HTTPS is something that is just "enabled" or not. But it is way more complex than that. -!!! tip - If you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques. +/// tip + +If you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques. + +/// To **learn the basics of HTTPS**, from a consumer perspective, check https://howhttps.works/. @@ -68,8 +71,11 @@ In the DNS server(s) you would configure a record (an "`A record`") to point **y You would probably do this just once, the first time, when setting everything up. -!!! tip - This Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here. +/// tip + +This Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here. + +/// ### DNS @@ -115,8 +121,11 @@ After this, the client and the server have an **encrypted TCP connection**, this And that's what **HTTPS** is, it's just plain **HTTP** inside a **secure TLS connection** instead of a pure (unencrypted) TCP connection. -!!! tip - Notice that the encryption of the communication happens at the **TCP level**, not at the HTTP level. +/// tip + +Notice that the encryption of the communication happens at the **TCP level**, not at the HTTP level. + +/// ### HTTPS Request diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index b10a3686d..3f7c7a008 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -1,133 +1,157 @@ -# Run a Server Manually - Uvicorn +# Run a Server Manually -The main thing you need to run a **FastAPI** application in a remote server machine is an ASGI server program like **Uvicorn**. +## Use the `fastapi run` Command -There are 3 main alternatives: +In short, use `fastapi run` to serve your FastAPI application: -* Uvicorn: a high performance ASGI server. -* Hypercorn: an ASGI server compatible with HTTP/2 and Trio among other features. -* Daphne: the ASGI server built for Django Channels. - -## Server Machine and Server Program - -There's a small detail about names to keep in mind. 💡 - -The word "**server**" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn). - -Just keep in mind that when you read "server" in general, it could refer to one of those two things. +
-When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs. +```console +$ fastapi run main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭─────────── FastAPI CLI - Production mode ───────────╮ + │ │ + │ Serving at: http://0.0.0.0:8000 │ + │ │ + │ API docs: http://0.0.0.0:8000/docs │ + │ │ + │ Running in production mode, for development use: │ + │ │ + fastapi dev + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Started server process [2306215] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +``` -## Install the Server Program +
-You can install an ASGI compatible server with: +That would work for most of the cases. 😎 -=== "Uvicorn" +You could use that command for example to start your **FastAPI** app in a container, in a server, etc. - * Uvicorn, a lightning-fast ASGI server, built on uvloop and httptools. +## ASGI Servers -
+Let's go a little deeper into the details. - ```console - $ pip install "uvicorn[standard]" +FastAPI uses a standard for building Python web frameworks and servers called ASGI. FastAPI is an ASGI web framework. - ---> 100% - ``` +The main thing you need to run a **FastAPI** application (or any other ASGI application) in a remote server machine is an ASGI server program like **Uvicorn**, this is the one that comes by default in the `fastapi` command. -
+There are several alternatives, including: - !!! tip - By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. +* Uvicorn: a high performance ASGI server. +* Hypercorn: an ASGI server compatible with HTTP/2 and Trio among other features. +* Daphne: the ASGI server built for Django Channels. +* Granian: A Rust HTTP server for Python applications. +* NGINX Unit: NGINX Unit is a lightweight and versatile web application runtime. - That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. +## Server Machine and Server Program -=== "Hypercorn" +There's a small detail about names to keep in mind. 💡 - * Hypercorn, an ASGI server also compatible with HTTP/2. +The word "**server**" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn). -
+Just keep in mind that when you read "server" in general, it could refer to one of those two things. - ```console - $ pip install hypercorn +When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs. - ---> 100% - ``` +## Install the Server Program -
+When you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command. - ...or any other ASGI server. +But you can also install an ASGI server manually. -## Run the Server Program +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server application. -You can then run your application the same way you have done in the tutorials, but without the `--reload` option, e.g.: +For example, to install Uvicorn: -=== "Uvicorn" +
-
+```console +$ pip install "uvicorn[standard]" - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +---> 100% +``` - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +
-
+A similar process would apply to any other ASGI server program. -=== "Hypercorn" +/// tip -
+By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well. -
+/// -!!! warning - Remember to remove the `--reload` option if you were using it. +## Run the Server Program - The `--reload` option consumes much more resources, is more unstable, etc. +If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application: - It helps a lot during **development**, but you **shouldn't** use it in **production**. +
-## Hypercorn with Trio +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 -Starlette and **FastAPI** are based on AnyIO, which makes them compatible with both Python's standard library asyncio and Trio. +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -Nevertheless, Uvicorn is currently only compatible with asyncio, and it normally uses `uvloop`, the high-performance drop-in replacement for `asyncio`. +
-But if you want to directly use **Trio**, then you can use **Hypercorn** as it supports it. ✨ +/// note -### Install Hypercorn with Trio +The command `uvicorn main:app` refers to: -First you need to install Hypercorn with Trio support: +* `main`: the file `main.py` (the Python "module"). +* `app`: the object created inside of `main.py` with the line `app = FastAPI()`. -
+It is equivalent to: -```console -$ pip install "hypercorn[trio]" ----> 100% +```Python +from main import app ``` -
+/// -### Run with Trio +Each alternative ASGI server program would have a similar command, you can read more in their respective documentation. -Then you can pass the command line option `--worker-class` with the value `trio`: +/// warning -
+Uvicorn and other servers support a `--reload` option that is useful during development. -```console -$ hypercorn main:app --worker-class trio -``` - -
+The `--reload` option consumes much more resources, is more unstable, etc. -And that will start Hypercorn with your app using Trio as the backend. +It helps a lot during **development**, but you **shouldn't** use it in **production**. -Now you can use Trio internally in your app. Or even better, you can use AnyIO, to keep your code compatible with both Trio and asyncio. 🎉 +/// ## Deployment Concepts diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 2df9f3d43..622c10a30 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -1,4 +1,4 @@ -# Server Workers - Gunicorn with Uvicorn +# Server Workers - Uvicorn with Workers Let's check back those deployment concepts from before: @@ -9,120 +9,92 @@ Let's check back those deployment concepts from before: * Memory * Previous steps before starting -Up to this point, with all the tutorials in the docs, you have probably been running a **server program** like Uvicorn, running a **single process**. +Up to this point, with all the tutorials in the docs, you have probably been running a **server program**, for example, using the `fastapi` command, that runs Uvicorn, running a **single process**. When deploying applications you will probably want to have some **replication of processes** to take advantage of **multiple cores** and to be able to handle more requests. -As you saw in the previous chapter about [Deployment Concepts](./concepts.md){.internal-link target=_blank}, there are multiple strategies you can use. +As you saw in the previous chapter about [Deployment Concepts](concepts.md){.internal-link target=_blank}, there are multiple strategies you can use. -Here I'll show you how to use **Gunicorn** with **Uvicorn worker processes**. +Here I'll show you how to use **Uvicorn** with **worker processes** using the `fastapi` command or the `uvicorn` command directly. -!!! info - If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank}. +/// info - In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. +If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. -## Gunicorn with Uvicorn Workers +In particular, when running on **Kubernetes** you will probably **not** want to use workers and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. -**Gunicorn** is mainly an application server using the **WSGI standard**. That means that Gunicorn can serve applications like Flask and Django. Gunicorn by itself is not compatible with **FastAPI**, as FastAPI uses the newest **ASGI standard**. +/// -But Gunicorn supports working as a **process manager** and allowing users to tell it which specific **worker process class** to use. Then Gunicorn would start one or more **worker processes** using that class. +## Multiple Workers -And **Uvicorn** has a **Gunicorn-compatible worker class**. +You can start multiple workers with the `--workers` command line option: -Using that combination, Gunicorn would act as a **process manager**, listening on the **port** and the **IP**. And it would **transmit** the communication to the worker processes running the **Uvicorn class**. +//// tab | `fastapi` -And then the Gunicorn-compatible **Uvicorn worker** class would be in charge of converting the data sent by Gunicorn to the ASGI standard for FastAPI to use it. - -## Install Gunicorn and Uvicorn - -
- -```console -$ pip install "uvicorn[standard]" gunicorn - ----> 100% -``` - -
- -That will install both Uvicorn with the `standard` extra packages (to get high performance) and Gunicorn. - -## Run Gunicorn with Uvicorn Workers - -Then you can run Gunicorn with: +If you use the `fastapi` command:
```console -$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 - -[19499] [INFO] Starting gunicorn 20.1.0 -[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) -[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker -[19511] [INFO] Booting worker with pid: 19511 -[19513] [INFO] Booting worker with pid: 19513 -[19514] [INFO] Booting worker with pid: 19514 -[19515] [INFO] Booting worker with pid: 19515 -[19511] [INFO] Started server process [19511] -[19511] [INFO] Waiting for application startup. -[19511] [INFO] Application startup complete. -[19513] [INFO] Started server process [19513] -[19513] [INFO] Waiting for application startup. -[19513] [INFO] Application startup complete. -[19514] [INFO] Started server process [19514] -[19514] [INFO] Waiting for application startup. -[19514] [INFO] Application startup complete. -[19515] [INFO] Started server process [19515] -[19515] [INFO] Waiting for application startup. -[19515] [INFO] Application startup complete. +$
 fastapi run --workers 4 main.py
+INFO     Using path main.py
+INFO     Resolved absolute path /home/user/code/awesomeapp/main.py
+INFO     Searching for package file structure from directories with __init__.py files
+INFO     Importing from /home/user/code/awesomeapp
+
+ ╭─ Python module file ─╮
+ │                      │
+ │  🐍 main.py          │
+ │                      │
+ ╰──────────────────────╯
+
+INFO     Importing module main
+INFO     Found importable FastAPI app
+
+ ╭─ Importable FastAPI app ─╮
+ │                          │
+ │  from main import app    │
+ │                          │
+ ╰──────────────────────────╯
+
+INFO     Using import string main:app
+
+ ╭─────────── FastAPI CLI - Production mode ───────────╮
+ │                                                     │
+ │  Serving at: http://0.0.0.0:8000                    │
+ │                                                     │
+ │  API docs: http://0.0.0.0:8000/docs                 │
+ │                                                     │
+ │  Running in production mode, for development use:   │
+ │                                                     │
+ fastapi dev
+ │                                                     │
+ ╰─────────────────────────────────────────────────────╯
+
+INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
+INFO:     Started parent process [27365]
+INFO:     Started server process [27368]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27369]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27370]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27367]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+
```
-Let's see what each of those options mean: - -* `main:app`: This is the same syntax used by Uvicorn, `main` means the Python module named "`main`", so, a file `main.py`. And `app` is the name of the variable that is the **FastAPI** application. - * You can imagine that `main:app` is equivalent to a Python `import` statement like: - - ```Python - from main import app - ``` +//// - * So, the colon in `main:app` would be equivalent to the Python `import` part in `from main import app`. +//// tab | `uvicorn` -* `--workers`: The number of worker processes to use, each will run a Uvicorn worker, in this case, 4 workers. - -* `--worker-class`: The Gunicorn-compatible worker class to use in the worker processes. - * Here we pass the class that Gunicorn can import and use with: - - ```Python - import uvicorn.workers.UvicornWorker - ``` - -* `--bind`: This tells Gunicorn the IP and the port to listen to, using a colon (`:`) to separate the IP and the port. - * If you were running Uvicorn directly, instead of `--bind 0.0.0.0:80` (the Gunicorn option) you would use `--host 0.0.0.0` and `--port 80`. - -In the output, you can see that it shows the **PID** (process ID) of each process (it's just a number). - -You can see that: - -* The Gunicorn **process manager** starts with PID `19499` (in your case it will be a different number). -* Then it starts `Listening at: http://0.0.0.0:80`. -* Then it detects that it has to use the worker class at `uvicorn.workers.UvicornWorker`. -* And then it starts **4 workers**, each with its own PID: `19511`, `19513`, `19514`, and `19515`. - -Gunicorn would also take care of managing **dead processes** and **restarting** new ones if needed to keep the number of workers. So that helps in part with the **restart** concept from the list above. - -Nevertheless, you would probably also want to have something outside making sure to **restart Gunicorn** if necessary, and also to **run it on startup**, etc. - -## Uvicorn with Workers - -Uvicorn also has an option to start and run several **worker processes**. - -Nevertheless, as of now, Uvicorn's capabilities for handling worker processes are more limited than Gunicorn's. So, if you want to have a process manager at this level (at the Python level), then it might be better to try with Gunicorn as the process manager. - -In any case, you would run it like this: +If you prefer to use the `uvicorn` command directly:
@@ -146,13 +118,15 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
+//// + The only new option here is `--workers` telling Uvicorn to start 4 worker processes. You can also see that it shows the **PID** of each process, `27365` for the parent process (this is the **process manager**) and one for each worker process: `27368`, `27369`, `27370`, and `27367`. ## Deployment Concepts -Here you saw how to use **Gunicorn** (or Uvicorn) managing **Uvicorn worker processes** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**. +Here you saw how to use multiple **workers** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**. From the list of deployment concepts from above, using workers would mainly help with the **replication** part, and a little bit with the **restarts**, but you still need to take care of the others: @@ -165,15 +139,13 @@ From the list of deployment concepts from above, using workers would mainly help ## Containers and Docker -In the next chapter about [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**. - -I'll also show you the **official Docker image** that includes **Gunicorn with Uvicorn workers** and some default configurations that can be useful for simple cases. +In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll explain some strategies you could use to handle the other **deployment concepts**. -There I'll also show you how to **build your own image from scratch** to run a single Uvicorn process (without Gunicorn). It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. +I'll show you how to **build your own image from scratch** to run a single Uvicorn process. It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. ## Recap -You can use **Gunicorn** (or also Uvicorn) as a process manager with Uvicorn workers to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**. +You can use multiple worker processes with the `--workers` CLI option with the `fastapi` or `uvicorn` commands to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**. You could use these tools and ideas if you are setting up **your own deployment system** while taking care of the other deployment concepts yourself. diff --git a/docs/en/docs/deployment/versions.md b/docs/en/docs/deployment/versions.md index 4be9385dd..23f49cf99 100644 --- a/docs/en/docs/deployment/versions.md +++ b/docs/en/docs/deployment/versions.md @@ -12,25 +12,25 @@ You can create production applications with **FastAPI** right now (and you have The first thing you should do is to "pin" the version of **FastAPI** you are using to the specific latest version that you know works correctly for your application. -For example, let's say you are using version `0.45.0` in your app. +For example, let's say you are using version `0.112.0` in your app. If you use a `requirements.txt` file you could specify the version with: ```txt -fastapi==0.45.0 +fastapi[standard]==0.112.0 ``` -that would mean that you would use exactly the version `0.45.0`. +that would mean that you would use exactly the version `0.112.0`. Or you could also pin it with: ```txt -fastapi>=0.45.0,<0.46.0 +fastapi[standard]>=0.112.0,<0.113.0 ``` -that would mean that you would use the versions `0.45.0` or above, but less than `0.46.0`, for example, a version `0.45.2` would still be accepted. +that would mean that you would use the versions `0.112.0` or above, but less than `0.113.0`, for example, a version `0.112.2` would still be accepted. -If you use any other tool to manage your installations, like Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. +If you use any other tool to manage your installations, like `uv`, Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. ## Available versions @@ -42,8 +42,11 @@ Following the Semantic Versioning conventions, any version below `1.0.0` could p FastAPI also follows the convention that any "PATCH" version change is for bug fixes and non-breaking changes. -!!! tip - The "PATCH" is the last number, for example, in `0.2.3`, the PATCH version is `3`. +/// tip + +The "PATCH" is the last number, for example, in `0.2.3`, the PATCH version is `3`. + +/// So, you should be able to pin to a version like: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Breaking changes and new features are added in "MINOR" versions. -!!! tip - The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`. +/// tip + +The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`. + +/// ## Upgrading the FastAPI versions @@ -78,10 +84,10 @@ So, you can just let **FastAPI** use the correct Starlette version. Pydantic includes the tests for **FastAPI** with its own tests, so new versions of Pydantic (above `1.0.0`) are always compatible with FastAPI. -You can pin Pydantic to any version above `1.0.0` that works for you and below `2.0.0`. +You can pin Pydantic to any version above `1.0.0` that works for you. For example: ```txt -pydantic>=1.2.0,<2.0.0 +pydantic>=2.7.0,<3.0.0 ``` diff --git a/docs/en/docs/environment-variables.md b/docs/en/docs/environment-variables.md new file mode 100644 index 000000000..43dd06add --- /dev/null +++ b/docs/en/docs/environment-variables.md @@ -0,0 +1,298 @@ +# Environment Variables + +/// tip + +If you already know what "environment variables" are and how to use them, feel free to skip this. + +/// + +An environment variable (also known as "**env var**") is a variable that lives **outside** of the Python code, in the **operating system**, and could be read by your Python code (or by other programs as well). + +Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc. + +## Create and Use Env Vars + +You can **create** and use environment variables in the **shell (terminal)**, without needing Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" + +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Read env vars in Python + +You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**. + +For example you could have a file `main.py` with: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +The second argument to `os.getenv()` is the default value to return. + +If not provided, it's `None` by default, here we provide `"World"` as the default value to use. + +/// + +Then you could call that Python program: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ $Env:MY_NAME = "Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or **settings**. + +You can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration. + +To do that, create it right before the program itself, on the same line: + +
+ +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +You can read more about it at The Twelve-Factor App: Config. + +/// + +## Types and Validation + +These environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). + +That means that **any value** read in Python from an environment variable **will be a `str`**, and any conversion to a different type or any validation has to be done in code. + +You will learn more about using environment variables for handling **application settings** in the [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}. + +## `PATH` Environment Variable + +There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run. + +The value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows. + +For example, the `PATH` environment variable could look like this: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +This means that the system should look for programs in the directories: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +This means that the system should look for programs in the directories: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +When you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable. + +For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list. + +If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**. + +### Installing Python and Updating the `PATH` + +When you install Python, you might be asked if you want to update the `PATH` environment variable. + +//// tab | Linux, macOS + +Let's say you install Python and it ends up in a directory `/opt/custompython/bin`. + +If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable. + +It could look like this: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one. + +//// + +//// tab | Windows + +Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`. + +If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +This way, when you type `python` in the terminal, the system will find the Python program in `C:\opt\custompython\bin` (the last directory) and use that one. + +//// + +So, if you type: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +The system will **find** the `python` program in `/opt/custompython/bin` and run it. + +It would be roughly equivalent to typing: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it. + +It would be roughly equivalent to typing: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +This information will be useful when learning about [Virtual Environments](virtual-environments.md){.internal-link target=_blank}. + +## Conclusion + +With this you should have a basic understanding of what **environment variables** are and how to use them in Python. + +You can also read more about them in the Wikipedia for Environment Variable. + +In many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them. + +For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md). diff --git a/docs/en/docs/external-links.md b/docs/en/docs/external-links.md index b89021ee2..5a3b8ee33 100644 --- a/docs/en/docs/external-links.md +++ b/docs/en/docs/external-links.md @@ -6,8 +6,11 @@ There are many posts, articles, tools, and projects, related to **FastAPI**. Here's an incomplete list of some of them. -!!! tip - If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a Pull Request adding it. +/// tip + +If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a Pull Request adding it. + +/// {% for section_name, section_content in external_links.items() %} diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md new file mode 100644 index 000000000..e27bebcb4 --- /dev/null +++ b/docs/en/docs/fastapi-cli.md @@ -0,0 +1,83 @@ +# FastAPI CLI + +**FastAPI CLI** is a command line program that you can use to serve your FastAPI app, manage your FastAPI project, and more. + +When you install FastAPI (e.g. with `pip install "fastapi[standard]"`), it includes a package called `fastapi-cli`, this package provides the `fastapi` command in the terminal. + +To run your FastAPI app for development, you can use the `fastapi dev` command: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +The command line program called `fastapi` is **FastAPI CLI**. + +FastAPI CLI takes the path to your Python program (e.g. `main.py`) and automatically detects the `FastAPI` instance (commonly named `app`), determines the correct import process, and then serves it. + +For production you would use `fastapi run` instead. 🚀 + +Internally, **FastAPI CLI** uses Uvicorn, a high-performance, production-ready, ASGI server. 😎 + +## `fastapi dev` + +Running `fastapi dev` initiates development mode. + +By default, **auto-reload** is enabled, automatically reloading the server when you make changes to your code. This is resource-intensive and could be less stable than when it's disabled. You should only use it for development. It also listens on the IP address `127.0.0.1`, which is the IP for your machine to communicate with itself alone (`localhost`). + +## `fastapi run` + +Executing `fastapi run` starts FastAPI in production mode by default. + +By default, **auto-reload** is disabled. It also listens on the IP address `0.0.0.0`, which means all the available IP addresses, this way it will be publicly accessible to anyone that can communicate with the machine. This is how you would normally run it in production, for example, in a container. + +In most cases you would (and should) have a "termination proxy" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself. + +/// tip + +You can learn more about it in the [deployment documentation](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md index 2bd01ba43..bf7954449 100644 --- a/docs/en/docs/fastapi-people.md +++ b/docs/en/docs/fastapi-people.md @@ -36,19 +36,41 @@ These are the people that: * [Help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. * [Create Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. * Review Pull Requests, [especially important for translations](contributing.md#translations){.internal-link target=_blank}. +* Help [manage the repository](management-tasks.md){.internal-link target=_blank} (team members). + +All these tasks help maintain the repository. A round of applause to them. 👏 🙇 +## Team + +This is the current list of team members. 😎 + +They have different levels of involvement and permissions, they can perform [repository management tasks](./management-tasks.md){.internal-link target=_blank} and together we [manage the FastAPI repository](./management.md){.internal-link target=_blank}. + +
+{% for user in members["members"] %} + + +{% endfor %} + +
+ +Although the team members have the permissions to perform privileged tasks, all the [help from others maintaining FastAPI](./help-fastapi.md#help-maintain-fastapi){.internal-link target=_blank} is very much appreciated! 🙇‍♂️ + ## FastAPI Experts These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🙇 They have proven to be **FastAPI Experts** by helping many others. ✨ -!!! tip - You could become an official FastAPI Expert too! +/// tip + +You could become an official FastAPI Expert too! + +Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓 - Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓 +/// You can see the **FastAPI Experts** for: @@ -148,7 +170,7 @@ They have contributed source code, documentation, translations, etc. 📦
{% endif %} -There are many other contributors (more than a hundred), you can see them all in the FastAPI GitHub Contributors page. 👷 +There are many other contributors (more than a hundred), you can see them all in the FastAPI GitHub Contributors page. 👷 ## Top Translation Reviewers @@ -229,7 +251,7 @@ The main intention of this page is to highlight the effort of the community to h Especially including efforts that are normally less visible, and in many cases more arduous, like helping others with questions and reviewing Pull Requests with translations. -The data is calculated each month, you can read the source code here. +The data is calculated each month, you can read the source code here. Here I'm also highlighting contributions from sponsors. diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md index 6f0e74b3d..9c38a4bd2 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Features ## FastAPI features @@ -11,7 +6,7 @@ hide: ### Based on open standards -* OpenAPI for API creation, including declarations of path operations, parameters, body requests, security, etc. +* OpenAPI for API creation, including declarations of path operations, parameters, request bodies, security, etc. * Automatic data model documentation with JSON Schema (as OpenAPI itself is based on JSON Schema). * Designed around these standards, after a meticulous study. Instead of an afterthought layer on top. * This also allows using automatic **client code generation** in many languages. @@ -30,7 +25,7 @@ Interactive API documentation and exploration web user interfaces. As the framew ### Just Modern Python -It's all based on standard **Python 3.6 type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python. +It's all based on standard **Python type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python. If you need a 2 minute refresher of how to use Python types (even if you don't use FastAPI), check the short tutorial: [Python Types](python-types.md){.internal-link target=_blank}. @@ -68,16 +63,19 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` means: +/// info + +`**second_user_data` means: + +Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")` - Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")` +/// ### Editor support All the framework was designed to be easy and intuitive to use, all the decisions were tested on multiple editors even before starting development, to ensure the best development experience. -In the last Python developer survey it was clear that the most used feature is "autocompletion". +In the Python developer surveys, it's clear that one of the most used features is "autocompletion". The whole **FastAPI** framework is based to satisfy that. Autocompletion works everywhere. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index 1d76aca5e..81151032f 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -26,13 +26,13 @@ You can subscribe to the (infrequent) [**FastAPI and friends** newsletter](newsl ## Star **FastAPI** in GitHub -You can "star" FastAPI in GitHub (clicking the star button at the top right): https://github.com/tiangolo/fastapi. ⭐️ +You can "star" FastAPI in GitHub (clicking the star button at the top right): https://github.com/fastapi/fastapi. ⭐️ By adding a star, other users will be able to find it more easily and see that it has been already useful for others. ## Watch the GitHub repository for releases -You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/tiangolo/fastapi. 👀 +You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/fastapi/fastapi. 👀 There you can select "Releases only". @@ -51,7 +51,7 @@ You can: * Tell me how you use FastAPI (I love to hear that). * Hear when I make announcements or release new tools. * You can also follow @fastapi on Twitter (a separate account). -* Follow me on **Linkedin**. +* Follow me on **LinkedIn**. * Hear when I make announcements or release new tools (although I use Twitter more often 🤷‍♂). * Read what I write (or follow me) on **Dev.to** or **Medium**. * Read other ideas, articles, and read about tools I have created. @@ -59,26 +59,26 @@ You can: ## Tweet about **FastAPI** -Tweet about **FastAPI** and let me and others know why you like it. 🎉 +Tweet about **FastAPI** and let me and others know why you like it. 🎉 I love to hear about how **FastAPI** is being used, what you have liked in it, in which project/company are you using it, etc. ## Vote for FastAPI * Vote for **FastAPI** in Slant. -* Vote for **FastAPI** in AlternativeTo. +* Vote for **FastAPI** in AlternativeTo. * Say you use **FastAPI** on StackShare. ## Help others with questions in GitHub You can try and help others with their questions in: -* GitHub Discussions -* GitHub Issues +* GitHub Discussions +* GitHub Issues In many cases you might already know the answer for those questions. 🤓 -If you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}. 🎉 +If you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. 🎉 Just remember, the most important point is: try to be kind. People come with their frustrations and in many cases don't ask in the best way, but try as best as you can to be kind. 🤗 @@ -125,7 +125,7 @@ If they reply, there's a high chance you would have solved their problem, congra ## Watch the GitHub repository -You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/tiangolo/fastapi. 👀 +You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/fastapi/fastapi. 👀 If you select "Watching" instead of "Releases only" you will receive notifications when someone creates a new issue or question. You can also specify that you only want to be notified about new issues, or discussions, or PRs, etc. @@ -133,7 +133,7 @@ Then you can try and help them solve those questions. ## Ask Questions -You can create a new question in the GitHub repository, for example to: +You can create a new question in the GitHub repository, for example to: * Ask a **question** or ask about a **problem**. * Suggest a new **feature**. @@ -170,12 +170,15 @@ And if there's any other style or consistency need, I'll ask directly for that, * Then **comment** saying that you did that, that's how I will know you really checked it. -!!! info - Unfortunately, I can't simply trust PRs that just have several approvals. +/// info - Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅 +Unfortunately, I can't simply trust PRs that just have several approvals. - So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓 +Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅 + +So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓 + +/// * If the PR can be simplified in a way, you can ask for that, but there's no need to be too picky, there might be a lot of subjective points of view (and I will have my own as well 🙈), so it's better if you can focus on the fundamental things. @@ -196,7 +199,7 @@ And if there's any other style or consistency need, I'll ask directly for that, You can [contribute](contributing.md){.internal-link target=_blank} to the source code with Pull Requests, for example: * To fix a typo you found on the documentation. -* To share an article, video, or podcast you created or found about FastAPI by editing this file. +* To share an article, video, or podcast you created or found about FastAPI by editing this file. * Make sure you add your link to the start of the corresponding section. * To help [translate the documentation](contributing.md#translations){.internal-link target=_blank} to your language. * You can also help to review the translations created by others. @@ -226,10 +229,13 @@ If you can help me with that, **you are helping me maintain FastAPI** and making Join the 👥 Discord chat server 👥 and hang out with others in the FastAPI community. -!!! tip - For questions, ask them in GitHub Discussions, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#experts){.internal-link target=_blank}. +/// tip + +For questions, ask them in GitHub Discussions, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + +Use the chat only for other general conversations. - Use the chat only for other general conversations. +/// ### Don't use the chat for questions @@ -237,7 +243,7 @@ Keep in mind that as chats allow more "free conversation", it's easy to ask ques In GitHub, the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the chat systems. 😅 -Conversations in the chat systems are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation. And only the ones in GitHub count to become a [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}, so you will most probably receive more attention in GitHub. +Conversations in the chat systems are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation. And only the ones in GitHub count to become a [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}, so you will most probably receive more attention in GitHub. On the other side, there are thousands of users in the chat systems, so there's a high chance you'll find someone to talk to there, almost all the time. 😄 diff --git a/docs/en/docs/help/index.md b/docs/en/docs/help/index.md deleted file mode 100644 index 5ee7df2fe..000000000 --- a/docs/en/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Help - -Help and get help, contribute, get involved. 🤝 diff --git a/docs/en/docs/history-design-future.md b/docs/en/docs/history-design-future.md index 7824fb080..b4a744d64 100644 --- a/docs/en/docs/history-design-future.md +++ b/docs/en/docs/history-design-future.md @@ -1,6 +1,6 @@ # History, Design and Future -Some time ago, a **FastAPI** user asked: +Some time ago, a **FastAPI** user asked: > What’s the history of this project? It seems to have come from nowhere to awesome in a few weeks [...] diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md deleted file mode 100644 index c7b340d67..000000000 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ /dev/null @@ -1,177 +0,0 @@ -# ~~Async SQL (Relational) Databases with Encode/Databases~~ (deprecated) - -!!! info - These docs are about to be updated. 🎉 - - The current version assumes Pydantic v1. - - The new docs will include Pydantic v2 and will use SQLModel once it is updated to use Pydantic v2 as well. - -!!! warning "Deprecated" - This tutorial is deprecated and will be removed in a future version. - -You can also use `encode/databases` with **FastAPI** to connect to databases using `async` and `await`. - -It is compatible with: - -* PostgreSQL -* MySQL -* SQLite - -In this example, we'll use **SQLite**, because it uses a single file and Python has integrated support. So, you can copy this example and run it as is. - -Later, for your production application, you might want to use a database server like **PostgreSQL**. - -!!! tip - You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code. - - This section doesn't apply those ideas, to be equivalent to the counterpart in Starlette. - -## Import and set up `SQLAlchemy` - -* Import `SQLAlchemy`. -* Create a `metadata` object. -* Create a table `notes` using the `metadata` object. - -```Python hl_lines="4 14 16-22" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip - Notice that all this code is pure SQLAlchemy Core. - - `databases` is not doing anything here yet. - -## Import and set up `databases` - -* Import `databases`. -* Create a `DATABASE_URL`. -* Create a `database` object. - -```Python hl_lines="3 9 12" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip - If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`. - -## Create the tables - -In this case, we are creating the tables in the same Python file, but in production, you would probably want to create them with Alembic, integrated with migrations, etc. - -Here, this section would run directly, right before starting your **FastAPI** application. - -* Create an `engine`. -* Create all the tables from the `metadata` object. - -```Python hl_lines="25-28" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## Create models - -Create Pydantic models for: - -* Notes to be created (`NoteIn`). -* Notes to be returned (`Note`). - -```Python hl_lines="31-33 36-39" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -By creating these Pydantic models, the input data will be validated, serialized (converted), and annotated (documented). - -So, you will be able to see it all in the interactive API docs. - -## Connect and disconnect - -* Create your `FastAPI` application. -* Create event handlers to connect and disconnect from the database. - -```Python hl_lines="42 45-47 50-52" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## Read notes - -Create the *path operation function* to read notes: - -```Python hl_lines="55-58" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! Note - Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. - -### Notice the `response_model=List[Note]` - -It uses `typing.List`. - -That documents (and validates, serializes, filters) the output data, as a `list` of `Note`s. - -## Create notes - -Create the *path operation function* to create notes: - -```Python hl_lines="61-65" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. - - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. - -!!! Note - Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. - -### About `{**note.dict(), "id": last_record_id}` - -`note` is a Pydantic `Note` object. - -`note.dict()` returns a `dict` with its data, something like: - -```Python -{ - "text": "Some note", - "completed": False, -} -``` - -but it doesn't have the `id` field. - -So we create a new `dict`, that contains the key-value pairs from `note.dict()` with: - -```Python -{**note.dict()} -``` - -`**note.dict()` "unpacks" the key value pairs directly, so, `{**note.dict()}` would be, more or less, a copy of `note.dict()`. - -And then, we extend that copy `dict`, adding another key-value pair: `"id": last_record_id`: - -```Python -{**note.dict(), "id": last_record_id} -``` - -So, the final result returned would be something like: - -```Python -{ - "id": 1, - "text": "Some note", - "completed": False, -} -``` - -## Check it - -You can copy this code as is, and see the docs at http://127.0.0.1:8000/docs. - -There you can see all your API documented and interact with it: - - - -## More info - -You can read more about `encode/databases` at its GitHub page. diff --git a/docs/en/docs/how-to/conditional-openapi.md b/docs/en/docs/how-to/conditional-openapi.md index add16fbec..bd6cad9a8 100644 --- a/docs/en/docs/how-to/conditional-openapi.md +++ b/docs/en/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ You can easily use the same Pydantic settings to configure your generated OpenAP For example: -```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`. diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md index f36ba5ba8..a8a8de48f 100644 --- a/docs/en/docs/how-to/configure-swagger-ui.md +++ b/docs/en/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # Configure Swagger UI -You can configure some extra Swagger UI parameters. +You can configure some extra Swagger UI parameters. To configure them, pass the `swagger_ui_parameters` argument when creating the `FastAPI()` app object or to the `get_swagger_ui_html()` function. @@ -18,9 +18,7 @@ Without changing the settings, syntax highlighting is enabled by default: But you can disable it by setting `syntaxHighlight` to `False`: -```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ...and then Swagger UI won't show the syntax highlighting anymore: @@ -30,9 +28,7 @@ But you can disable it by setting `syntaxHighlight` to `False`: The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle): -```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} That configuration would change the syntax highlighting color theme: @@ -44,21 +40,17 @@ FastAPI includes some default configuration parameters appropriate for most of t It includes these default configurations: -```Python -{!../../../fastapi/openapi/docs.py[ln:7-13]!} -``` +{* ../../fastapi/openapi/docs.py ln[8:23] hl[17:23] *} You can override any of them by setting a different value in the argument `swagger_ui_parameters`. For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`: -```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## Other Swagger UI Parameters -To see all the other possible configurations you can use, read the official docs for Swagger UI parameters. +To see all the other possible configurations you can use, read the official docs for Swagger UI parameters. ## JavaScript-only settings diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md index 9726be2c7..f717c98fa 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -18,15 +18,13 @@ The first step is to disable the automatic docs, as by default, those use the de To disable them, set their URLs to `None` when creating your `FastAPI` app: -```Python hl_lines="8" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} ### Include the custom docs Now you can create the *path operations* for the custom docs. -You can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: +You can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: * `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`. * `title`: the title of your API. @@ -36,24 +34,23 @@ You can re-use FastAPI's internal functions to create the HTML pages for the doc And similarly for ReDoc... -```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} + +/// tip -!!! tip - The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. +The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. - If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. +If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. - Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. +Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. + +/// ### Create a *path operation* to test it Now, to be able to test that everything works, create a *path operation*: -```Python hl_lines="36-38" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} ### Test it @@ -96,8 +93,8 @@ You can probably right-click each link and select an option similar to `Save lin **Swagger UI** uses the files: -* `swagger-ui-bundle.js` -* `swagger-ui.css` +* `swagger-ui-bundle.js` +* `swagger-ui.css` And **ReDoc** uses the file: @@ -121,9 +118,7 @@ After that, your file structure could look like: * Import `StaticFiles`. * "Mount" a `StaticFiles()` instance in a specific path. -```Python hl_lines="7 11" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} ### Test the static files @@ -155,15 +150,13 @@ The same as when using a custom CDN, the first step is to disable the automatic To disable them, set their URLs to `None` when creating your `FastAPI` app: -```Python hl_lines="9" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} ### Include the custom docs for static files And the same way as with a custom CDN, now you can create the *path operations* for the custom docs. -Again, you can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: +Again, you can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: * `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`. * `title`: the title of your API. @@ -173,24 +166,23 @@ Again, you can re-use FastAPI's internal functions to create the HTML pages for And similarly for ReDoc... -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} + +/// tip -!!! tip - The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. +The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. - If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. +If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. - Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. +Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. + +/// ### Create a *path operation* to test static files Now, to be able to test that everything works, create a *path operation*: -```Python hl_lines="39-41" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} ### Test Static Files UI diff --git a/docs/en/docs/how-to/custom-request-and-route.md b/docs/en/docs/how-to/custom-request-and-route.md index 3b9435004..9b4160d75 100644 --- a/docs/en/docs/how-to/custom-request-and-route.md +++ b/docs/en/docs/how-to/custom-request-and-route.md @@ -6,10 +6,13 @@ In particular, this may be a good alternative to logic in a middleware. For example, if you want to read or manipulate the request body before it is processed by your application. -!!! danger - This is an "advanced" feature. +/// danger - If you are just starting with **FastAPI** you might want to skip this section. +This is an "advanced" feature. + +If you are just starting with **FastAPI** you might want to skip this section. + +/// ## Use cases @@ -27,8 +30,11 @@ And an `APIRoute` subclass to use that custom request class. ### Create a custom `GzipRequest` class -!!! tip - This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. +/// tip + +This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. + +/// First, we create a `GzipRequest` class, which will overwrite the `Request.body()` method to decompress the body in the presence of an appropriate header. @@ -36,9 +42,7 @@ If there's no `gzip` in the header, it will not try to decompress the body. That way, the same route class can handle gzip compressed or uncompressed requests. -```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### Create a custom `GzipRoute` class @@ -50,20 +54,21 @@ This method returns a function. And that function is what will receive a request Here we use it to create a `GzipRequest` from the original request. -```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} -!!! note "Technical Details" - A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request. +/// note | Technical Details - A `Request` also has a `request.receive`, that's a function to "receive" the body of the request. +A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request. - The `scope` `dict` and `receive` function are both part of the ASGI specification. +A `Request` also has a `request.receive`, that's a function to "receive" the body of the request. - And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance. +The `scope` `dict` and `receive` function are both part of the ASGI specification. - To learn more about the `Request` check Starlette's docs about Requests. +And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance. + +To learn more about the `Request` check Starlette's docs about Requests. + +/// The only thing the function returned by `GzipRequest.get_route_handler` does differently is convert the `Request` to a `GzipRequest`. @@ -75,35 +80,30 @@ But because of our changes in `GzipRequest.body`, the request body will be autom ## Accessing the request body in an exception handler -!!! tip - To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). +/// tip + +To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). + +But this example is still valid and it shows how to interact with the internal components. - But this example is still valid and it shows how to interact with the internal components. +/// We can also use this same approach to access the request body in an exception handler. All we need to do is handle the request inside a `try`/`except` block: -```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} If an exception occurs, the`Request` instance will still be in scope, so we can read and make use of the request body when handling the error: -```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## Custom `APIRoute` class in a router You can also set the `route_class` parameter of an `APIRouter`: -```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} In this example, the *path operations* under the `router` will use the custom `TimedRoute` class, and will have an extra `X-Response-Time` header in the response with the time it took to generate the response: -```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md index a18fd737e..26c742c20 100644 --- a/docs/en/docs/how-to/extending-openapi.md +++ b/docs/en/docs/how-to/extending-openapi.md @@ -27,8 +27,11 @@ And that function `get_openapi()` receives as parameters: * `description`: The description of your API, this can include markdown and will be shown in the docs. * `routes`: A list of routes, these are each of the registered *path operations*. They are taken from `app.routes`. -!!! info - The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above. +/// info + +The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above. + +/// ## Overriding the defaults @@ -40,25 +43,19 @@ For example, let's add Strawberry 🍓 * With docs for FastAPI * Ariadne - * With docs for Starlette (that also apply to FastAPI) + * With docs for FastAPI * Tartiflette * With Tartiflette ASGI to provide ASGI integration * Graphene @@ -32,9 +35,7 @@ Depending on your use case, you might prefer to use a different library, but if Here's a small preview of how you could integrate Strawberry with FastAPI: -```Python hl_lines="3 22 25-26" -{!../../../docs_src/graphql/tutorial001.py!} -``` +{* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} You can learn more about Strawberry in the Strawberry documentation. @@ -46,8 +47,11 @@ Previous versions of Starlette included a `GraphQLApp` class to integrate with < It was deprecated from Starlette, but if you have code that used it, you can easily **migrate** to starlette-graphene3, that covers the same use case and has an **almost identical interface**. -!!! tip - If you need GraphQL, I still would recommend you check out Strawberry, as it's based on type annotations instead of custom classes and types. +/// tip + +If you need GraphQL, I still would recommend you check out Strawberry, as it's based on type annotations instead of custom classes and types. + +/// ## Learn More diff --git a/docs/en/docs/how-to/index.md b/docs/en/docs/how-to/index.md index ec7fd38f8..730dce5d5 100644 --- a/docs/en/docs/how-to/index.md +++ b/docs/en/docs/how-to/index.md @@ -6,6 +6,8 @@ Most of these ideas would be more or less **independent**, and in most cases you If something seems interesting and useful to your project, go ahead and check it, but otherwise, you might probably just skip them. -!!! tip +/// tip - If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead. +If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead. + +/// diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md deleted file mode 100644 index 563318984..000000000 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ /dev/null @@ -1,166 +0,0 @@ -# ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated) - -!!! info - These docs are about to be updated. 🎉 - - The current version assumes Pydantic v1. - - The new docs will hopefully use Pydantic v2 and will use ODMantic with MongoDB. - -!!! warning "Deprecated" - This tutorial is deprecated and will be removed in a future version. - -**FastAPI** can also be integrated with any NoSQL. - -Here we'll see an example using **Couchbase**, a document based NoSQL database. - -You can adapt it to any other NoSQL database like: - -* **MongoDB** -* **Cassandra** -* **CouchDB** -* **ArangoDB** -* **ElasticSearch**, etc. - -!!! tip - There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-couchbase - -## Import Couchbase components - -For now, don't pay attention to the rest, only the imports: - -```Python hl_lines="3-5" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Define a constant to use as a "document type" - -We will use it later as a fixed field `type` in our documents. - -This is not required by Couchbase, but is a good practice that will help you afterwards. - -```Python hl_lines="9" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Add a function to get a `Bucket` - -In **Couchbase**, a bucket is a set of documents, that can be of different types. - -They are generally all related to the same application. - -The analogy in the relational database world would be a "database" (a specific database, not the database server). - -The analogy in **MongoDB** would be a "collection". - -In the code, a `Bucket` represents the main entrypoint of communication with the database. - -This utility function will: - -* Connect to a **Couchbase** cluster (that might be a single machine). - * Set defaults for timeouts. -* Authenticate in the cluster. -* Get a `Bucket` instance. - * Set defaults for timeouts. -* Return it. - -```Python hl_lines="12-21" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Create Pydantic models - -As **Couchbase** "documents" are actually just "JSON objects", we can model them with Pydantic. - -### `User` model - -First, let's create a `User` model: - -```Python hl_lines="24-28" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -We will use this model in our *path operation function*, so, we don't include in it the `hashed_password`. - -### `UserInDB` model - -Now, let's create a `UserInDB` model. - -This will have the data that is actually stored in the database. - -We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of our own `User`, because it will have all the attributes in `User` plus a couple more: - -```Python hl_lines="31-33" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -!!! note - Notice that we have a `hashed_password` and a `type` field that will be stored in the database. - - But it is not part of the general `User` model (the one we will return in the *path operation*). - -## Get the user - -Now create a function that will: - -* Take a username. -* Generate a document ID from it. -* Get the document with that ID. -* Put the contents of the document in a `UserInDB` model. - -By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily re-use it in multiple parts and also add unit tests for it: - -```Python hl_lines="36-42" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### f-strings - -If you are not familiar with the `f"userprofile::{username}"`, it is a Python "f-string". - -Any variable that is put inside of `{}` in an f-string will be expanded / injected in the string. - -### `dict` unpacking - -If you are not familiar with the `UserInDB(**result.value)`, it is using `dict` "unpacking". - -It will take the `dict` at `result.value`, and take each of its keys and values and pass them as key-values to `UserInDB` as keyword arguments. - -So, if the `dict` contains: - -```Python -{ - "username": "johndoe", - "hashed_password": "some_hash", -} -``` - -It will be passed to `UserInDB` as: - -```Python -UserInDB(username="johndoe", hashed_password="some_hash") -``` - -## Create your **FastAPI** code - -### Create the `FastAPI` app - -```Python hl_lines="46" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### Create the *path operation function* - -As our code is calling Couchbase and we are not using the experimental Python await support, we should declare our function with normal `def` instead of `async def`. - -Also, Couchbase recommends not using a single `Bucket` object in multiple "threads", so, we can just get the bucket directly and pass it to our utility functions: - -```Python hl_lines="49-53" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Recap - -You can integrate any third party NoSQL database, just using their standard packages. - -The same applies to any other external tool, system or API. diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md index 10be1071a..9a27638fe 100644 --- a/docs/en/docs/how-to/separate-openapi-schemas.md +++ b/docs/en/docs/how-to/separate-openapi-schemas.md @@ -10,111 +10,13 @@ Let's see how that works and how to change it if you need to do that. Let's say you have a Pydantic model with default values, like this one: -=== "Python 3.10+" - - ```Python hl_lines="7" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` - -
- -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` - -
- -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` - -
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} ### Model for Input If you use this model as an input like here: -=== "Python 3.10+" - - ```Python hl_lines="14" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` - -
- -=== "Python 3.9+" - - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` - -
- -=== "Python 3.8+" - - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` - -
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} ...then the `description` field will **not be required**. Because it has a default value of `None`. @@ -130,23 +32,7 @@ You can confirm that in the docs, the `description` field doesn't have a **red a But if you use the same model as an output, like here: -=== "Python 3.10+" - - ```Python hl_lines="19" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} ...then because `description` has a default value, if you **don't return anything** for that field, it will still have that **default value**. @@ -199,26 +85,13 @@ Probably the main use case for this is if you already have some autogenerated cl In that case, you can disable this feature in **FastAPI**, with the parameter `separate_input_output_schemas=False`. -!!! info - Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 - -=== "Python 3.10+" - - ```Python hl_lines="10" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} - ``` - -=== "Python 3.9+" +/// info - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} - ``` +Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 -=== "Python 3.8+" +/// - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} - ``` +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} ### Same Schema for Input and Output Models in Docs diff --git a/docs/en/docs/how-to/sql-databases-peewee.md b/docs/en/docs/how-to/sql-databases-peewee.md deleted file mode 100644 index 7211f7ed3..000000000 --- a/docs/en/docs/how-to/sql-databases-peewee.md +++ /dev/null @@ -1,541 +0,0 @@ -# ~~SQL (Relational) Databases with Peewee~~ (deprecated) - -!!! warning "Deprecated" - This tutorial is deprecated and will be removed in a future version. - -!!! warning - If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. - - Feel free to skip this. - - Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives. - -!!! info - These docs assume Pydantic v1. - - Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes. - - The examples here are no longer tested in CI (as they were before). - -If you are starting a project from scratch, you are probably better off with SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), or any other async ORM. - -If you already have a code base that uses Peewee ORM, you can check here how to use it with **FastAPI**. - -!!! warning "Python 3.7+ required" - You will need Python 3.7 or above to safely use Peewee with FastAPI. - -## Peewee for async - -Peewee was not designed for async frameworks, or with them in mind. - -Peewee has some heavy assumptions about its defaults and about how it should be used. - -If you are developing an application with an older non-async framework, and can work with all its defaults, **it can be a great tool**. - -But if you need to change some of the defaults, support more than one predefined database, work with an async framework (like FastAPI), etc, you will need to add quite some complex extra code to override those defaults. - -Nevertheless, it's possible to do it, and here you'll see exactly what code you have to add to be able to use Peewee with FastAPI. - -!!! note "Technical Details" - You can read more about Peewee's stand about async in Python in the docs, an issue, a PR. - -## The same app - -We are going to create the same application as in the SQLAlchemy tutorial ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}). - -Most of the code is actually the same. - -So, we are going to focus only on the differences. - -## File structure - -Let's say you have a directory named `my_super_project` that contains a sub-directory called `sql_app` with a structure like this: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - └── schemas.py -``` - -This is almost the same structure as we had for the SQLAlchemy tutorial. - -Now let's see what each file/module does. - -## Create the Peewee parts - -Let's refer to the file `sql_app/database.py`. - -### The standard Peewee code - -Let's first check all the normal Peewee code, create a Peewee database: - -```Python hl_lines="3 5 22" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -!!! tip - Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class. - -#### Note - -The argument: - -```Python -check_same_thread=False -``` - -is equivalent to the one in the SQLAlchemy tutorial: - -```Python -connect_args={"check_same_thread": False} -``` - -...it is needed only for `SQLite`. - -!!! info "Technical Details" - - Exactly the same technical details as in [SQL (Relational) Databases](../tutorial/sql-databases.md#note){.internal-link target=_blank} apply. - -### Make Peewee async-compatible `PeeweeConnectionState` - -The main issue with Peewee and FastAPI is that Peewee relies heavily on Python's `threading.local`, and it doesn't have a direct way to override it or let you handle connections/sessions directly (as is done in the SQLAlchemy tutorial). - -And `threading.local` is not compatible with the new async features of modern Python. - -!!! note "Technical Details" - `threading.local` is used to have a "magic" variable that has a different value for each thread. - - This was useful in older frameworks designed to have one single thread per request, no more, no less. - - Using this, each request would have its own database connection/session, which is the actual final goal. - - But FastAPI, using the new async features, could handle more than one request on the same thread. And at the same time, for a single request, it could run multiple things in different threads (in a threadpool), depending on if you use `async def` or normal `def`. This is what gives all the performance improvements to FastAPI. - -But Python 3.7 and above provide a more advanced alternative to `threading.local`, that can also be used in the places where `threading.local` would be used, but is compatible with the new async features. - -We are going to use that. It's called `contextvars`. - -We are going to override the internal parts of Peewee that use `threading.local` and replace them with `contextvars`, with the corresponding updates. - -This might seem a bit complex (and it actually is), you don't really need to completely understand how it works to use it. - -We will create a `PeeweeConnectionState`: - -```Python hl_lines="10-19" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -This class inherits from a special internal class used by Peewee. - -It has all the logic to make Peewee use `contextvars` instead of `threading.local`. - -`contextvars` works a bit differently than `threading.local`. But the rest of Peewee's internal code assumes that this class works with `threading.local`. - -So, we need to do some extra tricks to make it work as if it was just using `threading.local`. The `__init__`, `__setattr__`, and `__getattr__` implement all the required tricks for this to be used by Peewee without knowing that it is now compatible with FastAPI. - -!!! tip - This will just make Peewee behave correctly when used with FastAPI. Not randomly opening or closing connections that are being used, creating errors, etc. - - But it doesn't give Peewee async super-powers. You should still use normal `def` functions and not `async def`. - -### Use the custom `PeeweeConnectionState` class - -Now, overwrite the `._state` internal attribute in the Peewee database `db` object using the new `PeeweeConnectionState`: - -```Python hl_lines="24" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -!!! tip - Make sure you overwrite `db._state` *after* creating `db`. - -!!! tip - You would do the same for any other Peewee database, including `PostgresqlDatabase`, `MySQLDatabase`, etc. - -## Create the database models - -Let's now see the file `sql_app/models.py`. - -### Create Peewee models for our data - -Now create the Peewee models (classes) for `User` and `Item`. - -This is the same you would do if you followed the Peewee tutorial and updated the models to have the same data as in the SQLAlchemy tutorial. - -!!! tip - Peewee also uses the term "**model**" to refer to these classes and instances that interact with the database. - - But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. - -Import `db` from `database` (the file `database.py` from above) and use it here. - -```Python hl_lines="3 6-12 15-21" -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -!!! tip - Peewee creates several magic attributes. - - It will automatically add an `id` attribute as an integer to be the primary key. - - It will chose the name of the tables based on the class names. - - For the `Item`, it will create an attribute `owner_id` with the integer ID of the `User`. But we don't declare it anywhere. - -## Create the Pydantic models - -Now let's check the file `sql_app/schemas.py`. - -!!! tip - To avoid confusion between the Peewee *models* and the Pydantic *models*, we will have the file `models.py` with the Peewee models, and the file `schemas.py` with the Pydantic models. - - These Pydantic models define more or less a "schema" (a valid data shape). - - So this will help us avoiding confusion while using both. - -### Create the Pydantic *models* / schemas - -Create all the same Pydantic models as in the SQLAlchemy tutorial: - -```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -!!! tip - Here we are creating the models with an `id`. - - We didn't explicitly specify an `id` attribute in the Peewee models, but Peewee adds one automatically. - - We are also adding the magic `owner_id` attribute to `Item`. - -### Create a `PeeweeGetterDict` for the Pydantic *models* / schemas - -When you access a relationship in a Peewee object, like in `some_user.items`, Peewee doesn't provide a `list` of `Item`. - -It provides a special custom object of class `ModelSelect`. - -It's possible to create a `list` of its items with `list(some_user.items)`. - -But the object itself is not a `list`. And it's also not an actual Python generator. Because of this, Pydantic doesn't know by default how to convert it to a `list` of Pydantic *models* / schemas. - -But recent versions of Pydantic allow providing a custom class that inherits from `pydantic.utils.GetterDict`, to provide the functionality used when using the `orm_mode = True` to retrieve the values for ORM model attributes. - -We are going to create a custom `PeeweeGetterDict` class and use it in all the same Pydantic *models* / schemas that use `orm_mode`: - -```Python hl_lines="3 8-13 31 49" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -Here we are checking if the attribute that is being accessed (e.g. `.items` in `some_user.items`) is an instance of `peewee.ModelSelect`. - -And if that's the case, just return a `list` with it. - -And then we use it in the Pydantic *models* / schemas that use `orm_mode = True`, with the configuration variable `getter_dict = PeeweeGetterDict`. - -!!! tip - We only need to create one `PeeweeGetterDict` class, and we can use it in all the Pydantic *models* / schemas. - -## CRUD utils - -Now let's see the file `sql_app/crud.py`. - -### Create all the CRUD utils - -Create all the same CRUD utils as in the SQLAlchemy tutorial, all the code is very similar: - -```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -There are some differences with the code for the SQLAlchemy tutorial. - -We don't pass a `db` attribute around. Instead we use the models directly. This is because the `db` object is a global object, that includes all the connection logic. That's why we had to do all the `contextvars` updates above. - -Aso, when returning several objects, like in `get_users`, we directly call `list`, like in: - -```Python -list(models.User.select()) -``` - -This is for the same reason that we had to create a custom `PeeweeGetterDict`. But by returning something that is already a `list` instead of the `peewee.ModelSelect` the `response_model` in the *path operation* with `List[models.User]` (that we'll see later) will work correctly. - -## Main **FastAPI** app - -And now in the file `sql_app/main.py` let's integrate and use all the other parts we created before. - -### Create the database tables - -In a very simplistic way create the database tables: - -```Python hl_lines="9-11" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### Create a dependency - -Create a dependency that will connect the database right at the beginning of a request and disconnect it at the end: - -```Python hl_lines="23-29" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -Here we have an empty `yield` because we are actually not using the database object directly. - -It is connecting to the database and storing the connection data in an internal variable that is independent for each request (using the `contextvars` tricks from above). - -Because the database connection is potentially I/O blocking, this dependency is created with a normal `def` function. - -And then, in each *path operation function* that needs to access the database we add it as a dependency. - -But we are not using the value given by this dependency (it actually doesn't give any value, as it has an empty `yield`). So, we don't add it to the *path operation function* but to the *path operation decorator* in the `dependencies` parameter: - -```Python hl_lines="32 40 47 59 65 72" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### Context variable sub-dependency - -For all the `contextvars` parts to work, we need to make sure we have an independent value in the `ContextVar` for each request that uses the database, and that value will be used as the database state (connection, transactions, etc) for the whole request. - -For that, we need to create another `async` dependency `reset_db_state()` that is used as a sub-dependency in `get_db()`. It will set the value for the context variable (with just a default `dict`) that will be used as the database state for the whole request. And then the dependency `get_db()` will store in it the database state (connection, transactions, etc). - -```Python hl_lines="18-20" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -For the **next request**, as we will reset that context variable again in the `async` dependency `reset_db_state()` and then create a new connection in the `get_db()` dependency, that new request will have its own database state (connection, transactions, etc). - -!!! tip - As FastAPI is an async framework, one request could start being processed, and before finishing, another request could be received and start processing as well, and it all could be processed in the same thread. - - But context variables are aware of these async features, so, a Peewee database state set in the `async` dependency `reset_db_state()` will keep its own data throughout the entire request. - - And at the same time, the other concurrent request will have its own database state that will be independent for the whole request. - -#### Peewee Proxy - -If you are using a Peewee Proxy, the actual database is at `db.obj`. - -So, you would reset it with: - -```Python hl_lines="3-4" -async def reset_db_state(): - database.db.obj._state._state.set(db_state_default.copy()) - database.db.obj._state.reset() -``` - -### Create your **FastAPI** *path operations* - -Now, finally, here's the standard **FastAPI** *path operations* code. - -```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### About `def` vs `async def` - -The same as with SQLAlchemy, we are not doing something like: - -```Python -user = await models.User.select().first() -``` - -...but instead we are using: - -```Python -user = models.User.select().first() -``` - -So, again, we should declare the *path operation functions* and the dependency without `async def`, just with a normal `def`, as: - -```Python hl_lines="2" -# Something goes here -def read_users(skip: int = 0, limit: int = 100): - # Something goes here -``` - -## Testing Peewee with async - -This example includes an extra *path operation* that simulates a long processing request with `time.sleep(sleep_time)`. - -It will have the database connection open at the beginning and will just wait some seconds before replying back. And each new request will wait one second less. - -This will easily let you test that your app with Peewee and FastAPI is behaving correctly with all the stuff about threads. - -If you want to check how Peewee would break your app if used without modification, go the `sql_app/database.py` file and comment the line: - -```Python -# db._state = PeeweeConnectionState() -``` - -And in the file `sql_app/main.py` file, comment the body of the `async` dependency `reset_db_state()` and replace it with a `pass`: - -```Python -async def reset_db_state(): -# database.db._state._state.set(db_state_default.copy()) -# database.db._state.reset() - pass -``` - -Then run your app with Uvicorn: - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Open your browser at http://127.0.0.1:8000/docs and create a couple of users. - -Then open 10 tabs at http://127.0.0.1:8000/docs#/default/read_slow_users_slowusers__get at the same time. - -Go to the *path operation* "Get `/slowusers/`" in all of the tabs. Use the "Try it out" button and execute the request in each tab, one right after the other. - -The tabs will wait for a bit and then some of them will show `Internal Server Error`. - -### What happens - -The first tab will make your app create a connection to the database and wait for some seconds before replying back and closing the database connection. - -Then, for the request in the next tab, your app will wait for one second less, and so on. - -This means that it will end up finishing some of the last tabs' requests earlier than some of the previous ones. - -Then one the last requests that wait less seconds will try to open a database connection, but as one of those previous requests for the other tabs will probably be handled in the same thread as the first one, it will have the same database connection that is already open, and Peewee will throw an error and you will see it in the terminal, and the response will have an `Internal Server Error`. - -This will probably happen for more than one of those tabs. - -If you had multiple clients talking to your app exactly at the same time, this is what could happen. - -And as your app starts to handle more and more clients at the same time, the waiting time in a single request needs to be shorter and shorter to trigger the error. - -### Fix Peewee with FastAPI - -Now go back to the file `sql_app/database.py`, and uncomment the line: - -```Python -db._state = PeeweeConnectionState() -``` - -And in the file `sql_app/main.py` file, uncomment the body of the `async` dependency `reset_db_state()`: - -```Python -async def reset_db_state(): - database.db._state._state.set(db_state_default.copy()) - database.db._state.reset() -``` - -Terminate your running app and start it again. - -Repeat the same process with the 10 tabs. This time all of them will wait and you will get all the results without errors. - -...You fixed it! - -## Review all the files - - Remember you should have a directory named `my_super_project` (or however you want) that contains a sub-directory called `sql_app`. - -`sql_app` should have the following files: - -* `sql_app/__init__.py`: is an empty file. - -* `sql_app/database.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -* `sql_app/crud.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -## Technical Details - -!!! warning - These are very technical details that you probably don't need. - -### The problem - -Peewee uses `threading.local` by default to store it's database "state" data (connection, transactions, etc). - -`threading.local` creates a value exclusive to the current thread, but an async framework would run all the code (e.g. for each request) in the same thread, and possibly not in order. - -On top of that, an async framework could run some sync code in a threadpool (using `asyncio.run_in_executor`), but belonging to the same request. - -This means that, with Peewee's current implementation, multiple tasks could be using the same `threading.local` variable and end up sharing the same connection and data (that they shouldn't), and at the same time, if they execute sync I/O-blocking code in a threadpool (as with normal `def` functions in FastAPI, in *path operations* and dependencies), that code won't have access to the database state variables, even while it's part of the same request and it should be able to get access to the same database state. - -### Context variables - -Python 3.7 has `contextvars` that can create a local variable very similar to `threading.local`, but also supporting these async features. - -There are several things to keep in mind. - -The `ContextVar` has to be created at the top of the module, like: - -```Python -some_var = ContextVar("some_var", default="default value") -``` - -To set a value used in the current "context" (e.g. for the current request) use: - -```Python -some_var.set("new value") -``` - -To get a value anywhere inside of the context (e.g. in any part handling the current request) use: - -```Python -some_var.get() -``` - -### Set context variables in the `async` dependency `reset_db_state()` - -If some part of the async code sets the value with `some_var.set("updated in function")` (e.g. like the `async` dependency), the rest of the code in it and the code that goes after (including code inside of `async` functions called with `await`) will see that new value. - -So, in our case, if we set the Peewee state variable (with a default `dict`) in the `async` dependency, all the rest of the internal code in our app will see this value and will be able to reuse it for the whole request. - -And the context variable would be set again for the next request, even if they are concurrent. - -### Set database state in the dependency `get_db()` - -As `get_db()` is a normal `def` function, **FastAPI** will make it run in a threadpool, with a *copy* of the "context", holding the same value for the context variable (the `dict` with the reset database state). Then it can add database state to that `dict`, like the connection, etc. - -But if the value of the context variable (the default `dict`) was set in that normal `def` function, it would create a new value that would stay only in that thread of the threadpool, and the rest of the code (like the *path operation functions*) wouldn't have access to it. In `get_db()` we can only set values in the `dict`, but not the entire `dict` itself. - -So, we need to have the `async` dependency `reset_db_state()` to set the `dict` in the context variable. That way, all the code has access to the same `dict` for the database state for a single request. - -### Connect and disconnect in the dependency `get_db()` - -Then the next question would be, why not just connect and disconnect the database in the `async` dependency itself, instead of in `get_db()`? - -The `async` dependency has to be `async` for the context variable to be preserved for the rest of the request, but creating and closing the database connection is potentially blocking, so it could degrade performance if it was there. - -So we also need the normal `def` dependency `get_db()`. diff --git a/docs/en/docs/how-to/testing-database.md b/docs/en/docs/how-to/testing-database.md new file mode 100644 index 000000000..d0ed15bca --- /dev/null +++ b/docs/en/docs/how-to/testing-database.md @@ -0,0 +1,7 @@ +# Testing a Database + +You can study about databases, SQL, and SQLModel in the SQLModel docs. 🤓 + +There's a mini tutorial on using SQLModel with FastAPI. ✨ + +That tutorial includes a section about testing SQL databases. 😎 diff --git a/docs/en/docs/img/sponsors/fine-banner.png b/docs/en/docs/img/sponsors/fine-banner.png new file mode 100644 index 000000000..57d8e52c7 Binary files /dev/null and b/docs/en/docs/img/sponsors/fine-banner.png differ diff --git a/docs/en/docs/img/sponsors/fine.png b/docs/en/docs/img/sponsors/fine.png new file mode 100644 index 000000000..ed770f212 Binary files /dev/null and b/docs/en/docs/img/sponsors/fine.png differ diff --git a/docs/en/docs/img/sponsors/kong-banner.png b/docs/en/docs/img/sponsors/kong-banner.png new file mode 100644 index 000000000..9f5b55a0f Binary files /dev/null and b/docs/en/docs/img/sponsors/kong-banner.png differ diff --git a/docs/en/docs/img/sponsors/kong.png b/docs/en/docs/img/sponsors/kong.png new file mode 100644 index 000000000..e54cdac2c Binary files /dev/null and b/docs/en/docs/img/sponsors/kong.png differ diff --git a/docs/en/docs/img/sponsors/liblab-banner.png b/docs/en/docs/img/sponsors/liblab-banner.png new file mode 100644 index 000000000..299ff816b Binary files /dev/null and b/docs/en/docs/img/sponsors/liblab-banner.png differ diff --git a/docs/en/docs/img/sponsors/liblab.png b/docs/en/docs/img/sponsors/liblab.png new file mode 100644 index 000000000..ee461d7bc Binary files /dev/null and b/docs/en/docs/img/sponsors/liblab.png differ diff --git a/docs/en/docs/img/sponsors/render-banner.svg b/docs/en/docs/img/sponsors/render-banner.svg new file mode 100644 index 000000000..b8b1ed2e9 --- /dev/null +++ b/docs/en/docs/img/sponsors/render-banner.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/img/sponsors/render.svg b/docs/en/docs/img/sponsors/render.svg new file mode 100644 index 000000000..4a830482d --- /dev/null +++ b/docs/en/docs/img/sponsors/render.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/img/sponsors/stainless.png b/docs/en/docs/img/sponsors/stainless.png new file mode 100644 index 000000000..0f99c1d32 Binary files /dev/null and b/docs/en/docs/img/sponsors/stainless.png differ diff --git a/docs/en/docs/img/sponsors/zuplo-banner.png b/docs/en/docs/img/sponsors/zuplo-banner.png new file mode 100644 index 000000000..a730f2cf2 Binary files /dev/null and b/docs/en/docs/img/sponsors/zuplo-banner.png differ diff --git a/docs/en/docs/img/sponsors/zuplo.png b/docs/en/docs/img/sponsors/zuplo.png new file mode 100644 index 000000000..7a7c16862 Binary files /dev/null and b/docs/en/docs/img/sponsors/zuplo.png differ diff --git a/docs/en/docs/img/tutorial/cookie-param-models/image01.png b/docs/en/docs/img/tutorial/cookie-param-models/image01.png new file mode 100644 index 000000000..85c370f80 Binary files /dev/null and b/docs/en/docs/img/tutorial/cookie-param-models/image01.png differ diff --git a/docs/en/docs/img/tutorial/header-param-models/image01.png b/docs/en/docs/img/tutorial/header-param-models/image01.png new file mode 100644 index 000000000..849dea3d8 Binary files /dev/null and b/docs/en/docs/img/tutorial/header-param-models/image01.png differ diff --git a/docs/en/docs/img/tutorial/query-param-models/image01.png b/docs/en/docs/img/tutorial/query-param-models/image01.png new file mode 100644 index 000000000..e7a61b61f Binary files /dev/null and b/docs/en/docs/img/tutorial/query-param-models/image01.png differ diff --git a/docs/en/docs/img/tutorial/request-form-models/image01.png b/docs/en/docs/img/tutorial/request-form-models/image01.png new file mode 100644 index 000000000..3fe32c03d Binary files /dev/null and b/docs/en/docs/img/tutorial/request-form-models/image01.png differ diff --git a/docs/en/docs/img/tutorial/sql-databases/image01.png b/docs/en/docs/img/tutorial/sql-databases/image01.png index 8e575abd6..bfcdb57a0 100644 Binary files a/docs/en/docs/img/tutorial/sql-databases/image01.png and b/docs/en/docs/img/tutorial/sql-databases/image01.png differ diff --git a/docs/en/docs/img/tutorial/sql-databases/image02.png b/docs/en/docs/img/tutorial/sql-databases/image02.png index ee59fc939..7bcad8378 100644 Binary files a/docs/en/docs/img/tutorial/sql-databases/image02.png and b/docs/en/docs/img/tutorial/sql-databases/image02.png differ diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 86b0c699b..4d0514241 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI +

FastAPI

@@ -5,11 +11,11 @@ FastAPI framework, alto desempeño, fácil de aprender, rápido de programar, listo para producción

- - Test + + Test - - Coverage + + Coverage Package version @@ -20,10 +26,10 @@ **Documentación**: https://fastapi.tiangolo.com -**Código Fuente**: https://github.com/tiangolo/fastapi +**Código Fuente**: https://github.com/fastapi/fastapi --- -FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 3.8+ basado en las anotaciones de tipos estándar de Python. +FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python basado en las anotaciones de tipos estándar de Python. Sus características principales son: @@ -60,7 +66,7 @@ Sus características principales son: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -84,7 +90,7 @@ Sus características principales son: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -106,8 +112,6 @@ Si estás construyendo un app de Starlette para las partes web. @@ -125,7 +129,7 @@ $ pip install fastapi
-También vas a necesitar un servidor ASGI para producción cómo Uvicorn o Hypercorn. +También vas a necesitar un servidor ASGI para producción cómo Uvicorn o Hypercorn.
@@ -319,7 +323,7 @@ Lo haces con tipos modernos estándar de Python. No tienes que aprender una sintaxis nueva, los métodos o clases de una library específica, etc. -Solo **Python 3.8+** estándar. +Solo **Python** estándar. Por ejemplo, para un `int`: @@ -433,7 +437,7 @@ Para entender más al respecto revisa la sección email_validator - para validación de emails. +* email-validator - para validación de emails. Usados por Starlette: @@ -443,12 +447,12 @@ Usados por Starlette: * itsdangerous - Requerido para dar soporte a `SessionMiddleware`. * pyyaml - Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI). * graphene - Requerido para dar soporte a `GraphQLApp`. -* ujson - Requerido si quieres usar `UJSONResponse`. Usado por FastAPI / Starlette: * uvicorn - para el servidor que carga y sirve tu aplicación. * orjson - Requerido si quieres usar `ORJSONResponse`. +* ujson - Requerido si quieres usar `UJSONResponse`. Puedes instalarlos con `pip install fastapi[all]`. diff --git a/docs/es/docs/newsletter.md b/docs/es/docs/newsletter.md deleted file mode 100644 index f4dcfe155..000000000 --- a/docs/es/docs/newsletter.md +++ /dev/null @@ -1,5 +0,0 @@ -# Boletín de Noticias de FastAPI y amigos - - - - diff --git a/docs/es/docs/project-generation.md b/docs/es/docs/project-generation.md new file mode 100644 index 000000000..6aa570397 --- /dev/null +++ b/docs/es/docs/project-generation.md @@ -0,0 +1,28 @@ +# Plantilla de FastAPI Full Stack + +Las plantillas, aunque típicamente vienen con una configuración específica, están diseñadas para ser flexibles y personalizables. Esto te permite modificarlas y adaptarlas a los requisitos de tu proyecto, lo que las convierte en un excelente punto de partida. 🏁 + +Puedes utilizar esta plantilla para comenzar, ya que incluye gran parte de la configuración inicial, seguridad, base de datos y algunos endpoints de API ya realizados. + +Repositorio en GitHub: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template) + +## Plantilla de FastAPI Full Stack - Tecnología y Características + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) para el backend API en Python. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para las interacciones con la base de datos SQL en Python (ORM). + - 🔍 [Pydantic](https://docs.pydantic.dev), utilizado por FastAPI, para la validación de datos y la gestión de configuraciones. + - 💾 [PostgreSQL](https://www.postgresql.org) como la base de datos SQL. +- 🚀 [React](https://react.dev) para el frontend. + - 💃 Usando TypeScript, hooks, [Vite](https://vitejs.dev) y otras partes de un stack de frontend moderno. + - 🎨 [Chakra UI](https://chakra-ui.com) para los componentes del frontend. + - 🤖 Un cliente frontend generado automáticamente. + - 🧪 [Playwright](https://playwright.dev) para pruebas End-to-End. + - 🦇 Soporte para modo oscuro. +- 🐋 [Docker Compose](https://www.docker.com) para desarrollo y producción. +- 🔒 Hashing seguro de contraseñas por defecto. +- 🔑 Autenticación con token JWT. +- 📫 Recuperación de contraseñas basada en email. +- ✅ Tests con [Pytest](https://pytest.org). +- 📞 [Traefik](https://traefik.io) como proxy inverso / balanceador de carga. +- 🚢 Instrucciones de despliegue utilizando Docker Compose, incluyendo cómo configurar un proxy frontend Traefik para manejar certificados HTTPS automáticos. +- 🏭 CI (integración continua) y CD (despliegue continuo) basados en GitHub Actions. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index 89edbb31e..156907ad1 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -12,15 +12,18 @@ Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints. -!!! note "Nota" - Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. +/// note | Nota + +Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. + +/// ## Motivación Comencemos con un ejemplo simple: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Llamar este programa nos muestra el siguiente output: @@ -36,14 +39,14 @@ La función hace lo siguiente: * Las concatena con un espacio en la mitad. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Edítalo Es un programa muy simple. -Ahora, imagina que lo estás escribiendo desde ceros. +Ahora, imagina que lo estás escribiendo desde cero. En algún punto habrías comenzado con la definición de la función, tenías los parámetros listos... @@ -80,7 +83,7 @@ Eso es todo. Esos son los "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` No es lo mismo a declarar valores por defecto, como sería con: @@ -110,7 +113,7 @@ Con esto puedes moverte hacia abajo viendo las opciones hasta que encuentras una Mira esta función que ya tiene type hints: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores: @@ -120,7 +123,7 @@ Como el editor conoce el tipo de las variables no solo obtienes auto-completado, Ahora que sabes que tienes que arreglarlo convierte `age` a un string con `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Declarando tipos @@ -141,7 +144,7 @@ Por ejemplo, puedes usar: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Tipos con sub-tipos @@ -159,7 +162,7 @@ Por ejemplo, vamos a definir una variable para que sea una `list` compuesta de ` De `typing`, importa `List` (con una `L` mayúscula): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Declara la variable con la misma sintaxis de los dos puntos (`:`). @@ -169,7 +172,7 @@ Pon `List` como el tipo. Como la lista es un tipo que permite tener un "sub-tipo" pones el sub-tipo en corchetes `[]`: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`. @@ -189,7 +192,7 @@ El editor aún sabe que es un `str` y provee soporte para ello. Harías lo mismo para declarar `tuple`s y `set`s: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Esto significa: @@ -206,7 +209,7 @@ El primer sub-tipo es para los keys del `dict`. El segundo sub-tipo es para los valores del `dict`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Esto significa: @@ -222,13 +225,13 @@ También puedes declarar una clase como el tipo de una variable. Digamos que tienes una clase `Person`con un nombre: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Entonces puedes declarar una variable que sea de tipo `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Una vez más tendrás todo el soporte del editor: @@ -250,11 +253,14 @@ Y obtienes todo el soporte del editor con el objeto resultante. Tomado de la documentación oficial de Pydantic: ```Python -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` -!!! info "Información" - Para aprender más sobre Pydantic mira su documentación. +/// info | Información + +Para aprender más sobre Pydantic mira su documentación. + +/// **FastAPI** está todo basado en Pydantic. @@ -282,5 +288,8 @@ Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti. -!!! info "Información" - Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`. +/// info | Información + +Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`. + +/// diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..9a3b1a00b --- /dev/null +++ b/docs/es/docs/tutorial/cookie-params.md @@ -0,0 +1,35 @@ +# Parámetros de Cookie + +Puedes definir parámetros de Cookie de la misma manera que defines parámetros de `Query` y `Path`. + +## Importar `Cookie` + +Primero importa `Cookie`: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3]*} + +## Declarar parámetros de `Cookie` + +Luego declara los parámetros de cookie usando la misma estructura que con `Path` y `Query`. + +El primer valor es el valor por defecto, puedes pasar todos los parámetros adicionales de validación o anotación: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9]*} + +/// note | Detalles Técnicos + +`Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`. + +Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales. + +/// + +/// info + +Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query. + +/// + +## Resumen + +Declara cookies con `Cookie`, usando el mismo patrón común que `Query` y `Path`. diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index 2cb7e6308..68df00e64 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Un archivo muy simple de FastAPI podría verse así: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Copia eso a un archivo `main.py`. @@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note "Nota" - El comando `uvicorn main:app` se refiere a: +/// note | Nota - * `main`: el archivo `main.py` (el "módulo" de Python). - * `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. - * `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo. +El comando `uvicorn main:app` se refiere a: + +* `main`: el archivo `main.py` (el "módulo" de Python). +* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. +* `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo. + +/// En el output, hay una línea que dice más o menos: @@ -131,20 +134,23 @@ También podrías usarlo para generar código automáticamente, para los cliente ### Paso 1: importa `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. -!!! note "Detalles Técnicos" - `FastAPI` es una clase que hereda directamente de `Starlette`. +/// note | Detalles Técnicos + +`FastAPI` es una clase que hereda directamente de `Starlette`. - También puedes usar toda la funcionalidad de Starlette. +También puedes usar toda la funcionalidad de Starlette. + +/// ### Paso 2: crea un "instance" de `FastAPI` ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Aquí la variable `app` será un instance de la clase `FastAPI`. @@ -166,7 +172,7 @@ $ uvicorn main:app --reload Si creas un app como: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` y lo guardas en un archivo `main.py`, entonces ejecutarías `uvicorn` así: @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Información" - Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". +/// info | Información + +Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". + +/// Cuando construyes una API, el "path" es la manera principal de separar los "intereses" y los "recursos". @@ -242,7 +251,7 @@ Nosotros también los llamaremos "**operación**". #### Define un *decorador de operaciones de path* ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` El `@app.get("/")` le dice a **FastAPI** que la función que tiene justo debajo está a cargo de manejar los requests que van a: @@ -250,16 +259,19 @@ El `@app.get("/")` le dice a **FastAPI** que la función que tiene justo debajo * el path `/` * usando una operación get -!!! info "Información sobre `@decorator`" - Esa sintaxis `@algo` se llama un "decorador" en Python. +/// info | Información sobre `@decorator` - Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto). +Esa sintaxis `@algo` se llama un "decorador" en Python. - Un "decorador" toma la función que tiene debajo y hace algo con ella. +Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto). - En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`. +Un "decorador" toma la función que tiene debajo y hace algo con ella. - Es el "**decorador de operaciones de path**". +En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`. + +Es el "**decorador de operaciones de path**". + +/// También puedes usar las otras operaciones: @@ -274,14 +286,17 @@ y las más exóticas: * `@app.patch()` * `@app.trace()` -!!! tip "Consejo" - Tienes la libertad de usar cada operación (método de HTTP) como quieras. +/// tip | Consejo + +Tienes la libertad de usar cada operación (método de HTTP) como quieras. - **FastAPI** no impone ningún significado específico. +**FastAPI** no impone ningún significado específico. - La información que está presentada aquí es una guía, no un requerimiento. +La información que está presentada aquí es una guía, no un requerimiento. - Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`. +Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`. + +/// ### Paso 4: define la **función de la operación de path** @@ -292,7 +307,7 @@ Esta es nuestra "**función de la operación de path**": * **función**: es la función debajo del "decorador" (debajo de `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Esto es una función de Python. @@ -306,16 +321,19 @@ En este caso es una función `async`. También podrías definirla como una función estándar en lugar de `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Nota" - Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note | Nota + +Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}. + +/// ### Paso 5: devuelve el contenido ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Puedes devolver `dict`, `list`, valores singulares como un `str`, `int`, etc. diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md index f0dff02b4..fa13450f0 100644 --- a/docs/es/docs/tutorial/index.md +++ b/docs/es/docs/tutorial/index.md @@ -50,22 +50,25 @@ $ pip install "fastapi[all]" ...eso también incluye `uvicorn` que puedes usar como el servidor que ejecuta tu código. -!!! nota - También puedes instalarlo parte por parte. +/// note | Nota - Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción: +También puedes instalarlo parte por parte. - ``` - pip install fastapi - ``` +Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción: - También debes instalar `uvicorn` para que funcione como tu servidor: +``` +pip install fastapi +``` + +También debes instalar `uvicorn` para que funcione como tu servidor: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Y lo mismo para cada una de las dependencias opcionales que quieras utilizar. - Y lo mismo para cada una de las dependencias opcionales que quieras utilizar. +/// ## Guía Avanzada de Usuario diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md index 7faa92f51..167c88659 100644 --- a/docs/es/docs/tutorial/path-params.md +++ b/docs/es/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Puedes declarar los "parámetros" o "variables" con la misma sintaxis que usan los format strings de Python: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` El valor del parámetro de path `item_id` será pasado a tu función como el argumento `item_id`. @@ -19,13 +19,16 @@ Entonces, si corres este ejemplo y vas a Conversión de datos @@ -35,10 +38,13 @@ Si corres este ejemplo y abres tu navegador en "parsing" automático del request. - Entonces, con esa declaración de tipos **FastAPI** te da "parsing" automático del request. +/// ## Validación de datos @@ -63,12 +69,15 @@ debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es El mismo error aparecería si pasaras un `float` en vez de un `int` como en: http://127.0.0.1:8000/items/4.2 -!!! check "Revisa" - Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. +/// check | Revisa - Observa que el error también muestra claramente el punto exacto en el que no pasó la validación. +Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. - Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API. +Observa que el error también muestra claramente el punto exacto en el que no pasó la validación. + +Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API. + +/// ## Documentación @@ -76,10 +85,13 @@ Cuando abras tu navegador en -!!! check "Revisa" - Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) +/// check | Revisa + +Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) + +Observa que el parámetro de path está declarado como un integer. - Observa que el parámetro de path está declarado como un integer. +/// ## Beneficios basados en estándares, documentación alternativa @@ -110,7 +122,7 @@ Digamos algo como `/users/me` que sea para obtener datos del usuario actual. Porque las *operaciones de path* son evaluadas en orden, tienes que asegurarte de que el path para `/users/me` sea declarado antes que el path para `/users/{user_id}`: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` De otra manera el path para `/users/{user_id}` coincidiría también con `/users/me` "pensando" que está recibiendo el parámetro `user_id` con el valor `"me"`. @@ -128,21 +140,27 @@ Al heredar desde `str` la documentación de la API podrá saber que los valores Luego crea atributos de clase con valores fijos, que serán los valores disponibles válidos: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! info "Información" - Las Enumerations (o enums) están disponibles en Python desde la versión 3.4. +/// info | Información -!!! tip "Consejo" - Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning. +Las Enumerations (o enums) están disponibles en Python desde la versión 3.4. + +/// + +/// tip | Consejo + +Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning. + +/// ### Declara un *parámetro de path* Luego, crea un *parámetro de path* con anotaciones de tipos usando la clase enum que creaste (`ModelName`): ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### Revisa la documentación @@ -160,7 +178,7 @@ El valor del *parámetro de path* será un *enumeration member*. Puedes compararlo con el *enumeration member* en el enum (`ModelName`) que creaste: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### Obtén el *enumeration value* @@ -168,11 +186,14 @@ Puedes compararlo con el *enumeration member* en el enum (`ModelName`) que creas Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value`, o en general, `your_enum_member.value`: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Consejo" - También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. +/// tip | Consejo + +También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. + +/// #### Devuelve *enumeration members* @@ -181,7 +202,7 @@ Puedes devolver *enum members* desde tu *operación de path* inclusive en un bod Ellos serán convertidos a sus valores correspondientes (strings en este caso) antes de devolverlos al cliente: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` En tu cliente obtendrás una respuesta en JSON como: @@ -222,13 +243,16 @@ En este caso el nombre del parámetro es `file_path` y la última parte, `:path` Entonces lo puedes usar con: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Consejo" - Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). +/// tip | Consejo + +Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). + +En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`. - En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`. +/// ## Repaso diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md index 482af8dc0..f9b5cf69d 100644 --- a/docs/es/docs/tutorial/query-params.md +++ b/docs/es/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Cuando declaras otros parámetros de la función que no hacen parte de los parámetros de path estos se interpretan automáticamente como parámetros de "query". ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` El query es el conjunto de pares de key-value que van después del `?` en la URL, separados por caracteres `&`. @@ -64,25 +64,31 @@ Los valores de los parámetros en tu función serán: Del mismo modo puedes declarar parámetros de query opcionales definiendo el valor por defecto como `None`: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} +{!../../docs_src/query_params/tutorial002.py!} ``` En este caso el parámetro de la función `q` será opcional y será `None` por defecto. -!!! check "Revisa" - También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. +/// check | Revisa -!!! note "Nota" - FastAPI sabrá que `q` es opcional por el `= None`. +También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. - El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código. +/// + +/// note | Nota + +FastAPI sabrá que `q` es opcional por el `= None`. + +El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código. + +/// ## Conversión de tipos de parámetros de query También puedes declarar tipos `bool` y serán convertidos: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} +{!../../docs_src/query_params/tutorial003.py!} ``` En este caso, si vas a: @@ -126,7 +132,7 @@ No los tienes que declarar en un orden específico. Serán detectados por nombre: ```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} +{!../../docs_src/query_params/tutorial004.py!} ``` ## Parámetros de query requeridos @@ -138,7 +144,7 @@ Si no quieres añadir un valor específico sino solo hacerlo opcional, pon el va Pero cuando quieres hacer que un parámetro de query sea requerido, puedes simplemente no declararle un valor por defecto: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Aquí el parámetro de query `needy` es un parámetro de query requerido, del tipo `str`. @@ -184,7 +190,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Por supuesto que también puedes definir algunos parámetros como requeridos, con un valor por defecto y otros completamente opcionales: ```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} +{!../../docs_src/query_params/tutorial006.py!} ``` En este caso hay 3 parámetros de query: @@ -193,5 +199,8 @@ En este caso hay 3 parámetros de query: * `skip`, un `int` con un valor por defecto de `0`. * `limit`, un `int` opcional. -!!! tip "Consejo" - También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#predefined-values){.internal-link target=_blank}. +/// tip | Consejo + +También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}. + +/// diff --git a/docs/fa/docs/advanced/sub-applications.md b/docs/fa/docs/advanced/sub-applications.md index f3a948414..5e4326776 100644 --- a/docs/fa/docs/advanced/sub-applications.md +++ b/docs/fa/docs/advanced/sub-applications.md @@ -13,7 +13,7 @@ ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### زیر برنامه @@ -23,7 +23,7 @@ این زیر برنامه فقط یکی دیگر از برنامه های استاندارد FastAPI است، اما این برنامه ای است که متصل می شود: ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### اتصال زیر برنامه @@ -31,7 +31,7 @@ در برنامه سطح بالا `app` اتصال زیر برنامه `subapi` در این نمونه `/subapi` در مسیر قرار میدهد و میشود: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### اسناد API خودکار را بررسی کنید @@ -69,4 +69,4 @@ $ uvicorn main:app --reload و زیر برنامه ها نیز می تواند زیر برنامه های متصل شده خود را داشته باشد و همه چیز به درستی کار کند، زیرا FastAPI تمام این مسیرهای `root_path` را به طور خودکار مدیریت می کند. -در بخش [پشت پراکسی](./behind-a-proxy.md){.internal-link target=_blank}. درباره `root_path` و نحوه استفاده درست از آن بیشتر خواهید آموخت. +در بخش [پشت پراکسی](behind-a-proxy.md){.internal-link target=_blank}. درباره `root_path` و نحوه استفاده درست از آن بیشتر خواهید آموخت. diff --git a/docs/fa/docs/features.md b/docs/fa/docs/features.md index 58c34b7fc..a5ab1597e 100644 --- a/docs/fa/docs/features.md +++ b/docs/fa/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` یعنی: +/// info - کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` یعنی: + +کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### پشتیبانی ویرایشگر diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index e5231ec8d..6addce763 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ فریم‌ورک FastAPI، کارایی بالا، یادگیری آسان، کدنویسی سریع، آماده برای استفاده در محیط پروداکشن

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,14 +29,14 @@ **مستندات**: https://fastapi.tiangolo.com -**کد منبع**: https://github.com/tiangolo/fastapi +**کد منبع**: https://github.com/fastapi/fastapi --- FastAPI یک وب فریم‌ورک مدرن و سریع (با کارایی بالا) برای ایجاد APIهای متنوع (وب، وب‌سوکت و غبره) با زبان پایتون نسخه +۳.۶ است. این فریم‌ورک با رعایت کامل راهنمای نوع داده (Type Hint) ایجاد شده است. ویژگی‌های کلیدی این فریم‌ورک عبارتند از: -* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریع‌ترین فریم‌ورک‌های پایتونی موجود](#performance). +* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریع‌ترین فریم‌ورک‌های پایتونی موجود](#_10). * **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه قابلیت‌های جدید. * * **باگ کمتر**: کاهش ۴۰ درصدی خطاهای انسانی (برنامه‌نویسی). * @@ -60,7 +66,7 @@ FastAPI یک وب فریم‌ورک مدرن و سریع (با کارایی با

[...] I'm using FastAPI a ton these days. [...] I'm actually planning to use it for all of my team's ML services at Microsoft. Some of them are getting integrated into the core Windows product and some Office products."
-
Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -84,7 +90,7 @@ FastAPI یک وب فریم‌ورک مدرن و سریع (با کارایی با
"Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted Hug to be - it's really inspiring to see someone build that."
-
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -125,7 +131,7 @@ $ pip install fastapi
-نصب یک سرور پروداکشن نظیر Uvicorn یا Hypercorn نیز جزء نیازمندی‌هاست. +نصب یک سرور پروداکشن نظیر Uvicorn یا Hypercorn نیز جزء نیازمندی‌هاست.
@@ -436,7 +442,7 @@ item: Item استفاده شده توسط Pydantic: -* email_validator - برای اعتبارسنجی آدرس‌های ایمیل. +* email-validator - برای اعتبارسنجی آدرس‌های ایمیل. استفاده شده توسط Starlette: @@ -447,12 +453,12 @@ item: Item * itsdangerous - در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید. * pyyaml - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمی‌کنید). * graphene - در صورتی که از `GraphQLApp` پشتیبانی می‌کنید. -* ujson - در صورتی که بخواهید از `UJSONResponse` استفاده کنید. استفاده شده توسط FastAPI / Starlette: * uvicorn - برای سرور اجرا کننده برنامه وب. * orjson - در صورتی که بخواهید از `ORJSONResponse` استفاده کنید. +* ujson - در صورتی که بخواهید از `UJSONResponse` استفاده کنید. می‌توان همه این موارد را با استفاده از دستور `pip install fastapi[all]`. به صورت یکجا نصب کرد. diff --git a/docs/fa/docs/tutorial/middleware.md b/docs/fa/docs/tutorial/middleware.md index c5752a4b5..a3ab483fb 100644 --- a/docs/fa/docs/tutorial/middleware.md +++ b/docs/fa/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند. * سپس **پاسخ** را برمی گرداند. -!!! توجه "جزئیات فنی" - در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میان‌‌افزار اجرا خواهد شد. +/// توجه | جزئیات فنی - در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده می‌شوند)، تمام میان‌افزارها *پس از آن* اجرا خواهند شد. +در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میان‌‌افزار اجرا خواهد شد. + +در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده می‌شوند)، تمام میان‌افزارها *پس از آن* اجرا خواهند شد. + +/// ## ساخت یک میان افزار @@ -28,17 +31,22 @@ * شما می‌توانید سپس `پاسخ` را تغییر داده و پس از آن را برگردانید. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` -!!! نکته به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد. +/// نکته | به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد. + +اما اگر هدرهای سفارشی دارید که می‌خواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید. + +/// + +/// توجه | جزئیات فنی - اما اگر هدرهای سفارشی دارید که می‌خواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید. +شما همچنین می‌توانید از `from starlette.requests import Request` استفاده کنید. -!!! توجه "جزئیات فنی" - شما همچنین می‌توانید از `from starlette.requests import Request` استفاده کنید. +**FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامه‌نویس فراهم می‌کند. اما این مستقیما از Starlette به دست می‌آید. - **FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامه‌نویس فراهم می‌کند. اما این مستقیما از Starlette به دست می‌آید. +/// ### قبل و بعد از `پاسخ` @@ -49,7 +57,7 @@ به عنوان مثال، می‌توانید یک هدر سفارشی به نام `X-Process-Time` که شامل زمان پردازش درخواست و تولید پاسخ به صورت ثانیه است، اضافه کنید. ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## سایر میان افزار diff --git a/docs/fa/docs/tutorial/security/index.md b/docs/fa/docs/tutorial/security/index.md index 4e68ba961..c0827a8b3 100644 --- a/docs/fa/docs/tutorial/security/index.md +++ b/docs/fa/docs/tutorial/security/index.md @@ -33,8 +33,11 @@ پروتکل استاندارد OAuth2 روش رمزگذاری ارتباط را مشخص نمی کند، بلکه انتظار دارد که برنامه شما با HTTPS سرویس دهی شود. -!!! نکته - در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید. +/// نکته + +در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید. + +/// ## استاندارد OpenID Connect @@ -86,10 +89,13 @@ * شیوه `openIdConnect`: یک روش برای تعریف نحوه کشف داده‌های احراز هویت OAuth2 به صورت خودکار. * کشف خودکار این موضوع را که در مشخصه OpenID Connect تعریف شده است، مشخص می‌کند. -!!! نکته - ادغام سایر ارائه‌دهندگان احراز هویت/اجازه‌دهی مانند گوگل، فیسبوک، توییتر، گیت‌هاب و غیره نیز امکان‌پذیر و نسبتاً آسان است. +/// نکته + +ادغام سایر ارائه‌دهندگان احراز هویت/اجازه‌دهی مانند گوگل، فیسبوک، توییتر، گیت‌هاب و غیره نیز امکان‌پذیر و نسبتاً آسان است. + +مشکل پیچیده‌ترین مسئله، ساخت یک ارائه‌دهنده احراز هویت/اجازه‌دهی مانند آن‌ها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما می‌دهد و همه کارهای سنگین را برای شما انجام می‌دهد. - مشکل پیچیده‌ترین مسئله، ساخت یک ارائه‌دهنده احراز هویت/اجازه‌دهی مانند آن‌ها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما می‌دهد و همه کارهای سنگین را برای شما انجام می‌دهد. +/// ## ابزارهای **FastAPI** diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md index 35b57594d..38527aad3 100644 --- a/docs/fr/docs/advanced/additional-responses.md +++ b/docs/fr/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Réponses supplémentaires dans OpenAPI -!!! Attention - Ceci concerne un sujet plutôt avancé. +/// warning | Attention - Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin. +Ceci concerne un sujet plutôt avancé. + +Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin. + +/// Vous pouvez déclarer des réponses supplémentaires, avec des codes HTTP, des types de médias, des descriptions, etc. @@ -23,24 +26,28 @@ Chacun de ces `dict` de réponse peut avoir une clé `model`, contenant un modè Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un modèle Pydantic `Message`, vous pouvez écrire : -```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note | Remarque + +Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. + +/// + +/// info -!!! Remarque - Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. +La clé `model` ne fait pas partie d'OpenAPI. -!!! Info - La clé `model` ne fait pas partie d'OpenAPI. +**FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit. - **FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit. +Le bon endroit est : - Le bon endroit est : +* Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient : + * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient : + * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit. + * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc. - * Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient : - * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient : - * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit. - * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc. +/// Les réponses générées au format OpenAPI pour cette *opération de chemin* seront : @@ -168,17 +175,21 @@ Vous pouvez utiliser ce même paramètre `responses` pour ajouter différents ty Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, en déclarant que votre *opération de chemin* peut renvoyer un objet JSON (avec le type de média `application/json`) ou une image PNG : -```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note | Remarque + +Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. + +/// -!!! Remarque - Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. +/// info -!!! Info - À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`). +À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`). - Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle. +Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle. + +/// ## Combinaison d'informations @@ -192,9 +203,7 @@ Par exemple, vous pouvez déclarer une réponse avec un code HTTP `404` qui util Et une réponse avec un code HTTP `200` qui utilise votre `response_model`, mais inclut un `example` personnalisé : -```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} Tout sera combiné et inclus dans votre OpenAPI, et affiché dans la documentation de l'API : @@ -206,7 +215,7 @@ Vous voulez peut-être avoir des réponses prédéfinies qui s'appliquent à de Dans ces cas, vous pouvez utiliser la technique Python "d'affection par décomposition" (appelé _unpacking_ en anglais) d'un `dict` avec `**dict_to_unpack` : -``` Python +```Python old_dict = { "old key": "old value", "second old key": "second old value", @@ -216,7 +225,7 @@ new_dict = {**old_dict, "new key": "new value"} Ici, `new_dict` contiendra toutes les paires clé-valeur de `old_dict` plus la nouvelle paire clé-valeur : -``` Python +```Python { "old key": "old value", "second old key": "second old value", @@ -228,9 +237,7 @@ Vous pouvez utiliser cette technique pour réutiliser certaines réponses préd Par exemple: -```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## Plus d'informations sur les réponses OpenAPI diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md index e7b003707..c406ae8cb 100644 --- a/docs/fr/docs/advanced/additional-status-codes.md +++ b/docs/fr/docs/advanced/additional-status-codes.md @@ -15,20 +15,26 @@ Mais vous voulez aussi qu'il accepte de nouveaux éléments. Et lorsque les él Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu, en définissant le `status_code` que vous souhaitez : ```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} +{!../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! Attention - Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. +/// warning | Attention - Elle ne sera pas sérialisée avec un modèle. +Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. - Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`). +Elle ne sera pas sérialisée avec un modèle. -!!! note "Détails techniques" - Vous pouvez également utiliser `from starlette.responses import JSONResponse`. +Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`). - Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`. +/// + +/// note | Détails techniques + +Vous pouvez également utiliser `from starlette.responses import JSONResponse`. + +Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`. + +/// ## Documents OpenAPI et API diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md index aa37f1806..d9d8ad8e6 100644 --- a/docs/fr/docs/advanced/index.md +++ b/docs/fr/docs/advanced/index.md @@ -6,10 +6,13 @@ Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link targ Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires. -!!! Note - Les sections de ce chapitre ne sont **pas nécessairement "avancées"**. +/// note | Remarque - Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux. +Les sections de ce chapitre ne sont **pas nécessairement "avancées"**. + +Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux. + +/// ## Lisez d'abord le didacticiel diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md index 7ded97ce1..7daf0fc65 100644 --- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md @@ -2,16 +2,17 @@ ## ID d'opération OpenAPI -!!! Attention - Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin. +/// warning | Attention + +Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin. + +/// Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`. Vous devez vous assurer qu'il est unique pour chaque opération. -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Utilisation du nom *path operation function* comme operationId @@ -19,25 +20,27 @@ Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`, Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*. -```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} + +/// tip | Astuce -!!! Astuce - Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant. +Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant. -!!! Attention - Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique. +/// - Même s'ils se trouvent dans des modules différents (fichiers Python). +/// warning | Attention + +Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique. + +Même s'ils se trouvent dans des modules différents (fichiers Python). + +/// ## Exclusion d'OpenAPI Pour exclure un *chemin* du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et assignez-lui la valeur `False` : -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Description avancée de docstring @@ -47,9 +50,7 @@ L'ajout d'un `\f` (un caractère d'échappement "form feed") va permettre à **F Il n'apparaîtra pas dans la documentation, mais d'autres outils (tel que Sphinx) pourront utiliser le reste. -```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## Réponses supplémentaires @@ -59,14 +60,17 @@ Cela définit les métadonnées sur la réponse principale d'une *opération de Vous pouvez également déclarer des réponses supplémentaires avec leurs modèles, codes de statut, etc. -Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}. +Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. ## OpenAPI supplémentaire Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI. -!!! note "Détails techniques" - La spécification OpenAPI appelle ces métadonnées des Objets d'opération. +/// note | Détails techniques + +La spécification OpenAPI appelle ces métadonnées des Objets d'opération. + +/// Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation. @@ -74,8 +78,11 @@ Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc. Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre. -!!! Astuce - Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}. +/// tip | Astuce + +Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`. @@ -83,9 +90,7 @@ Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utili Cet `openapi_extra` peut être utile, par exemple, pour déclarer [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) : -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} Si vous ouvrez la documentation automatique de l'API, votre extension apparaîtra au bas du *chemin* spécifique. @@ -132,9 +137,7 @@ Par exemple, vous pouvez décider de lire et de valider la requête avec votre p Vous pouvez le faire avec `openapi_extra` : -```Python hl_lines="20-37 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py !} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} Dans cet exemple, nous n'avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n'est même pas parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre. @@ -148,9 +151,7 @@ Et vous pouvez le faire même si le type de données dans la requête n'est pas Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON : -```Python hl_lines="17-22 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML. @@ -158,11 +159,12 @@ Ensuite, nous utilisons directement la requête et extrayons son contenu en tant Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML : -```Python hl_lines="26-33" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} + +/// tip | Astuce + +Ici, nous réutilisons le même modèle Pydantic. -!!! Astuce - Ici, nous réutilisons le même modèle Pydantic. +Mais nous aurions pu tout aussi bien pu le valider d'une autre manière. - Mais nous aurions pu tout aussi bien pu le valider d'une autre manière. +/// diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md index 1c923fb82..4ff883c77 100644 --- a/docs/fr/docs/advanced/response-directly.md +++ b/docs/fr/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci. -!!! Note - `JSONResponse` est elle-même une sous-classe de `Response`. +/// note | Remarque + +`JSONResponse` est elle-même une sous-classe de `Response`. + +/// Et quand vous retournez une `Response`, **FastAPI** la transmet directement. @@ -31,14 +34,15 @@ Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONRespons Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convertir vos données avant de les passer à une réponse : -```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | Détails techniques + +Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`. -!!! note "Détails techniques" - Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`. +**FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette. - **FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette. +/// ## Renvoyer une `Response` personnalisée @@ -50,9 +54,7 @@ Disons que vous voulez retourner une réponse Flask Flask est un "micro-framework", il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django. @@ -59,11 +65,14 @@ qui est nécessaire, était une caractéristique clé que je voulais conserver. Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un "Django REST Framework" pour Flask. -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Être un micro-framework. Il est donc facile de combiner les outils et les pièces nécessaires. Proposer un système de routage simple et facile à utiliser. +/// + ### Requests **FastAPI** n'est pas réellement une alternative à **Requests**. Leur cadre est très différent. @@ -98,9 +107,13 @@ def read_url(): Notez les similitudes entre `requests.get(...)` et `@app.get(...)`. -!!! check "A inspiré **FastAPI** à" -_ Avoir une API simple et intuitive. -_ Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes. +/// check | A inspiré **FastAPI** à + +Avoir une API simple et intuitive. + +Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes. + +/// ### Swagger / OpenAPI @@ -115,15 +128,18 @@ Swagger pour une API permettrait d'utiliser cette interface utilisateur web auto C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire "Swagger", et pour la version 3+ "OpenAPI". -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Adopter et utiliser une norme ouverte pour les spécifications des API, au lieu d'un schéma personnalisé. - Intégrer des outils d'interface utilisateur basés sur des normes : +Intégrer des outils d'interface utilisateur basés sur des normes : - * Swagger UI - * ReDoc +* Swagger UI +* ReDoc - Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**). +Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**). + +/// ### Frameworks REST pour Flask @@ -150,9 +166,12 @@ Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une e Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation. +/// + ### Webargs Une autre grande fonctionnalité requise par les API est le APISpec Marshmallow et Webargs fournissent la validation, l'analyse et la sérialisation en tant que plug-ins. @@ -188,12 +213,18 @@ Mais alors, nous avons à nouveau le problème d'avoir une micro-syntaxe, dans u L'éditeur ne peut guère aider en la matière. Et si nous modifions les paramètres ou les schémas Marshmallow et que nous oublions de modifier également cette docstring YAML, le schéma généré deviendrait obsolète. -!!! info +/// info + APISpec a été créé par les développeurs de Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | A inspiré **FastAPI** à + Supporter la norme ouverte pour les API, OpenAPI. +/// + ### Flask-apispec C'est un plug-in pour Flask, qui relie Webargs, Marshmallow et APISpec. @@ -215,12 +246,18 @@ j'ai (ainsi que plusieurs équipes externes) utilisées jusqu'à présent : Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md){.internal-link target=\_blank}. -!!! info +/// info + Flask-apispec a été créé par les développeurs de Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | A inspiré **FastAPI** à + Générer le schéma OpenAPI automatiquement, à partir du même code qui définit la sérialisation et la validation. +/// + ### NestJS (et Angular) Ce n'est même pas du Python, NestJS est un framework JavaScript (TypeScript) NodeJS inspiré d'Angular. @@ -236,24 +273,33 @@ Mais comme les données TypeScript ne sont pas préservées après la compilatio Il ne peut pas très bien gérer les modèles imbriqués. Ainsi, si le corps JSON de la requête est un objet JSON comportant des champs internes qui sont à leur tour des objets JSON imbriqués, il ne peut pas être correctement documenté et validé. -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Utiliser les types Python pour bénéficier d'un excellent support de l'éditeur. - Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code. +Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code. + +/// ### Sanic C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask. -!!! note "Détails techniques" +/// note | Détails techniques + Il utilisait `uvloop` au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide. - Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks. +Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks. + +/// + +/// check | A inspiré **FastAPI** à -!!! check "A inspiré **FastAPI** à" Trouvez un moyen d'avoir une performance folle. - C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers). +C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers). + +/// ### Falcon @@ -267,12 +313,15 @@ pas possible de déclarer des paramètres de requête et des corps avec des indi Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres. -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Trouver des moyens d'obtenir de bonnes performances. - Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions. +Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions. + +Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs. - Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs. +/// ### Molten @@ -294,12 +343,15 @@ d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonc méthode est plus proche de celle de Django que de celle de Flask (et Starlette). Il sépare dans le code des choses qui sont relativement fortement couplées. -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant. - Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic). +Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic). + +/// -### Hug +### Hug Hug a été l'un des premiers frameworks à implémenter la déclaration des types de paramètres d'API en utilisant les type hints Python. C'était une excellente idée qui a inspiré d'autres outils à faire de même. @@ -314,16 +366,22 @@ API et des CLI. Comme il est basé sur l'ancienne norme pour les frameworks web Python synchrones (WSGI), il ne peut pas gérer les Websockets et autres, bien qu'il soit également très performant. -!!! info +/// info + Hug a été créé par Timothy Crosley, le créateur de `isort`, un excellent outil pour trier automatiquement les imports dans les fichiers Python. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | A inspiré **FastAPI** à + Hug a inspiré certaines parties d'APIStar, et était l'un des outils que je trouvais les plus prometteurs, à côté d'APIStar. - Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python - pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API. +Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python +pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API. + +Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies. - Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies. +/// ### APIStar (<= 0.5) @@ -351,23 +409,29 @@ Il ne s'agissait plus d'un framework web API, le créateur devant se concentrer Maintenant, APIStar est un ensemble d'outils pour valider les spécifications OpenAPI, et non un framework web. -!!! info +/// info + APIStar a été créé par Tom Christie. Le même gars qui a créé : - * Django REST Framework - * Starlette (sur lequel **FastAPI** est basé) - * Uvicorn (utilisé par Starlette et **FastAPI**) +* Django REST Framework +* Starlette (sur lequel **FastAPI** est basé) +* Uvicorn (utilisé par Starlette et **FastAPI**) + +/// + +/// check | A inspiré **FastAPI** à -!!! check "A inspiré **FastAPI** à" Exister. - L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante. +L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante. - Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible. +Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible. - Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**. +Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**. - Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents. +Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents. + +/// ## Utilisés par **FastAPI** @@ -380,10 +444,13 @@ Cela le rend extrêmement intuitif. Il est comparable à Marshmallow. Bien qu'il soit plus rapide que Marshmallow dans les benchmarks. Et comme il est basé sur les mêmes type hints Python, le support de l'éditeur est grand. -!!! check "**FastAPI** l'utilise pour" +/// check | **FastAPI** l'utilise pour + Gérer toute la validation des données, leur sérialisation et la documentation automatique du modèle (basée sur le schéma JSON). - **FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait. +**FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait. + +/// ### Starlette @@ -413,17 +480,23 @@ Mais il ne fournit pas de validation automatique des données, de sérialisation C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les type hints Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc. -!!! note "Détails techniques" +/// note | Détails techniques + ASGI est une nouvelle "norme" développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une "norme Python" (un PEP), bien qu'ils soient en train de le faire. - Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`. +Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`. + +/// + +/// check | **FastAPI** l'utilise pour -!!! check "**FastAPI** l'utilise pour" Gérer toutes les parties web de base. Ajouter des fonctionnalités par-dessus. - La classe `FastAPI` elle-même hérite directement de la classe `Starlette`. +La classe `FastAPI` elle-même hérite directement de la classe `Starlette`. - Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes. +Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes. + +/// ### Uvicorn @@ -434,12 +507,15 @@ quelque chose qu'un framework comme Starlette (ou **FastAPI**) fournirait par-de C'est le serveur recommandé pour Starlette et **FastAPI**. -!!! check "**FastAPI** le recommande comme" +/// check | **FastAPI** le recommande comme + Le serveur web principal pour exécuter les applications **FastAPI**. - Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone. +Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone. + +Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}. - Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}. +/// ## Benchmarks et vitesse diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md index 3f65032fe..0ff5fa5d1 100644 --- a/docs/fr/docs/async.md +++ b/docs/fr/docs/async.md @@ -20,8 +20,11 @@ async def read_results(): return results ``` -!!! note - Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`. +/// note + +Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`. + +/// --- @@ -103,24 +106,44 @@ Pour expliquer la différence, voici une histoire de burgers : Vous amenez votre crush 😍 dans votre fast food 🍔 favori, et faites la queue pendant que le serveur 💁 prend les commandes des personnes devant vous. + + Puis vient votre tour, vous commandez alors 2 magnifiques burgers 🍔 pour votre crush 😍 et vous. -Vous payez 💸. + Le serveur 💁 dit quelque chose à son collègue dans la cuisine 👨‍🍳 pour qu'il sache qu'il doit préparer vos burgers 🍔 (bien qu'il soit déjà en train de préparer ceux des clients précédents). + + +Vous payez 💸. + Le serveur 💁 vous donne le numéro assigné à votre commande. + + Pendant que vous attendez, vous allez choisir une table avec votre crush 😍, vous discutez avec votre crush 😍 pendant un long moment (les burgers étant "magnifiques" ils sont très longs à préparer ✨🍔✨). Pendant que vous êtes assis à table, en attendant que les burgers 🍔 soient prêts, vous pouvez passer ce temps à admirer à quel point votre crush 😍 est géniale, mignonne et intelligente ✨😍✨. + + Pendant que vous discutez avec votre crush 😍, de temps en temps vous jetez un coup d'oeil au nombre affiché au-dessus du comptoir pour savoir si c'est à votre tour d'être servis. Jusqu'au moment où c'est (enfin) votre tour. Vous allez au comptoir, récupérez vos burgers 🍔 et revenez à votre table. + + Vous et votre crush 😍 mangez les burgers 🍔 et passez un bon moment ✨. + + +/// info + +Illustrations proposées par Ketrina Thompson. 🎨 + +/// + --- Imaginez que vous êtes l'ordinateur / le programme 🤖 dans cette histoire. @@ -149,26 +172,44 @@ Vous attendez pendant que plusieurs (disons 8) serveurs qui sont aussi des cuisi Chaque personne devant vous attend 🕙 que son burger 🍔 soit prêt avant de quitter le comptoir car chacun des 8 serveurs va lui-même préparer le burger directement avant de prendre la commande suivante. + + Puis c'est enfin votre tour, vous commandez 2 magnifiques burgers 🍔 pour vous et votre crush 😍. Vous payez 💸. + + Le serveur va dans la cuisine 👨‍🍳. Vous attendez devant le comptoir afin que personne ne prenne vos burgers 🍔 avant vous, vu qu'il n'y a pas de numéro de commande. + + Vous et votre crush 😍 étant occupés à vérifier que personne ne passe devant vous prendre vos burgers au moment où ils arriveront 🕙, vous ne pouvez pas vous préoccuper de votre crush 😞. C'est du travail "synchrone", vous être "synchronisés" avec le serveur/cuisinier 👨‍🍳. Vous devez attendre 🕙 et être présent au moment exact où le serveur/cuisinier 👨‍🍳 finira les burgers 🍔 et vous les donnera, sinon quelqu'un risque de vous les prendre. + + Puis le serveur/cuisinier 👨‍🍳 revient enfin avec vos burgers 🍔, après un long moment d'attente 🕙 devant le comptoir. + + Vous prenez vos burgers 🍔 et allez à une table avec votre crush 😍 Vous les mangez, et vous avez terminé 🍔 ⏹. + + Durant tout ce processus, il n'y a presque pas eu de discussions ou de flirts car la plupart de votre temps à été passé à attendre 🕙 devant le comptoir 😞. +/// info + +Illustrations proposées par Ketrina Thompson. 🎨 + +/// + --- Dans ce scénario de burgers parallèles, vous êtes un ordinateur / programme 🤖 avec deux processeurs (vous et votre crush 😍) attendant 🕙 à deux et dédiant votre attention 🕙 à "attendre devant le comptoir" pour une longue durée. @@ -352,12 +393,15 @@ Tout ceci est donc ce qui donne sa force à **FastAPI** (à travers Starlette) e ## Détails très techniques -!!! warning "Attention !" - Vous pouvez probablement ignorer cela. +/// warning | Attention ! + +Vous pouvez probablement ignorer cela. + +Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan. - Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan. +Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous. - Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous. +/// ### Fonctions de chemin diff --git a/docs/fr/docs/contributing.md b/docs/fr/docs/contributing.md index 8292f14bb..408958339 100644 --- a/docs/fr/docs/contributing.md +++ b/docs/fr/docs/contributing.md @@ -24,72 +24,85 @@ Cela va créer un répertoire `./env/` avec les binaires Python et vous pourrez Activez le nouvel environnement avec : -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
+ +//// - Ou si vous utilisez Bash pour Windows (par exemple Git Bash): +//// tab | Windows Bash -
+Ou si vous utilisez Bash pour Windows (par exemple Git Bash): - ```console - $ source ./env/Scripts/activate - ``` +
-
+```console +$ source ./env/Scripts/activate +``` + +
+ +//// Pour vérifier que cela a fonctionné, utilisez : -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which pip -
+some/directory/fastapi/env/bin/pip +``` - ```console - $ which pip +
- some/directory/fastapi/env/bin/pip - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +$ Get-Command pip - ```console - $ Get-Command pip +some/directory/fastapi/env/bin/pip +``` - some/directory/fastapi/env/bin/pip - ``` +
-
+//// Si celui-ci montre le binaire `pip` à `env/bin/pip`, alors ça a fonctionné. 🎉 -!!! tip - Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement. +/// tip - Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement. +Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement. + +Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement. + +/// ### Flit @@ -111,31 +124,35 @@ Réactivez maintenant l'environnement pour vous assurer que vous utilisez le "fl Et maintenant, utilisez `flit` pour installer les dépendances de développement : -=== "Linux, macOS" +//// tab | Linux, macOS + +
+ +```console +$ flit install --deps develop --symlink -
+---> 100% +``` - ```console - $ flit install --deps develop --symlink +
- ---> 100% - ``` +//// -
+//// tab | Windows -=== "Windows" +Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` : - Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` : +
-
+```console +$ flit install --deps develop --pth-file - ```console - $ flit install --deps develop --pth-file +---> 100% +``` - ---> 100% - ``` +
-
+//// Il installera toutes les dépendances et votre FastAPI local dans votre environnement local. @@ -185,8 +202,11 @@ La documentation utilise pull requests existantes pour votre langue et ajouter des reviews demandant des changements ou les approuvant. +* Vérifiez les pull requests existantes pour votre langue et ajouter des reviews demandant des changements ou les approuvant. + +/// tip + +Vous pouvez ajouter des commentaires avec des suggestions de changement aux pull requests existantes. -!!! tip - Vous pouvez ajouter des commentaires avec des suggestions de changement aux pull requests existantes. +Consultez les documents concernant l'ajout d'un review de pull request pour l'approuver ou demander des modifications. - Consultez les documents concernant l'ajout d'un review de pull request pour l'approuver ou demander des modifications. +/// -* Vérifiez dans issues pour voir s'il y a une personne qui coordonne les traductions pour votre langue. +* Vérifiez dans issues pour voir s'il y a une personne qui coordonne les traductions pour votre langue. * Ajoutez une seule pull request par page traduite. Il sera ainsi beaucoup plus facile pour les autres de l'examiner. @@ -296,8 +319,11 @@ Disons que vous voulez traduire une page pour une langue qui a déjà des traduc Dans le cas de l'espagnol, le code à deux lettres est `es`. Ainsi, le répertoire des traductions espagnoles se trouve à l'adresse `docs/es/`. -!!! tip - La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/". +/// tip + +La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/". + +/// Maintenant, lancez le serveur en live pour les documents en espagnol : @@ -334,8 +360,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`. +/// tip + +Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`. + +/// * Ouvrez maintenant le fichier de configuration de MkDocs pour l'anglais à @@ -406,10 +435,13 @@ Updating en Vous pouvez maintenant vérifier dans votre éditeur de code le répertoire nouvellement créé `docs/ht/`. -!!! tip - Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions. +/// tip + +Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions. + +Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀 - Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀 +/// Commencez par traduire la page principale, `docs/ht/index.md`. diff --git a/docs/fr/docs/deployment/docker.md b/docs/fr/docs/deployment/docker.md index d2dcae722..05b597a2d 100644 --- a/docs/fr/docs/deployment/docker.md +++ b/docs/fr/docs/deployment/docker.md @@ -17,8 +17,11 @@ Cette image est dotée d'un mécanisme d'"auto-tuning", de sorte qu'il vous suff Mais vous pouvez toujours changer et mettre à jour toutes les configurations avec des variables d'environnement ou des fichiers de configuration. -!!! tip "Astuce" - Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : tiangolo/uvicorn-gunicorn-fastapi. +/// tip | Astuce + +Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : tiangolo/uvicorn-gunicorn-fastapi. + +/// ## Créer un `Dockerfile` diff --git a/docs/fr/docs/deployment/https.md b/docs/fr/docs/deployment/https.md index ccf1f847a..3f7068ff0 100644 --- a/docs/fr/docs/deployment/https.md +++ b/docs/fr/docs/deployment/https.md @@ -4,8 +4,11 @@ Il est facile de penser que HTTPS peut simplement être "activé" ou non. Mais c'est beaucoup plus complexe que cela. -!!! tip - Si vous êtes pressé ou si cela ne vous intéresse pas, passez aux sections suivantes pour obtenir des instructions étape par étape afin de tout configurer avec différentes techniques. +/// tip + +Si vous êtes pressé ou si cela ne vous intéresse pas, passez aux sections suivantes pour obtenir des instructions étape par étape afin de tout configurer avec différentes techniques. + +/// Pour apprendre les bases du HTTPS, du point de vue d'un utilisateur, consultez https://howhttps.works/. diff --git a/docs/fr/docs/deployment/manually.md b/docs/fr/docs/deployment/manually.md index c53e2db67..7c29242a9 100644 --- a/docs/fr/docs/deployment/manually.md +++ b/docs/fr/docs/deployment/manually.md @@ -5,7 +5,7 @@ La principale chose dont vous avez besoin pour exécuter une application **FastA Il existe 3 principales alternatives : * Uvicorn : un serveur ASGI haute performance. -* Hypercorn : un serveur +* Hypercorn : un serveur ASGI compatible avec HTTP/2 et Trio entre autres fonctionnalités. * Daphne : le serveur ASGI conçu pour Django Channels. @@ -25,75 +25,89 @@ Lorsqu'on se réfère à la machine distante, il est courant de l'appeler **serv Vous pouvez installer un serveur compatible ASGI avec : -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools. +* Uvicorn, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools. -
+
+ +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +
- ---> 100% - ``` +/// tip | Astuce -
+En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées. - !!! tip "Astuce" - En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées. +Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence. - Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence. +/// -=== "Hypercorn" +//// - * Hypercorn, un serveur ASGI également compatible avec HTTP/2. +//// tab | Hypercorn -
+* Hypercorn, un serveur ASGI également compatible avec HTTP/2. - ```console - $ pip install hypercorn +
+ +```console +$ pip install hypercorn + +---> 100% +``` - ---> 100% - ``` +
-
+...ou tout autre serveur ASGI. - ...ou tout autre serveur ASGI. +//// ## Exécutez le programme serveur Vous pouvez ensuite exécuter votre application de la même manière que vous l'avez fait dans les tutoriels, mais sans l'option `--reload`, par exemple : -=== "Uvicorn" +//// tab | Uvicorn -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
+ +//// -=== "Hypercorn" +//// tab | Hypercorn -
+
+ +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning -
+N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez. -!!! warning - N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez. + L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc. - L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc. + Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**. - Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**. +/// ## Hypercorn avec Trio diff --git a/docs/fr/docs/deployment/versions.md b/docs/fr/docs/deployment/versions.md index 136165e9d..9d84274e2 100644 --- a/docs/fr/docs/deployment/versions.md +++ b/docs/fr/docs/deployment/versions.md @@ -48,8 +48,11 @@ des changements non rétrocompatibles. FastAPI suit également la convention que tout changement de version "PATCH" est pour des corrections de bogues et des changements rétrocompatibles. -!!! tip "Astuce" - Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`. +/// tip | Astuce + +Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`. + +/// Donc, vous devriez être capable d'épingler une version comme suit : @@ -59,8 +62,11 @@ fastapi>=0.45.0,<0.46.0 Les changements non rétrocompatibles et les nouvelles fonctionnalités sont ajoutés dans les versions "MINOR". -!!! tip "Astuce" - Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`. +/// tip | Astuce + +Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`. + +/// ## Mise à jour des versions FastAPI diff --git a/docs/fr/docs/external-links.md b/docs/fr/docs/external-links.md deleted file mode 100644 index 37b8c5b13..000000000 --- a/docs/fr/docs/external-links.md +++ /dev/null @@ -1,33 +0,0 @@ -# Articles et liens externes - -**FastAPI** possède une grande communauté en constante extension. - -Il existe de nombreux articles, outils et projets liés à **FastAPI**. - -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. - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projets - -Les projets Github avec le topic `fastapi` les plus récents : - -
-
diff --git a/docs/fr/docs/fastapi-people.md b/docs/fr/docs/fastapi-people.md deleted file mode 100644 index 275a9bd37..000000000 --- a/docs/fr/docs/fastapi-people.md +++ /dev/null @@ -1,175 +0,0 @@ -# La communauté FastAPI - -FastAPI a une communauté extraordinaire qui accueille des personnes de tous horizons. - -## Créateur - Mainteneur - -Salut! 👋 - -C'est moi : - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Réponses: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Je suis le créateur et le responsable de **FastAPI**. Vous pouvez en lire plus à ce sujet dans [Aide FastAPI - Obtenir de l'aide - Se rapprocher de l'auteur](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Mais ici, je veux vous montrer la communauté. - ---- - -**FastAPI** reçoit beaucoup de soutien de la part de la communauté. Et je tiens à souligner leurs contributions. - -Ce sont ces personnes qui : - -* [Aident les autres à résoudre des problèmes (questions) dans GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Créent des Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Review les Pull Requests, [particulièrement important pour les traductions](contributing.md#translations){.internal-link target=_blank}. - -Une salve d'applaudissements pour eux. 👏 🙇 - -## Utilisateurs les plus actifs le mois dernier - -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} au cours du dernier mois. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Questions répondues: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Experts - -Voici les **Experts FastAPI**. 🤓 - -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} depuis *toujours*. - -Ils ont prouvé qu'ils étaient des experts en aidant beaucoup d'autres personnes. ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Questions répondues: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Principaux contributeurs - -Ces utilisateurs sont les **Principaux contributeurs**. 👷 - -Ces utilisateurs ont [créé le plus grand nombre de demandes Pull Request](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} qui ont été *merged*. - -Ils ont contribué au code source, à la documentation, aux traductions, etc. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Il existe de nombreux autres contributeurs (plus d'une centaine), vous pouvez les voir tous dans la Page des contributeurs de FastAPI GitHub. 👷 - -## Principaux Reviewers - -Ces utilisateurs sont les **Principaux Reviewers**. 🕵️ - -### Reviewers des traductions - -Je ne parle que quelques langues (et pas très bien 😅). Ainsi, les reviewers sont ceux qui ont le [**pouvoir d'approuver les traductions**](contributing.md#translations){.internal-link target=_blank} de la documentation. Sans eux, il n'y aurait pas de documentation dans plusieurs autres langues. - ---- - -Les **Principaux Reviewers** 🕵️ ont examiné le plus grand nombre de demandes Pull Request des autres, assurant la qualité du code, de la documentation, et surtout, des **traductions**. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsors - -Ce sont les **Sponsors**. 😎 - -Ils soutiennent mon travail avec **FastAPI** (et d'autres) avec GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Gold Sponsors - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Silver Sponsors - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronze Sponsors - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} -### Individual Sponsors - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## À propos des données - détails techniques - -L'intention de cette page est de souligner l'effort de la communauté pour aider les autres. - -Notamment en incluant des efforts qui sont normalement moins visibles, et, dans de nombreux cas, plus difficile, comme aider d'autres personnes à résoudre des problèmes et examiner les Pull Requests de traduction. - -Les données sont calculées chaque mois, vous pouvez lire le code source ici. - -Je me réserve également le droit de mettre à jour l'algorithme, les sections, les seuils, etc. (juste au cas où 🤷). diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md index 1457df2a5..afb1de243 100644 --- a/docs/fr/docs/features.md +++ b/docs/fr/docs/features.md @@ -62,10 +62,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` signifie: +/// info - Utilise les clés et valeurs du dictionnaire `second_user_data` directement comme des arguments clé-valeur. C'est équivalent à: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` signifie: + +Utilise les clés et valeurs du dictionnaire `second_user_data` directement comme des arguments clé-valeur. C'est équivalent à: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Support d'éditeurs diff --git a/docs/fr/docs/help-fastapi.md b/docs/fr/docs/help-fastapi.md index 525c699f5..a365a8d3a 100644 --- a/docs/fr/docs/help-fastapi.md +++ b/docs/fr/docs/help-fastapi.md @@ -12,13 +12,13 @@ Il existe également plusieurs façons d'obtenir de l'aide. ## Star **FastAPI** sur GitHub -Vous pouvez "star" FastAPI dans GitHub (en cliquant sur le bouton étoile en haut à droite) : https://github.com/tiangolo/fastapi. ⭐️ +Vous pouvez "star" FastAPI dans GitHub (en cliquant sur le bouton étoile en haut à droite) : https://github.com/fastapi/fastapi. ⭐️ En ajoutant une étoile, les autres utilisateurs pourront la trouver plus facilement et constater qu'elle a déjà été utile à d'autres. ## Watch le dépôt GitHub pour les releases -Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : https://github.com/tiangolo/fastapi. 👀 +Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : https://github.com/fastapi/fastapi. 👀 Vous pouvez y sélectionner "Releases only". @@ -44,7 +44,7 @@ Vous pouvez : ## Tweeter sur **FastAPI** -Tweetez à propos de **FastAPI** et faites-moi savoir, ainsi qu'aux autres, pourquoi vous aimez ça. 🎉 +Tweetez à propos de **FastAPI** et faites-moi savoir, ainsi qu'aux autres, pourquoi vous aimez ça. 🎉 J'aime entendre parler de l'utilisation du **FastAPI**, de ce que vous avez aimé dedans, dans quel projet/entreprise l'utilisez-vous, etc. @@ -56,11 +56,11 @@ J'aime entendre parler de l'utilisation du **FastAPI**, de ce que vous avez aim ## Aider les autres à résoudre les problèmes dans GitHub -Vous pouvez voir les problèmes existants et essayer d'aider les autres, la plupart du temps il s'agit de questions dont vous connaissez peut-être déjà la réponse. 🤓 +Vous pouvez voir les problèmes existants et essayer d'aider les autres, la plupart du temps il s'agit de questions dont vous connaissez peut-être déjà la réponse. 🤓 ## Watch le dépôt GitHub -Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : https://github.com/tiangolo/fastapi. 👀 +Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : https://github.com/fastapi/fastapi. 👀 Si vous sélectionnez "Watching" au lieu de "Releases only", vous recevrez des notifications lorsque quelqu'un crée une nouvelle Issue. @@ -68,7 +68,7 @@ Vous pouvez alors essayer de les aider à résoudre ces problèmes. ## Créer une Issue -Vous pouvez créer une Issue dans le dépôt GitHub, par exemple pour : +Vous pouvez créer une Issue dans le dépôt GitHub, par exemple pour : * Poser une question ou s'informer sur un problème. * Suggérer une nouvelle fonctionnalité. @@ -77,7 +77,7 @@ Vous pouvez créer une Pull Request, par exemple : +Vous pouvez créer une Pull Request, par exemple : * Pour corriger une faute de frappe que vous avez trouvée sur la documentation. * Proposer de nouvelles sections de documentation. diff --git a/docs/fr/docs/history-design-future.md b/docs/fr/docs/history-design-future.md index beb649121..6b26dd079 100644 --- a/docs/fr/docs/history-design-future.md +++ b/docs/fr/docs/history-design-future.md @@ -1,6 +1,6 @@ # Histoire, conception et avenir -Il y a quelque temps, un utilisateur de **FastAPI** a demandé : +Il y a quelque temps, un utilisateur de **FastAPI** a demandé : > Quelle est l'histoire de ce projet ? Il semble être sorti de nulle part et est devenu génial en quelques semaines [...]. diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index bc3ae3c06..695429008 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ Framework FastAPI, haute performance, facile à apprendre, rapide à coder, prêt pour la production

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +29,11 @@ **Documentation** : https://fastapi.tiangolo.com -**Code Source** : https://github.com/tiangolo/fastapi +**Code Source** : https://github.com/fastapi/fastapi --- -FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python 3.8+, basé sur les annotations de type standard de Python. +FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python, basé sur les annotations de type standard de Python. Les principales fonctionnalités sont : @@ -63,7 +69,7 @@ Les principales fonctionnalités sont : "_[...] J'utilise beaucoup **FastAPI** ces derniers temps. [...] Je prévois de l'utiliser dans mon équipe pour tous les **services de ML chez Microsoft**. Certains d'entre eux seront intégrés dans le coeur de **Windows** et dans certains produits **Office**._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -87,7 +93,7 @@ Les principales fonctionnalités sont : "_Honnêtement, ce que vous avez construit a l'air super solide et élégant. A bien des égards, c'est comme ça que je voulais que **Hug** soit - c'est vraiment inspirant de voir quelqu'un construire ça._" -
Timothy Crosley - Créateur de Hug (ref)
+
Timothy Crosley - Créateur de Hug (ref)
--- @@ -115,8 +121,6 @@ Si vous souhaitez construire une application Starlette pour les parties web. @@ -331,7 +335,7 @@ Vous faites cela avec les types Python standard modernes. Vous n'avez pas à apprendre une nouvelle syntaxe, les méthodes ou les classes d'une bibliothèque spécifique, etc. -Juste du **Python 3.8+** standard. +Juste du **Python** standard. Par exemple, pour un `int`: @@ -445,7 +449,7 @@ Pour en savoir plus, consultez la section email_validator - pour la validation des adresses email. +* email-validator - pour la validation des adresses email. Utilisées par Starlette : @@ -454,12 +458,12 @@ Utilisées par Starlette : * python-multipart - Obligatoire si vous souhaitez supporter le "décodage" de formulaire avec `request.form()`. * itsdangerous - Obligatoire pour la prise en charge de `SessionMiddleware`. * pyyaml - Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI). -* ujson - Obligatoire si vous souhaitez utiliser `UJSONResponse`. Utilisées par FastAPI / Starlette : * uvicorn - Pour le serveur qui charge et sert votre application. * orjson - Obligatoire si vous voulez utiliser `ORJSONResponse`. +* ujson - Obligatoire si vous souhaitez utiliser `UJSONResponse`. Vous pouvez tout installer avec `pip install fastapi[all]`. diff --git a/docs/fr/docs/learn/index.md b/docs/fr/docs/learn/index.md new file mode 100644 index 000000000..46fc095dc --- /dev/null +++ b/docs/fr/docs/learn/index.md @@ -0,0 +1,5 @@ +# Apprendre + +Voici les sections introductives et les tutoriels pour apprendre **FastAPI**. + +Vous pouvez considérer ceci comme un **manuel**, un **cours**, la **méthode officielle** et recommandée pour appréhender FastAPI. 😎 diff --git a/docs/fr/docs/project-generation.md b/docs/fr/docs/project-generation.md index c58d2cd2b..4c04dc167 100644 --- a/docs/fr/docs/project-generation.md +++ b/docs/fr/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub : Swarm * Intégration **Docker Compose** et optimisation pour développement local. * Serveur web Python **prêt au déploiement** utilisant Uvicorn et Gunicorn. -* Backend Python **FastAPI** : +* Backend Python **FastAPI** : * **Rapide** : Très hautes performances, comparables à **NodeJS** ou **Go** (grâce à Starlette et Pydantic). * **Intuitif** : Excellent support des éditeurs. Complétion partout. Moins de temps passé à déboguer. * **Facile** : Fait pour être facile à utiliser et apprendre. Moins de temps passé à lire de la documentation. diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md index 4232633e3..99ca90827 100644 --- a/docs/fr/docs/python-types.md +++ b/docs/fr/docs/python-types.md @@ -13,16 +13,17 @@ Seulement le minimum nécessaire pour les utiliser avec **FastAPI** sera couvert Mais même si vous n'utilisez pas ou n'utiliserez jamais **FastAPI**, vous pourriez bénéficier d'apprendre quelques choses sur ces dernières. -!!! note - Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant. +/// note + +Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant. + +/// ## Motivations Prenons un exemple simple : -```Python -{!../../../docs_src/python_types/tutorial001.py!} -``` +{*../../docs_src/python_types/tutorial001.py*} Exécuter ce programe affiche : @@ -36,9 +37,7 @@ La fonction : * Convertit la première lettre de chaque paramètre en majuscules grâce à `title()`. * Concatène les résultats avec un espace entre les deux. -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} -``` +{*../../docs_src/python_types/tutorial001.py hl[2] *} ### Limitations @@ -81,9 +80,7 @@ C'est tout. Ce sont des annotations de types : -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} -``` +{*../../docs_src/python_types/tutorial002.py hl[1] *} À ne pas confondre avec la déclaration de valeurs par défaut comme ici : @@ -111,9 +108,7 @@ Vous pouvez donc dérouler les options jusqu'à trouver la méthode à laquelle Cette fonction possède déjà des annotations de type : -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} -``` +{*../../docs_src/python_types/tutorial003.py hl[1] *} Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'auto-complétion, mais aussi de la détection d'erreurs : @@ -121,9 +116,7 @@ Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'aut Maintenant que vous avez connaissance du problème, convertissez `age` en chaîne de caractères grâce à `str(age)` : -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} -``` +{*../../docs_src/python_types/tutorial004.py hl[2] *} ## Déclarer des types @@ -142,9 +135,7 @@ Comme par exemple : * `bool` * `bytes` -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} -``` +{*../../docs_src/python_types/tutorial005.py hl[1] *} ### Types génériques avec des paramètres de types @@ -160,9 +151,7 @@ Par exemple, définissons une variable comme `list` de `str`. Importez `List` (avec un `L` majuscule) depuis `typing`. -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} -``` +{*../../docs_src/python_types/tutorial006.py hl[1] *} Déclarez la variable, en utilisant la syntaxe des deux-points (`:`). @@ -170,14 +159,15 @@ Et comme type, mettez `List`. Les listes étant un type contenant des types internes, mettez ces derniers entre crochets (`[`, `]`) : -```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} -``` +{*../../docs_src/python_types/tutorial006.py hl[4] *} + +/// tip | Astuce + +Ces types internes entre crochets sont appelés des "paramètres de type". -!!! tip "Astuce" - Ces types internes entre crochets sont appelés des "paramètres de type". +Ici, `str` est un paramètre de type passé à `List`. - Ici, `str` est un paramètre de type passé à `List`. +/// Ce qui signifie : "la variable `items` est une `list`, et chacun de ses éléments a pour type `str`. @@ -195,9 +185,7 @@ Et pourtant, l'éditeur sait qu'elle est de type `str` et pourra donc vous aider C'est le même fonctionnement pour déclarer un `tuple` ou un `set` : -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} -``` +{*../../docs_src/python_types/tutorial007.py hl[1,4] *} Dans cet exemple : @@ -210,9 +198,7 @@ Pour définir un `dict`, il faut lui passer 2 paramètres, séparés par une vir Le premier paramètre de type est pour les clés et le second pour les valeurs du dictionnaire (`dict`). -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} -``` +{*../../docs_src/python_types/tutorial008.py hl[1,4] *} Dans cet exemple : @@ -224,9 +210,7 @@ Dans cet exemple : Vous pouvez aussi utiliser `Optional` pour déclarer qu'une variable a un type, comme `str` mais qu'il est "optionnel" signifiant qu'il pourrait aussi être `None`. -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} -``` +{*../../docs_src/python_types/tutorial009.py hl[1,4] *} Utiliser `Optional[str]` plutôt que `str` permettra à l'éditeur de vous aider à détecter les erreurs où vous supposeriez qu'une valeur est toujours de type `str`, alors qu'elle pourrait aussi être `None`. @@ -249,15 +233,12 @@ Vous pouvez aussi déclarer une classe comme type d'une variable. Disons que vous avez une classe `Person`, avec une variable `name` : -```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{*../../docs_src/python_types/tutorial010.py hl[1:3] *} + Vous pouvez ensuite déclarer une variable de type `Person` : -```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{*../../docs_src/python_types/tutorial010.py hl[6] *} Et vous aurez accès, encore une fois, au support complet offert par l'éditeur : @@ -277,12 +258,13 @@ Ainsi, votre éditeur vous offrira un support adapté pour l'objet résultant. Extrait de la documentation officielle de **Pydantic** : -```Python -{!../../../docs_src/python_types/tutorial011.py!} -``` +{*../../docs_src/python_types/tutorial011.py*} + +/// info -!!! info - Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation. +Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation. + +/// **FastAPI** est basé entièrement sur **Pydantic**. @@ -310,5 +292,8 @@ Tout cela peut paraître bien abstrait, mais ne vous inquiétez pas, vous verrez Ce qu'il faut retenir c'est qu'en utilisant les types standard de Python, à un seul endroit (plutôt que d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous. -!!! info - Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`. +/// info + +Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`. + +/// diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md index f7cf1a6cc..e14d5a8e8 100644 --- a/docs/fr/docs/tutorial/background-tasks.md +++ b/docs/fr/docs/tutorial/background-tasks.md @@ -16,9 +16,7 @@ Cela comprend, par exemple : Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin* avec `BackgroundTasks` comme type déclaré. -```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre. @@ -32,18 +30,14 @@ Dans cet exemple, la fonction de tâche écrira dans un fichier (afin de simuler L'opération d'écriture n'utilisant ni `async` ni `await`, on définit la fonction avec un `def` normal. -```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Ajouter une tâche d'arrière-plan Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de type `BackgroundTasks` (`background_tasks` ici) grâce à la méthode `.add_task()` : -```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` reçoit comme arguments : @@ -57,9 +51,7 @@ Utiliser `BackgroundTasks` fonctionne aussi avec le système d'injection de dép **FastAPI** sait quoi faire dans chaque cas et comment réutiliser le même objet, afin que tous les paramètres de type `BackgroundTasks` soient fusionnés et que les tâches soient exécutées en arrière-plan : -```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} -``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée. diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..0541acc74 --- /dev/null +++ b/docs/fr/docs/tutorial/body-multiple-params.md @@ -0,0 +1,171 @@ +# Body - Paramètres multiples + +Maintenant que nous avons vu comment manipuler `Path` et `Query`, voyons comment faire pour le corps d'une requête, communément désigné par le terme anglais "body". + +## Mélanger les paramètres `Path`, `Query` et body + +Tout d'abord, sachez que vous pouvez mélanger les déclarations des paramètres `Path`, `Query` et body, **FastAPI** saura quoi faire. + +Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` : + +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} + +/// note + +Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`). + +/// + +## Paramètres multiples du body + +Dans l'exemple précédent, les opérations de routage attendaient un body JSON avec les attributs d'un `Item`, par exemple : + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément : + +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} + +Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic). + +Il utilisera alors les noms des paramètres comme clés, et s'attendra à recevoir quelque chose de semblable à : + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note + +"Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`. + +/// + +**FastAPI** effectue la conversion de la requête de façon transparente, de sorte que les objets `item` et `user` se trouvent correctement définis. + +Il effectue également la validation des données (même imbriquées les unes dans les autres), et permet de les documenter correctement (schéma OpenAPI et documentation auto-générée). + +## Valeurs scalaires dans le body + +De la même façon qu'il existe `Query` et `Path` pour définir des données supplémentaires pour les paramètres query et path, **FastAPI** fournit un équivalent `Body`. + +Par exemple, en étendant le modèle précédent, vous pouvez vouloir ajouter un paramètre `importance` dans le même body, en plus des paramètres `item` et `user`. + +Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`). + +Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` : + +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} + +Dans ce cas, **FastAPI** s'attendra à un body semblable à : + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +Encore une fois, cela convertira les types de données, les validera, permettra de générer la documentation, etc... + +## Paramètres multiples body et query + +Bien entendu, vous pouvez déclarer autant de paramètres que vous le souhaitez, en plus des paramètres body déjà déclarés. + +Par défaut, les valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) sont interprétées comme des paramètres query, donc inutile d'ajouter explicitement `Query`. Vous pouvez juste écrire : + +```Python +q: Union[str, None] = None +``` + +Ou bien, en Python 3.10 et supérieur : + +```Python +q: str | None = None +``` + +Par exemple : + +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} + +/// info + +`Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard. + +/// + +## Inclure un paramètre imbriqué dans le body + +Disons que vous avez seulement un paramètre `item` dans le body, correspondant à un modèle Pydantic `Item`. + +Par défaut, **FastAPI** attendra sa déclaration directement dans le body. + +Cependant, si vous souhaitez qu'il interprête correctement un JSON avec une clé `item` associée au contenu du modèle, comme cela serait le cas si vous déclariez des paramètres body additionnels, vous pouvez utiliser le paramètre spécial `embed` de `Body` : + +```Python +item: Item = Body(embed=True) +``` + +Voici un exemple complet : + +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} + +Dans ce cas **FastAPI** attendra un body semblable à : + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +au lieu de : + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Pour résumer + +Vous pouvez ajouter plusieurs paramètres body dans votre fonction de routage, même si une requête ne peut avoir qu'un seul body. + +Cependant, **FastAPI** se chargera de faire opérer sa magie, afin de toujours fournir à votre fonction des données correctes, les validera et documentera le schéma associé. + +Vous pouvez également déclarer des valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) à recevoir dans le body. + +Et vous pouvez indiquer à **FastAPI** d'inclure le body dans une autre variable, même lorsqu'un seul paramètre est déclaré. diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index ae952405c..760b6d80a 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -8,20 +8,21 @@ Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un cli Pour déclarer un corps de **requête**, on utilise les modèles de Pydantic en profitant de tous leurs avantages et fonctionnalités. -!!! info - Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`. +/// info - Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes. +Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`. - Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter. +Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes. + +Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter. + +/// ## Importez le `BaseModel` de Pydantic Commencez par importer la classe `BaseModel` du module `pydantic` : -```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Créez votre modèle de données @@ -29,9 +30,7 @@ Déclarez ensuite votre modèle de données en tant que classe qui hérite de `B Utilisez les types Python standard pour tous les attributs : -```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Tout comme pour la déclaration de paramètres de requête, quand un attribut de modèle a une valeur par défaut, il n'est pas nécessaire. Sinon, cet attribut doit être renseigné dans le corps de la requête. Pour rendre ce champ optionnel simplement, utilisez `None` comme valeur par défaut. @@ -59,9 +58,7 @@ Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) te Pour l'ajouter à votre *opération de chemin*, déclarez-le comme vous déclareriez des paramètres de chemin ou de requête : -```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...et déclarez que son type est le modèle que vous avez créé : `Item`. @@ -110,24 +107,25 @@ Mais vous auriez le même support de l'éditeur avec -!!! tip "Astuce" - Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin. +/// tip | Astuce + +Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin. - Ce qui améliore le support pour les modèles Pydantic avec : +Ce qui améliore le support pour les modèles Pydantic avec : - * de l'auto-complétion - * des vérifications de type - * du "refactoring" (ou remaniement de code) - * de la recherche - * de l'inspection +* de l'auto-complétion +* des vérifications de type +* du "refactoring" (ou remaniement de code) +* de la recherche +* de l'inspection + +/// ## Utilisez le modèle Dans la fonction, vous pouvez accéder à tous les attributs de l'objet du modèle directement : -```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Corps de la requête + paramètres de chemin @@ -135,9 +133,7 @@ Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la **FastAPI** est capable de reconnaître que les paramètres de la fonction qui correspondent aux paramètres de chemin doivent être **récupérés depuis le chemin**, et que les paramètres de fonctions déclarés comme modèles Pydantic devraient être **récupérés depuis le corps de la requête**. -```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Corps de la requête + paramètres de chemin et de requête @@ -145,9 +141,7 @@ Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de **FastAPI** saura reconnaître chacun d'entre eux et récupérer la bonne donnée au bon endroit. -```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Les paramètres de la fonction seront reconnus comme tel : @@ -155,10 +149,13 @@ Les paramètres de la fonction seront reconnus comme tel : * Si le paramètre est d'un **type singulier** (comme `int`, `float`, `str`, `bool`, etc.), il sera interprété comme un paramètre de **requête**. * Si le paramètre est déclaré comme ayant pour type un **modèle Pydantic**, il sera interprété comme faisant partie du **corps** de la requête. -!!! note - **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`. +/// note + +**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`. + +Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type. - Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type. +/// ## Sans Pydantic diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md index e58872d30..ab00fbdeb 100644 --- a/docs/fr/docs/tutorial/debugging.md +++ b/docs/fr/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ Vous pouvez connecter le débogueur da Dans votre application FastAPI, importez et exécutez directement `uvicorn` : -```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### À propos de `__name__ == "__main__"` @@ -74,9 +72,12 @@ Ainsi, la ligne : ne sera pas exécutée. -!!! info +/// info + Pour plus d'informations, consultez la documentation officielle de Python. +/// + ## Exécutez votre code avec votre débogueur Parce que vous exécutez le serveur Uvicorn directement depuis votre code, vous pouvez appeler votre programme Python (votre application FastAPI) directement depuis le débogueur. diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md index e98283f1e..758145362 100644 --- a/docs/fr/docs/tutorial/first-steps.md +++ b/docs/fr/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Le fichier **FastAPI** le plus simple possible pourrait ressembler à cela : -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copiez ce code dans un fichier nommé `main.py`. @@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note - La commande `uvicorn main:app` fait référence à : +/// note + +La commande `uvicorn main:app` fait référence à : + +* `main` : le fichier `main.py` (le module Python). +* `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`. +* `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production ! - * `main` : le fichier `main.py` (le module Python). - * `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`. - * `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production ! +/// Vous devriez voir dans la console, une ligne semblable à la suivante : @@ -131,22 +132,21 @@ Vous pourriez aussi l'utiliser pour générer du code automatiquement, pour les ### Étape 1 : import `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires au lancement de votre API. -!!! note "Détails techniques" - `FastAPI` est une classe héritant directement de `Starlette`. +/// note | Détails techniques + +`FastAPI` est une classe héritant directement de `Starlette`. - Vous pouvez donc aussi utiliser toutes les fonctionnalités de Starlette depuis `FastAPI`. +Vous pouvez donc aussi utiliser toutes les fonctionnalités de Starlette depuis `FastAPI`. + +/// ### Étape 2 : créer une "instance" `FastAPI` -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Ici la variable `app` sera une "instance" de la classe `FastAPI`. @@ -166,9 +166,7 @@ $ uvicorn main:app --reload Si vous créez votre app avec : -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} Et la mettez dans un fichier `main.py`, alors vous appelleriez `uvicorn` avec : @@ -200,9 +198,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Un chemin, ou "path" est aussi souvent appelé route ou "endpoint". +/// info +Un chemin, ou "path" est aussi souvent appelé route ou "endpoint". + +/// #### Opération @@ -242,25 +242,26 @@ Nous allons donc aussi appeler ces dernières des "**opérations**". #### Définir un *décorateur d'opération de chemin* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} Le `@app.get("/")` dit à **FastAPI** que la fonction en dessous est chargée de gérer les requêtes qui vont sur : * le chemin `/` * en utilisant une opération get -!!! info "`@décorateur` Info" - Cette syntaxe `@something` en Python est appelée un "décorateur". +/// info | `@décorateur` Info - Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻‍♂). +Cette syntaxe `@something` en Python est appelée un "décorateur". - Un "décorateur" prend la fonction en dessous et en fait quelque chose. +Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻‍♂). - Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`. +Un "décorateur" prend la fonction en dessous et en fait quelque chose. - C'est le "**décorateur d'opération de chemin**". +Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`. + +C'est le "**décorateur d'opération de chemin**". + +/// Vous pouvez aussi utiliser les autres opérations : @@ -275,14 +276,17 @@ Tout comme celles les plus exotiques : * `@app.patch()` * `@app.trace()` -!!! tip "Astuce" - Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez. +/// tip | Astuce + +Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez. - **FastAPI** n'impose pas de sens spécifique à chacune d'elle. +**FastAPI** n'impose pas de sens spécifique à chacune d'elle. - Les informations qui sont présentées ici forment une directive générale, pas des obligations. +Les informations qui sont présentées ici forment une directive générale, pas des obligations. - Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`. +Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`. + +/// ### Étape 4 : définir la **fonction de chemin**. @@ -292,9 +296,7 @@ Voici notre "**fonction de chemin**" (ou fonction d'opération de chemin) : * **opération** : `get`. * **fonction** : la fonction sous le "décorateur" (sous `@app.get("/")`). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} C'est une fonction Python. @@ -306,18 +308,17 @@ Ici, c'est une fonction asynchrone (définie avec `async def`). Vous pourriez aussi la définir comme une fonction classique plutôt qu'avec `async def` : -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note -!!! note - Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}. +Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}. + +/// ### Étape 5 : retourner le contenu -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Vous pouvez retourner un dictionnaire (`dict`), une liste (`list`), des valeurs seules comme des chaines de caractères (`str`) et des entiers (`int`), etc. diff --git a/docs/fr/docs/tutorial/index.md b/docs/fr/docs/tutorial/index.md index 4dc202b33..83cc5f9e8 100644 --- a/docs/fr/docs/tutorial/index.md +++ b/docs/fr/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install fastapi[all] ... qui comprend également `uvicorn`, que vous pouvez utiliser comme serveur pour exécuter votre code. -!!! note - Vous pouvez également l'installer pièce par pièce. +/// note - C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production : +Vous pouvez également l'installer pièce par pièce. - ``` - pip install fastapi - ``` +C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production : - Installez également `uvicorn` pour qu'il fonctionne comme serveur : +``` +pip install fastapi +``` + +Installez également `uvicorn` pour qu'il fonctionne comme serveur : + +``` +pip install uvicorn +``` - ``` - pip install uvicorn - ``` +Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser. - Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser. +/// ## Guide utilisateur avancé diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..3f3280e64 --- /dev/null +++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,163 @@ +# Paramètres de chemin et validations numériques + +De la même façon que vous pouvez déclarer plus de validations et de métadonnées pour les paramètres de requête avec `Query`, vous pouvez déclarer le même type de validations et de métadonnées pour les paramètres de chemin avec `Path`. + +## Importer Path + +Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` : + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} + +/// info + +FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0. + +Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`. + +Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`. + +/// + +## Déclarer des métadonnées + +Vous pouvez déclarer les mêmes paramètres que pour `Query`. + +Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètre de chemin `item_id`, vous pouvez écrire : + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} + +/// note + +Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis. + +/// + +## Ordonnez les paramètres comme vous le souhaitez + +/// tip + +Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. + +/// + +Disons que vous voulez déclarer le paramètre de requête `q` comme un `str` requis. + +Et vous n'avez pas besoin de déclarer autre chose pour ce paramètre, donc vous n'avez pas vraiment besoin d'utiliser `Query`. + +Mais vous avez toujours besoin d'utiliser `Path` pour le paramètre de chemin `item_id`. Et vous ne voulez pas utiliser `Annotated` pour une raison quelconque. + +Python se plaindra si vous mettez une valeur avec une "défaut" avant une valeur qui n'a pas de "défaut". + +Mais vous pouvez les réorganiser, et avoir la valeur sans défaut (le paramètre de requête `q`) en premier. + +Cela n'a pas d'importance pour **FastAPI**. Il détectera les paramètres par leurs noms, types et déclarations par défaut (`Query`, `Path`, etc), il ne se soucie pas de l'ordre. + +Ainsi, vous pouvez déclarer votre fonction comme suit : + +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} + +Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`. + +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *} + +## Ordonnez les paramètres comme vous le souhaitez (astuces) + +/// tip + +Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. + +/// + +Voici une **petite astuce** qui peut être pratique, mais vous n'en aurez pas souvent besoin. + +Si vous voulez : + +* déclarer le paramètre de requête `q` sans `Query` ni valeur par défaut +* déclarer le paramètre de chemin `item_id` en utilisant `Path` +* les avoir dans un ordre différent +* ne pas utiliser `Annotated` + +...Python a une petite syntaxe spéciale pour cela. + +Passez `*`, comme premier paramètre de la fonction. + +Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants doivent être appelés comme arguments "mots-clés" (paires clé-valeur), également connus sous le nom de kwargs. Même s'ils n'ont pas de valeur par défaut. + +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} + +# Avec `Annotated` + +Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`. + +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} + +## Validations numériques : supérieur ou égal + +Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des contraintes numériques. + +Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`. + +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} + +## Validations numériques : supérieur ou égal et inférieur ou égal + +La même chose s'applique pour : + +* `gt` : `g`reater `t`han +* `le` : `l`ess than or `e`qual + +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} + +## Validations numériques : supérieur et inférieur ou égal + +La même chose s'applique pour : + +* `gt` : `g`reater `t`han +* `le` : `l`ess than or `e`qual + +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} + +## Validations numériques : flottants, supérieur et inférieur + +Les validations numériques fonctionnent également pour les valeurs `float`. + +C'est ici qu'il devient important de pouvoir déclarer gt et pas seulement ge. Avec cela, vous pouvez exiger, par exemple, qu'une valeur doit être supérieure à `0`, même si elle est inférieure à `1`. + +Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas. + +Et la même chose pour lt. + +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} + +## Pour résumer + +Avec `Query`, `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des métadonnées et des validations de chaînes de la même manière qu'avec les [Paramètres de requête et validations de chaînes](query-params-str-validations.md){.internal-link target=_blank}. + +Et vous pouvez également déclarer des validations numériques : + +* `gt` : `g`reater `t`han +* `ge` : `g`reater than or `e`qual +* `lt` : `l`ess `t`han +* `le` : `l`ess than or `e`qual + +/// info + +`Query`, `Path`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`. + +Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment. + +/// + +/// note | Détails techniques + +Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions. + +Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom. + +Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`. + +Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types. + +De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs. + +/// diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 817545c1c..71c96b18e 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -4,9 +4,7 @@ Vous pouvez déclarer des "paramètres" ou "variables" de chemin avec la même s formatage de chaîne Python : -```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} La valeur du paramètre `item_id` sera transmise à la fonction dans l'argument `item_id`. @@ -22,15 +20,16 @@ vous verrez comme réponse : Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en utilisant les annotations de type Python : -```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} Ici, `item_id` est déclaré comme `int`. -!!! hint "Astuce" - Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles - que des vérifications d'erreur, de l'auto-complétion, etc. +/// check | vérifier + +Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles +que des vérifications d'erreur, de l'auto-complétion, etc. + +/// ## Conversion de données @@ -40,12 +39,15 @@ Si vous exécutez cet exemple et allez sur "parsing" automatique. +Comme vous l'avez remarqué, la valeur reçue par la fonction (et renvoyée ensuite) est `3`, +en tant qu'entier (`int`) Python, pas la chaîne de caractères (`string`) `"3"`. + +Grâce aux déclarations de types, **FastAPI** fournit du +"parsing" automatique. + +/// ## Validation de données @@ -72,12 +74,15 @@ La même erreur se produira si vous passez un nombre flottant (`float`) et non u http://127.0.0.1:8000/items/4.2. -!!! hint "Astuce" - Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. +/// check | vérifier + +Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. - Notez que l'erreur mentionne le point exact où la validation n'a pas réussi. +Notez que l'erreur mentionne le point exact où la validation n'a pas réussi. - Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API. +Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API. + +/// ## Documentation @@ -86,10 +91,13 @@ documentation générée automatiquement et interactive : -!!! info - À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI). +/// info + +À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI). + +On voit bien dans la documentation que `item_id` est déclaré comme entier. - On voit bien dans la documentation que `item_id` est déclaré comme entier. +/// ## Les avantages d'avoir une documentation basée sur une norme, et la documentation alternative. @@ -119,9 +127,7 @@ Et vous avez un second chemin : `/users/{user_id}` pour récupérer de la donné Les *fonctions de chemin* étant évaluées dans l'ordre, il faut s'assurer que la fonction correspondant à `/users/me` est déclarée avant celle de `/users/{user_id}` : -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, la fonction "croyant" qu'elle a reçu un paramètre `user_id` avec pour valeur `"me"`. @@ -137,23 +143,25 @@ En héritant de `str` la documentation sera capable de savoir que les valeurs do Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs autorisées pour cette énumération. -```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info -!!! info - Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4. +Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4. -!!! tip "Astuce" - Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning. +/// + +/// tip | Astuce + +Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning. + +/// ### Déclarer un paramètre de chemin Créez ensuite un *paramètre de chemin* avec une annotation de type désignant l'énumération créée précédemment (`ModelName`) : -```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Documentation @@ -169,20 +177,19 @@ La valeur du *paramètre de chemin* sera un des "membres" de l'énumération. Vous pouvez comparer ce paramètre avec les membres de votre énumération `ModelName` : -```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### Récupérer la *valeur de l'énumération* Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici), avec `model_name.value`, ou en général, `votre_membre_d'enum.value` : -```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} -!!! tip "Astuce" - Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`. +/// tip | Astuce + +Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`. + +/// #### Retourner des *membres d'énumération* @@ -190,9 +197,7 @@ Vous pouvez retourner des *membres d'énumération* dans vos *fonctions de chemi Ils seront convertis vers leurs valeurs correspondantes (chaînes de caractères ici) avant d'être transmis au client : -```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} Le client recevra une réponse JSON comme celle-ci : @@ -231,14 +236,15 @@ Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:pat Vous pouvez donc l'utilisez comme tel : -```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Astuce + +Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`). -!!! tip "Astuce" - Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`). +Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`. - Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`. +/// ## Récapitulatif diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md index f5248fe8b..c54c0c717 100644 --- a/docs/fr/docs/tutorial/query-params-str-validations.md +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -4,16 +4,17 @@ Commençons avec cette application pour exemple : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis. -!!! note - **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`. +/// note + +**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`. - Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs. +Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs. + +/// ## Validation additionnelle @@ -23,17 +24,13 @@ Nous allons imposer que bien que `q` soit un paramètre optionnel, dès qu'il es Pour cela, importez d'abord `Query` depuis `fastapi` : -```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## Utiliser `Query` comme valeur par défaut Construisez ensuite la valeur par défaut de votre paramètre avec `Query`, en choisissant 50 comme `max_length` : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} Comme nous devons remplacer la valeur par défaut `None` dans la fonction par `Query()`, nous pouvons maintenant définir la valeur par défaut avec le paramètre `Query(default=None)`, il sert le même objectif qui est de définir cette valeur par défaut. @@ -51,22 +48,25 @@ q: Union[str, None] = None Mais déclare explicitement `q` comme étant un paramètre de requête. -!!! info - Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est : +/// info + +Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est : + +```Python += None +``` - ```Python - = None - ``` +ou : - ou : +```Python += Query(None) +``` - ```Python - = Query(None) - ``` +et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**. - et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**. +Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support. - Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support. +/// Ensuite, nous pouvons passer d'autres paramètres à `Query`. Dans cet exemple, le paramètre `max_length` qui s'applique aux chaînes de caractères : @@ -80,17 +80,13 @@ Cela va valider les données, montrer une erreur claire si ces dernières ne son Vous pouvez aussi rajouter un second paramètre `min_length` : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[9] *} ## Ajouter des validations par expressions régulières On peut définir une expression régulière à laquelle le paramètre doit correspondre : -```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[10] *} Cette expression régulière vérifie que la valeur passée comme paramètre : @@ -108,12 +104,13 @@ De la même façon que vous pouvez passer `None` comme premier argument pour l'u Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de `3`, et une valeur par défaut étant `"fixedquery"` : -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} + +/// note | Rappel + +Avoir une valeur par défaut rend le paramètre optionnel. -!!! note "Rappel" - Avoir une valeur par défaut rend le paramètre optionnel. +/// ## Rendre ce paramètre requis @@ -137,12 +134,13 @@ q: Union[str, None] = Query(default=None, min_length=3) Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut utiliser `...` comme premier argument : -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} + +/// info -!!! info - Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis". +Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis". + +/// Cela indiquera à **FastAPI** que la présence de ce paramètre est obligatoire. @@ -152,9 +150,7 @@ Quand on définit un paramètre de requête explicitement avec `Query` on peut a Par exemple, pour déclarer un paramètre de requête `q` qui peut apparaître plusieurs fois dans une URL, on écrit : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} Ce qui fait qu'avec une URL comme : @@ -175,8 +171,11 @@ Donc la réponse de cette URL serait : } ``` -!!! tip "Astuce" - Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. +/// tip | Astuce + +Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. + +/// La documentation sera donc mise à jour automatiquement pour autoriser plusieurs valeurs : @@ -186,9 +185,7 @@ La documentation sera donc mise à jour automatiquement pour autoriser plusieurs Et l'on peut aussi définir une liste de valeurs par défaut si aucune n'est fournie : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} Si vous allez à : @@ -213,14 +210,15 @@ et la réponse sera : Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` : -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} -!!! note - Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste. +/// note - Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification. +Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste. + +Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification. + +/// ## Déclarer des métadonnées supplémentaires @@ -228,22 +226,21 @@ On peut aussi ajouter plus d'informations sur le paramètre. Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés. -!!! note - Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI. +/// note + +Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI. + +Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées. - Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées. +/// Vous pouvez ajouter un `title` : -```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} Et une `description` : -```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## Alias de paramètres @@ -263,9 +260,7 @@ Mais vous avez vraiment envie que ce soit exactement `item-query`... Pour cela vous pouvez déclarer un `alias`, et cet alias est ce qui sera utilisé pour trouver la valeur du paramètre : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## Déprécier des paramètres @@ -275,9 +270,7 @@ Il faut qu'il continue à exister pendant un certain temps car vos clients l'uti On utilise alors l'argument `deprecated=True` de `Query` : -```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} La documentation le présentera comme il suit : diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md index 962135f63..b87c26c78 100644 --- a/docs/fr/docs/tutorial/query-params.md +++ b/docs/fr/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Quand vous déclarez des paramètres dans votre fonction de chemin qui ne font pas partie des paramètres indiqués dans le chemin associé, ces paramètres sont automatiquement considérés comme des paramètres de "requête". -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} La partie appelée requête (ou **query**) dans une URL est l'ensemble des paires clés-valeurs placées après le `?` , séparées par des `&`. @@ -63,28 +61,29 @@ Les valeurs des paramètres de votre fonction seront : De la même façon, vous pouvez définir des paramètres de requête comme optionnels, en leur donnant comme valeur par défaut `None` : -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut. -!!! check "Remarque" - On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête. +/// check | Remarque + +On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête. -!!! note - **FastAPI** saura que `q` est optionnel grâce au `=None`. +/// - Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code. +/// note +**FastAPI** saura que `q` est optionnel grâce au `=None`. + +Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code. + +/// ## Conversion des types des paramètres de requête Vous pouvez aussi déclarer des paramètres de requête comme booléens (`bool`), **FastAPI** les convertira : -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} Avec ce code, en allant sur : @@ -126,9 +125,7 @@ Et vous n'avez pas besoin de les déclarer dans un ordre spécifique. Ils seront détectés par leurs noms : -```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## Paramètres de requête requis @@ -138,9 +135,7 @@ Si vous ne voulez pas leur donner de valeur par défaut mais juste les rendre op Mais si vous voulez rendre un paramètre de requête obligatoire, vous pouvez juste ne pas y affecter de valeur par défaut : -```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Ici le paramètre `needy` est un paramètre requis (ou obligatoire) de type `str`. @@ -184,9 +179,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Et bien sur, vous pouvez définir certains paramètres comme requis, certains avec des valeurs par défaut et certains entièrement optionnels : -```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} Ici, on a donc 3 paramètres de requête : @@ -194,5 +187,8 @@ Ici, on a donc 3 paramètres de requête : * `skip`, un `int` avec comme valeur par défaut `0`. * `limit`, un `int` optionnel. -!!! tip "Astuce" - Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}. +/// tip | Astuce + +Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}. + +/// diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 335a22743..6498d15e1 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ תשתית FastAPI, ביצועים גבוהים, קלה ללמידה, מהירה לתכנות, מוכנה לסביבת ייצור

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,7 +29,7 @@ **תיעוד**: https://fastapi.tiangolo.com -**קוד**: https://github.com/tiangolo/fastapi +**קוד**: https://github.com/fastapi/fastapi --- @@ -31,7 +37,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג תכונות המפתח הן: -- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#performance). +- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#_14). - **מהירה לתכנות**: הגבירו את מהירות פיתוח התכונות החדשות בכ - %200 עד %300. \* - **פחות שגיאות**: מנעו כ - %40 משגיאות אנוש (מפתחים). \* @@ -64,7 +70,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -88,7 +94,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -129,7 +135,7 @@ $ pip install fastapi
-תצטרכו גם שרת ASGI כגון Uvicorn או Hypercorn. +תצטרכו גם שרת ASGI כגון Uvicorn או Hypercorn.
@@ -440,7 +446,7 @@ item: Item בשימוש Pydantic: -- email_validator - לאימות כתובות אימייל. +- email-validator - לאימות כתובות אימייל. בשימוש Starlette: @@ -449,12 +455,12 @@ item: Item - python-multipart - דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form(). - itsdangerous - דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`. - pyyaml - דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI). -- ujson - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`. בשימוש FastAPI / Starlette: - uvicorn - לשרת שטוען ומגיש את האפליקציה שלכם. - orjson - דרוש אם ברצונכם להשתמש ב - `ORJSONResponse`. +- ujson - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`. תוכלו להתקין את כל אלו באמצעות pip install "fastapi[all]". diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index 75ea88c4d..c6f596650 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -5,11 +5,11 @@ FastAPI keretrendszer, nagy teljesítmény, könnyen tanulható, gyorsan kódolható, productionre kész

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,10 +23,10 @@ **Dokumentáció**: https://fastapi.tiangolo.com -**Forrás kód**: https://github.com/tiangolo/fastapi +**Forrás kód**: https://github.com/fastapi/fastapi --- -A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python 3.8+-al, a Python szabványos típusjelöléseire építve. +A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python -al, a Python szabványos típusjelöléseire építve. Kulcs funkciók: @@ -63,7 +63,7 @@ Kulcs funkciók: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -87,7 +87,7 @@ Kulcs funkciók: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -115,8 +115,6 @@ Ha egy olyan CLI alkalmazást fejlesztesz amit a parancssorban kell használni w ## Követelmények -Python 3.8+ - A FastAPI óriások vállán áll: * Starlette a webes részekhez. @@ -331,7 +329,7 @@ Ezt standard modern Python típusokkal csinálod. Nem kell új szintaxist, vagy specifikus könyvtár mert metódósait, stb. megtanulnod. -Csak standard **Python 3.8+**. +Csak standard **Python**. Például egy `int`-nek: @@ -378,7 +376,7 @@ Visszatérve az előző kód példához. A **FastAPI**: * Validálja hogy van egy `item_id` mező a `GET` és `PUT` kérésekben. * Validálja hogy az `item_id` `int` típusú a `GET` és `PUT` kérésekben. * Ha nem akkor látni fogunk egy tiszta hibát ezzel kapcsolatban. -* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. +* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. * Mivel a `q` paraméter `= None`-al van deklarálva, ezért opcionális. * `None` nélkül ez a mező kötelező lenne (mint például a body `PUT` kérések esetén). * a `/items/{item_id}` címre érkező `PUT` kérések esetén, a JSON-t a következőképpen olvassa be: @@ -445,7 +443,7 @@ Ezeknek a további megértéséhez: email_validator - e-mail validációkra. +* email-validator - e-mail validációkra. * pydantic-settings - Beállítások követésére. * pydantic-extra-types - Extra típusok Pydantic-hoz. @@ -456,12 +454,12 @@ Starlette által használt: * python-multipart - Követelmény ha "parsing"-ot akarsz támogatni, `request.form()`-al. * itsdangerous - Követelmény `SessionMiddleware` támogatáshoz. * pyyaml - Követelmény a Starlette `SchemaGenerator`-ának támogatásához (valószínűleg erre nincs szükség FastAPI használása esetén). -* ujson - Követelmény ha `UJSONResponse`-t akarsz használni. FastAPI / Starlette által használt * uvicorn - Szerverekhez amíg betöltik és szolgáltatják az applikációdat. * orjson - Követelmény ha `ORJSONResponse`-t akarsz használni. +* ujson - Követelmény ha `UJSONResponse`-t akarsz használni. Ezeket mind telepítheted a `pip install "fastapi[all]"` paranccsal. diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md index b8ed96ae1..c01ec9a89 100644 --- a/docs/id/docs/tutorial/index.md +++ b/docs/id/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu. -!!! catatan - Kamu juga dapat meng-installnya bagian demi bagian. +/// note | Catatan - Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi: +Kamu juga dapat meng-installnya bagian demi bagian. - ``` - pip install fastapi - ``` +Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi: - Juga install `uvicorn` untuk menjalankan server" +``` +pip install fastapi +``` + +Juga install `uvicorn` untuk menjalankan server" + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan. - Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan. +/// ## Pedoman Pengguna Lanjutan diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index a69008d2b..8a1039bc5 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -1,7 +1,3 @@ - -{!../../../docs/missing-translation.md!} - -

FastAPI

@@ -9,11 +5,11 @@ FastAPI framework, alte prestazioni, facile da imparare, rapido da implementare, pronto per il rilascio in produzione

- - Build Status + + Build Status - - Coverage + + Coverage Package version @@ -24,7 +20,7 @@ **Documentazione**: https://fastapi.tiangolo.com -**Codice Sorgente**: https://github.com/tiangolo/fastapi +**Codice Sorgente**: https://github.com/fastapi/fastapi --- @@ -64,7 +60,7 @@ Le sue caratteristiche principali sono: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -88,7 +84,7 @@ Le sue caratteristiche principali sono: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -129,7 +125,7 @@ $ pip install fastapi
-Per il rilascio in produzione, sarà necessario un server ASGI come Uvicorn oppure Hypercorn. +Per il rilascio in produzione, sarà necessario un server ASGI come Uvicorn oppure Hypercorn.
@@ -438,8 +434,7 @@ Per approfondire, consulta la sezione ujson - per un "parsing" di JSON più veloce. -* email_validator - per la validazione di email. +* email-validator - per la validazione di email. Usate da Starlette: @@ -450,12 +445,12 @@ Usate da Starlette: * itsdangerous - Richiesto per usare `SessionMiddleware`. * pyyaml - Richiesto per il supporto dello `SchemaGenerator` di Starlette (probabilmente non ti serve con FastAPI). * graphene - Richiesto per il supporto di `GraphQLApp`. -* ujson - Richiesto se vuoi usare `UJSONResponse`. Usate da FastAPI / Starlette: * uvicorn - per il server che carica e serve la tua applicazione. * orjson - ichiesto se vuoi usare `ORJSONResponse`. +* ujson - Richiesto se vuoi usare `UJSONResponse`. Puoi installarle tutte con `pip install fastapi[all]`. diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md index d1f8e6451..fb3164328 100644 --- a/docs/ja/docs/advanced/additional-status-codes.md +++ b/docs/ja/docs/advanced/additional-status-codes.md @@ -15,20 +15,26 @@ これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。 ```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} +{!../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning "注意" - 上記の例のように `Response` を明示的に返す場合、それは直接返されます。 +/// warning | 注意 - モデルなどはシリアライズされません。 +上記の例のように `Response` を明示的に返す場合、それは直接返されます。 - 必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。 +モデルなどはシリアライズされません。 -!!! note "技術詳細" - `from starlette.responses import JSONResponse` を利用することもできます。 +必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。 - **FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。 +/// + +/// note | 技術詳細 + +`from starlette.responses import JSONResponse` を利用することもできます。 + +**FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。 + +/// ## OpenAPIとAPIドキュメント diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md index d8b47629a..15edc11ad 100644 --- a/docs/ja/docs/advanced/custom-response.md +++ b/docs/ja/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ そしてもし、`Response` が、`JSONResponse` や `UJSONResponse` の場合のようにJSONメディアタイプ (`application/json`) ならば、データは *path operationデコレータ* に宣言したPydantic `response_model` により自動的に変換 (もしくはフィルタ) されます。 -!!! note "備考" - メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。 +/// note | 備考 + +メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。 + +/// ## `ORJSONResponse` を使う @@ -22,18 +25,24 @@ 使いたい `Response` クラス (サブクラス) をインポートし、 *path operationデコレータ* に宣言します。 ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info "情報" - パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。 +/// info | 情報 + +パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。 + +この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。 + +そして、OpenAPIにはそのようにドキュメントされます。 + +/// - この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。 +/// tip | 豆知識 - そして、OpenAPIにはそのようにドキュメントされます。 +`ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。 -!!! tip "豆知識" - `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。 +/// ## HTMLレスポンス @@ -43,15 +52,18 @@ * *path operation* のパラメータ `content_type` に `HTMLResponse` を渡す。 ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` -!!! info "情報" - パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。 +/// info | 情報 - この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。 +パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。 - そして、OpenAPIにはそのようにドキュメント化されます。 +この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。 + +そして、OpenAPIにはそのようにドキュメント化されます。 + +/// ### `Response` を返す @@ -60,14 +72,20 @@ 上記と同じ例において、 `HTMLResponse` を返すと、このようになります: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning "注意" - *path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。 +/// warning | 注意 + +*path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。 + +/// + +/// info | 情報 -!!! info "情報" - もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。 +もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。 + +/// ### OpenAPIドキュメントと `Response` のオーバーライド @@ -80,7 +98,7 @@ 例えば、このようになります: ```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` この例では、関数 `generate_html_response()` は、`str` のHTMLを返すのではなく `Response` を生成して返しています。 @@ -97,10 +115,13 @@ `Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。 -!!! note "技術詳細" - `from starlette.responses import HTMLResponse` も利用できます。 +/// note | 技術詳細 + +`from starlette.responses import HTMLResponse` も利用できます。 + +**FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ### `Response` @@ -118,7 +139,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含みます。また、media_typeに基づいたContent-Typeヘッダーを含み、テキストタイプのためにcharsetを追加します。 ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -130,7 +151,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 テキストやバイトを受け取り、プレーンテキストのレスポンスを返します。 ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -147,22 +168,28 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 `ujson`を使った、代替のJSONレスポンスです。 -!!! warning "注意" - `ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。 +/// warning | 注意 + +`ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。 + +/// ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} +{!../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip "豆知識" - `ORJSONResponse` のほうが高速な代替かもしれません。 +/// tip | 豆知識 + +`ORJSONResponse` のほうが高速な代替かもしれません。 + +/// ### `RedirectResponse` HTTPリダイレクトを返します。デフォルトでは307ステータスコード (Temporary Redirect) となります。 ```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} +{!../../docs_src/custom_response/tutorial006.py!} ``` ### `StreamingResponse` @@ -170,7 +197,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス 非同期なジェネレータか通常のジェネレータ・イテレータを受け取り、レスポンスボディをストリームします。 ```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} +{!../../docs_src/custom_response/tutorial007.py!} ``` #### `StreamingResponse` をファイルライクなオブジェクトとともに使う @@ -180,11 +207,14 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス これにはクラウドストレージとの連携や映像処理など、多くのライブラリが含まれています。 ```Python hl_lines="2 10-12 14" -{!../../../docs_src/custom_response/tutorial008.py!} +{!../../docs_src/custom_response/tutorial008.py!} ``` -!!! tip "豆知識" - ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。 +/// tip | 豆知識 + +ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。 + +/// ### `FileResponse` @@ -200,7 +230,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス ファイルレスポンスには、適切な `Content-Length` 、 `Last-Modified` 、 `ETag` ヘッダーが含まれます。 ```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} +{!../../docs_src/custom_response/tutorial009.py!} ``` ## デフォルトレスポンスクラス @@ -212,11 +242,14 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス 以下の例では、 **FastAPI** は、全ての *path operation* で `JSONResponse` の代わりに `ORJSONResponse` をデフォルトとして利用します。 ```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} +{!../../docs_src/custom_response/tutorial010.py!} ``` -!!! tip "豆知識" - 前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。 +/// tip | 豆知識 + +前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。 + +/// ## その他のドキュメント diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md index 2d60e7489..22eaf6eb8 100644 --- a/docs/ja/docs/advanced/index.md +++ b/docs/ja/docs/advanced/index.md @@ -6,10 +6,13 @@ 以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。 -!!! tip "豆知識" - 以降のセクションは、 **必ずしも"応用編"ではありません**。 +/// tip | 豆知識 - ユースケースによっては、その中から解決策を見つけられるかもしれません。 +以降のセクションは、 **必ずしも"応用編"ではありません**。 + +ユースケースによっては、その中から解決策を見つけられるかもしれません。 + +/// ## 先にチュートリアルを読む diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md index 35b381cae..99428bcbe 100644 --- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md @@ -2,15 +2,18 @@ ## OpenAPI operationId -!!! warning "注意" - あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。 +/// warning | 注意 + +あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。 + +/// *path operation* で `operation_id` パラメータを利用することで、OpenAPIの `operationId` を設定できます。 `operation_id` は各オペレーションで一意にする必要があります。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### *path operation関数* の名前をoperationIdとして使用する @@ -20,23 +23,29 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP そうする場合は、すべての *path operation* を追加した後に行う必要があります。 ```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip "豆知識" - `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。 +/// tip | 豆知識 + +`app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。 + +/// + +/// warning | 注意 + +この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。 -!!! warning "注意" - この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。 +それらが異なるモジュール (Pythonファイル) にあるとしてもです。 - それらが異なるモジュール (Pythonファイル) にあるとしてもです。 +/// ## OpenAPIから除外する 生成されるOpenAPIスキーマ (つまり、自動ドキュメント生成の仕組み) から *path operation* を除外するには、 `include_in_schema` パラメータを `False` にします。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## docstringによる説明の高度な設定 @@ -48,5 +57,5 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP ドキュメントには表示されませんが、他のツール (例えばSphinx) では残りの部分を利用できるでしょう。 ```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md index 10ec88548..dc66e238c 100644 --- a/docs/ja/docs/advanced/response-directly.md +++ b/docs/ja/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 実際は、`Response` やそのサブクラスを返すことができます。 -!!! tip "豆知識" - `JSONResponse` それ自体は、 `Response` のサブクラスです。 +/// tip | 豆知識 + +`JSONResponse` それ自体は、 `Response` のサブクラスです。 + +/// `Response` を返した場合は、**FastAPI** は直接それを返します。 @@ -32,13 +35,16 @@ このようなケースでは、レスポンスにデータを含める前に `jsonable_encoder` を使ってデータを変換できます。 ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "技術詳細" - また、`from starlette.responses import JSONResponse` も利用できます。 +/// note | 技術詳細 + +また、`from starlette.responses import JSONResponse` も利用できます。 + +**FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ## カスタム `Response` を返す @@ -51,7 +57,7 @@ XMLを文字列にし、`Response` に含め、それを返します。 ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ## 備考 diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md index 65e4112a6..365ceca9d 100644 --- a/docs/ja/docs/advanced/websockets.md +++ b/docs/ja/docs/advanced/websockets.md @@ -39,7 +39,7 @@ $ pip install websockets しかし、これはWebSocketのサーバーサイドに焦点を当て、実用的な例を示す最も簡単な方法です。 ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## `websocket` を作成する @@ -47,20 +47,23 @@ $ pip install websockets **FastAPI** アプリケーションで、`websocket` を作成します。 ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` -!!! note "技術詳細" - `from starlette.websockets import WebSocket` を使用しても構いません. +/// note | 技術詳細 - **FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。 +`from starlette.websockets import WebSocket` を使用しても構いません. + +**FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。 + +/// ## メッセージの送受信 WebSocketルートでは、 `await` を使ってメッセージの送受信ができます。 ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` バイナリやテキストデータ、JSONデータを送受信できます。 @@ -113,15 +116,18 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート これらは、他のFastAPI エンドポイント/*path operation* の場合と同じように機能します。 ```Python hl_lines="58-65 68-83" -{!../../../docs_src/websockets/tutorial002.py!} +{!../../docs_src/websockets/tutorial002.py!} ``` -!!! info "情報" - WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。 +/// info | 情報 + +WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。 + +クロージングコードは、仕様で定義された有効なコードの中から使用することができます。 - クロージングコードは、仕様で定義された有効なコードの中から使用することができます。 +将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。 - 将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。 +/// ### 依存関係を用いてWebSocketsを試してみる @@ -144,8 +150,11 @@ $ uvicorn main:app --reload * パスで使用される「Item ID」 * クエリパラメータとして使用される「Token」 -!!! tip "豆知識" - クエリ `token` は依存パッケージによって処理されることに注意してください。 +/// tip | 豆知識 + +クエリ `token` は依存パッケージによって処理されることに注意してください。 + +/// これにより、WebSocketに接続してメッセージを送受信できます。 @@ -156,7 +165,7 @@ $ uvicorn main:app --reload WebSocket接続が閉じられると、 `await websocket.receive_text()` は例外 `WebSocketDisconnect` を発生させ、この例のようにキャッチして処理することができます。 ```Python hl_lines="81-83" -{!../../../docs_src/websockets/tutorial003.py!} +{!../../docs_src/websockets/tutorial003.py!} ``` 試してみるには、 @@ -171,12 +180,15 @@ WebSocket接続が閉じられると、 `await websocket.receive_text()` は例 Client #1596980209979 left the chat ``` -!!! tip "豆知識" - 上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。 +/// tip | 豆知識 + +上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。 + +しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。 - しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。 +もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。 - もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。 +/// ## その他のドキュメント diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md index ce4b36408..8129a7002 100644 --- a/docs/ja/docs/alternatives.md +++ b/docs/ja/docs/alternatives.md @@ -30,11 +30,17 @@ Mozilla、Red Hat、Eventbrite など多くの企業で利用されています これは**自動的なAPIドキュメント生成**の最初の例であり、これは**FastAPI**に向けた「調査」を触発した最初のアイデアの一つでした。 -!!! note "備考" - Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。 +/// note | 備考 -!!! check "**FastAPI**へ与えたインスピレーション" - 自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 +Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。 + +/// + +/// check | **FastAPI**へ与えたインスピレーション + +自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 + +/// ### Flask @@ -50,11 +56,13 @@ Flask は「マイクロフレームワーク」であり、データベース Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。 -!!! check "**FastAPI**へ与えたインスピレーション" - マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 +/// check | **FastAPI**へ与えたインスピレーション + +マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 - シンプルで簡単なルーティングの仕組みを持っている点。 +シンプルで簡単なルーティングの仕組みを持っている点。 +/// ### Requests @@ -90,11 +98,13 @@ def read_url(): `requests.get(...)` と`@app.get(...)` には類似点が見受けられます。 -!!! check "**FastAPI**へ与えたインスピレーション" - * シンプルで直感的なAPIを持っている点。 - * HTTPメソッド名を直接利用し、単純で直感的である。 - * 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。 +/// check | **FastAPI**へ与えたインスピレーション + +* シンプルで直感的なAPIを持っている点。 +* HTTPメソッド名を直接利用し、単純で直感的である。 +* 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。 +/// ### Swagger / OpenAPI @@ -108,15 +118,18 @@ def read_url(): そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。 -!!! check "**FastAPI**へ与えたインスピレーション" - 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 +/// check | **FastAPI**へ与えたインスピレーション - そして、標準に基づくユーザーインターフェースツールを統合しています。 +独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 - * Swagger UI - * ReDoc +そして、標準に基づくユーザーインターフェースツールを統合しています。 - この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。 +* Swagger UI +* ReDoc + +この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。 + +/// ### Flask REST フレームワーク @@ -134,8 +147,11 @@ APIが必要とするもう一つの大きな機能はデータのバリデー しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。 -!!! check "**FastAPI**へ与えたインスピレーション" - コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 +/// check | **FastAPI**へ与えたインスピレーション + +コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 + +/// ### Webargs @@ -147,11 +163,17 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上 素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。 -!!! info "情報" - Webargsは、Marshmallowと同じ開発者により作られました。 +/// info | 情報 + +Webargsは、Marshmallowと同じ開発者により作られました。 + +/// -!!! check "**FastAPI**へ与えたインスピレーション" - 受信したデータに対する自動的なバリデーションを持っている点。 +/// check | **FastAPI**へ与えたインスピレーション + +受信したデータに対する自動的なバリデーションを持っている点。 + +/// ### APISpec @@ -171,11 +193,17 @@ Flask, Starlette, Responderなどにおいてはそのように動作します エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。 -!!! info "情報" - APISpecは、Marshmallowと同じ開発者により作成されました。 +/// info | 情報 + +APISpecは、Marshmallowと同じ開発者により作成されました。 + +/// + +/// check | **FastAPI**へ与えたインスピレーション + +OpenAPIという、APIについてのオープンな標準をサポートしている点。 -!!! check "**FastAPI**へ与えたインスピレーション" - OpenAPIという、APIについてのオープンな標準をサポートしている点。 +/// ### Flask-apispec @@ -197,11 +225,17 @@ Flask、Flask-apispec、Marshmallow、Webargsの組み合わせは、**FastAPI** そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}の元となっていました。 -!!! info "情報" - Flask-apispecはMarshmallowと同じ開発者により作成されました。 +/// info | 情報 -!!! check "**FastAPI**へ与えたインスピレーション" - シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 +Flask-apispecはMarshmallowと同じ開発者により作成されました。 + +/// + +/// check | **FastAPI**へ与えたインスピレーション + +シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 + +/// ### NestJS (とAngular) @@ -217,24 +251,33 @@ Angular 2にインスピレーションを受けた、統合された依存性 入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。 -!!! check "**FastAPI**へ与えたインスピレーション" - 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 +/// check | **FastAPI**へ与えたインスピレーション + +素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 + +強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。 - 強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。 +/// ### Sanic `asyncio`に基づいた、Pythonのフレームワークの中でも非常に高速なものの一つです。Flaskと非常に似た作りになっています。 -!!! note "技術詳細" - Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。 +/// note | 技術詳細 - `Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。 +Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。 -!!! check "**FastAPI**へ与えたインスピレーション" - 物凄い性能を出す方法を見つけた点。 +`Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。 - **FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。 +/// + +/// check | **FastAPI**へ与えたインスピレーション + +物凄い性能を出す方法を見つけた点。 + +**FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。 + +/// ### Falcon @@ -246,12 +289,15 @@ Pythonのウェブフレームワーク標準規格 (WSGI) を使用していま そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。 -!!! check "**FastAPI**へ与えたインスピレーション" - 素晴らしい性能を得るための方法を見つけた点。 +/// check | **FastAPI**へ与えたインスピレーション + +素晴らしい性能を得るための方法を見つけた点。 + +Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。 - Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。 +**FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。 - **FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。 +/// ### Molten @@ -269,10 +315,13 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。 -!!! check "**FastAPI**へ与えたインスピレーション" - モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 +/// check | **FastAPI**へ与えたインスピレーション - 同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。) +モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 + +同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。) + +/// ### Hug @@ -288,15 +337,21 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。 -!!! info "情報" - HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 +/// info | 情報 + +HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 + +/// + +/// check | **FastAPI**へ与えたインスピレーション + +HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 -!!! check "**FastAPI**へ与えたインスピレーション" - HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 +Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。 - Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。 +Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。 - Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。 +/// ### APIStar (<= 0.5) @@ -322,23 +377,29 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 今ではAPIStarはOpenAPI仕様を検証するためのツールセットであり、ウェブフレームワークではありません。 -!!! info "情報" - APIStarはTom Christieにより開発されました。以下の開発者でもあります: +/// info | 情報 - * Django REST Framework - * Starlette (**FastAPI**のベースになっています) - * Uvicorn (Starletteや**FastAPI**で利用されています) +APIStarはTom Christieにより開発されました。以下の開発者でもあります: -!!! check "**FastAPI**へ与えたインスピレーション" - 存在そのもの。 +* Django REST Framework +* Starlette (**FastAPI**のベースになっています) +* Uvicorn (Starletteや**FastAPI**で利用されています) - 複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。 +/// - そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。 +/// check | **FastAPI**へ与えたインスピレーション - その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。 +存在そのもの。 - 私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。 +複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。 + +そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。 + +その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。 + +私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。 + +/// ## **FastAPI**が利用しているもの @@ -350,10 +411,13 @@ Pydanticは、Pythonの型ヒントを元にデータのバリデーション、 Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。 -!!! check "**FastAPI**での使用用途" - データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 +/// check | **FastAPI**での使用用途 + +データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 + +**FastAPI**はJSON SchemaのデータをOpenAPIに利用します。 - **FastAPI**はJSON SchemaのデータをOpenAPIに利用します。 +/// ### Starlette @@ -383,17 +447,23 @@ Starletteは基本的なWebマイクロフレームワークの機能をすべ これは **FastAPI** が追加する主な機能の一つで、すべての機能は Pythonの型ヒントに基づいています (Pydanticを使用しています) 。これに加えて、依存性注入の仕組み、セキュリティユーティリティ、OpenAPIスキーマ生成などがあります。 -!!! note "技術詳細" - ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。 +/// note | 技術詳細 - しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。 +ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。 -!!! check "**FastAPI**での使用用途" - webに関するコアな部分を全て扱います。その上に機能を追加します。 +しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。 - `FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。 +/// - 基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。 +/// check | **FastAPI**での使用用途 + +webに関するコアな部分を全て扱います。その上に機能を追加します。 + +`FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。 + +基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。 + +/// ### Uvicorn @@ -403,12 +473,15 @@ Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構 Starletteや**FastAPI**のサーバーとして推奨されています。 -!!! check "**FastAPI**が推奨する理由" - **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。 +/// check | **FastAPI**が推奨する理由 + +**FastAPI**アプリケーションを実行するメインのウェブサーバーである点。 + +Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。 - Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。 +詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。 - 詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。 +/// ## ベンチマーク と スピード diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md index 934cea0ef..d1da1f82d 100644 --- a/docs/ja/docs/async.md +++ b/docs/ja/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "備考" - `async def` を使用して作成された関数の内部でしか `await` は使用できません。 +/// note | 備考 + +`async def` を使用して作成された関数の内部でしか `await` は使用できません。 + +/// --- @@ -355,12 +358,15 @@ async def read_burgers(): ## 非常に発展的な技術的詳細 -!!! warning "注意" - 恐らくスキップしても良いでしょう。 +/// warning | 注意 + +恐らくスキップしても良いでしょう。 + +この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。 - この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。 +かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。 - かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。 +/// ### Path operation 関数 @@ -368,7 +374,7 @@ async def read_burgers(): 上記の方法と違った方法の別の非同期フレームワークから来ており、小さなパフォーマンス向上 (約100ナノ秒) のために通常の `def` を使用して些細な演算のみ行う *path operation 関数* を定義するのに慣れている場合は、**FastAPI**ではまったく逆の効果になることに注意してください。このような場合、*path operation 関数* がブロッキングI/Oを実行しないのであれば、`async def` の使用をお勧めします。 -それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](index.md#performance){.internal-link target=_blank}可能性があります。 +それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](index.md#_10){.internal-link target=_blank}可能性があります。 ### 依存関係 @@ -390,4 +396,4 @@ async def read_burgers(): 繰り返しになりますが、これらは非常に技術的な詳細であり、検索して辿り着いた場合は役立つでしょう。 -それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: 急いでいますか?。 +それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: 急いでいますか?。 diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md index 31db51c52..3ee742ec2 100644 --- a/docs/ja/docs/contributing.md +++ b/docs/ja/docs/contributing.md @@ -24,71 +24,84 @@ $ python -m venv env 新しい環境を有効化するには: -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
- もしwindows用のBash (例えば、Git Bash)を使っているなら: +//// -
+//// tab | Windows Bash - ```console - $ source ./env/Scripts/activate - ``` +もしwindows用のBash (例えば、Git Bash)を使っているなら: -
+
+ +```console +$ source ./env/Scripts/activate +``` + +
+ +//// 動作の確認には、下記を実行します: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ Get-Command pip +
- some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip -
+some/directory/fastapi/env/bin/pip +``` + +
+ +//// `env/bin/pip`に`pip`バイナリが表示される場合は、正常に機能しています。🎉 -!!! tip "豆知識" - この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。 +/// tip | 豆知識 + +この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。 - これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。 +これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。 + +/// ### pip @@ -152,8 +165,11 @@ $ bash scripts/format-imports.sh そして、翻訳を処理するためのツール/スクリプトが、`./scripts/docs.py`に用意されています。 -!!! tip "豆知識" - `./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。 +/// tip | 豆知識 + +`./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。 + +/// すべてのドキュメントが、Markdown形式で`./docs/en/`ディレクトリにあります。 @@ -236,14 +252,17 @@ Uvicornはデフォルトでポート`8000`を使用するため、ポート`800 #### 豆知識とガイドライン -* あなたの言語の今あるプルリクエストを確認し、変更や承認をするレビューを追加します。 +* あなたの言語の今あるプルリクエストを確認し、変更や承認をするレビューを追加します。 + +/// tip | 豆知識 + +すでにあるプルリクエストに修正提案つきのコメントを追加できます。 -!!! tip "豆知識" - すでにあるプルリクエストに修正提案つきのコメントを追加できます。 +修正提案の承認のためにプルリクエストのレビューの追加のドキュメントを確認してください。 - 修正提案の承認のためにプルリクエストのレビューの追加のドキュメントを確認してください。 +/// -* issuesをチェックして、あなたの言語に対応する翻訳があるかどうかを確認してください。 +* issuesをチェックして、あなたの言語に対応する翻訳があるかどうかを確認してください。 * 翻訳したページごとに1つのプルリクエストを追加します。これにより、他のユーザーがレビューしやすくなります。 @@ -263,8 +282,11 @@ Uvicornはデフォルトでポート`8000`を使用するため、ポート`800 スペイン語の場合、2文字のコードは`es`です。したがって、スペイン語のディレクトリは`docs/es/`です。 -!!! tip "豆知識" - メイン (「公式」) 言語は英語で、`docs/en/`にあります。 +/// tip | 豆知識 + +メイン (「公式」) 言語は英語で、`docs/en/`にあります。 + +/// 次に、ドキュメントのライブサーバーをスペイン語で実行します: @@ -301,8 +323,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip "豆知識" - パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。 +/// tip | 豆知識 + +パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。 + +/// * ここで、英語のMkDocs構成ファイルを開きます: @@ -373,10 +398,13 @@ Updating en これで、新しく作成された`docs/ht/`ディレクトリをコードエディターから確認できます。 -!!! tip "豆知識" - 翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。 +/// tip | 豆知識 + +翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。 + +そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀 - そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀 +/// まず、メインページの`docs/ht/index.md`を翻訳します。 diff --git a/docs/ja/docs/deployment/concepts.md b/docs/ja/docs/deployment/concepts.md index 38cbca219..c6b21fd1b 100644 --- a/docs/ja/docs/deployment/concepts.md +++ b/docs/ja/docs/deployment/concepts.md @@ -30,7 +30,7 @@ ## セキュリティ - HTTPS -[前チャプターのHTTPSについて](./https.md){.internal-link target=_blank}では、HTTPSがどのようにAPIを暗号化するのかについて学びました。 +[前チャプターのHTTPSについて](https.md){.internal-link target=_blank}では、HTTPSがどのようにAPIを暗号化するのかについて学びました。 通常、アプリケーションサーバにとって**外部の**コンポーネントである**TLS Termination Proxy**によって提供されることが一般的です。このプロキシは通信の暗号化を担当します。 @@ -151,10 +151,13 @@ FastAPIでWeb APIを構築する際に、コードにエラーがある場合、 しかし、実行中の**プロセス**をクラッシュさせるような本当にひどいエラーの場合、少なくとも2〜3回ほどプロセスを**再起動**させる外部コンポーネントが必要でしょう。 -!!! tip - ...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。 +/// tip - そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 +...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。 + +そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 + +/// あなたはおそらく**外部コンポーネント**がアプリケーションの再起動を担当することを望むと考えます。 なぜなら、その時点でUvicornとPythonを使った同じアプリケーションはすでにクラッシュしており、同じアプリケーションの同じコードに対して何もできないためです。 @@ -188,7 +191,7 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ ### ワーカー・プロセス と ポート -[HTTPSについて](./https.md){.internal-link target=_blank}のドキュメントで、1つのサーバーで1つのポートとIPアドレスの組み合わせでリッスンできるのは1つのプロセスだけであることを覚えていますでしょうか? +[HTTPSについて](https.md){.internal-link target=_blank}のドキュメントで、1つのサーバーで1つのポートとIPアドレスの組み合わせでリッスンできるのは1つのプロセスだけであることを覚えていますでしょうか? これはいまだに同じです。 @@ -243,11 +246,14 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ * **クラウド・サービス**によるレプリケーション * クラウド・サービスはおそらく**あなたのためにレプリケーションを処理**します。**実行するプロセス**や使用する**コンテナイメージ**を定義できるかもしれませんが、いずれにせよ、それはおそらく**単一のUvicornプロセス**であり、クラウドサービスはそのレプリケーションを担当するでしょう。 -!!! tip - これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。 - +/// tip + +これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。 + + +コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. - コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}. +/// ## 開始前の事前のステップ @@ -265,10 +271,13 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ もちろん、事前のステップを何度も実行しても問題がない場合もあり、その際は対処がかなり楽になります。 -!!! tip - また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。 +/// tip - その場合は、このようなことを心配する必要はないです。🤷 +また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。 + +その場合は、このようなことを心配する必要はないです。🤷 + +/// ### 事前ステップの戦略例 @@ -280,9 +289,12 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ * 事前のステップを実行し、アプリケーションを起動するbashスクリプト * 利用するbashスクリプトを起動/再起動したり、エラーを検出したりする方法は以前として必要になるでしょう。 -!!! tip - - コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}. +/// tip + + +コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. + +/// ## リソースの利用 diff --git a/docs/ja/docs/deployment/docker.md b/docs/ja/docs/deployment/docker.md index ca9dedc3c..53fc851f1 100644 --- a/docs/ja/docs/deployment/docker.md +++ b/docs/ja/docs/deployment/docker.md @@ -6,9 +6,12 @@ FastAPIアプリケーションをデプロイする場合、一般的なアプ Linuxコンテナの使用には、**セキュリティ**、**反復可能性(レプリカビリティ)**、**シンプリシティ**など、いくつかの利点があります。 -!!! tip - TODO: なぜか遷移できない - お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。 +/// tip + +TODO: なぜか遷移できない +お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。 + +///
Dockerfile プレビュー 👀 @@ -117,7 +120,7 @@ FastAPI用の**Dockerイメージ**を、**公式Python**イメージに基づ 最も一般的な方法は、`requirements.txt` ファイルにパッケージ名とそのバージョンを 1 行ずつ書くことです。 -もちろん、[FastAPI バージョンについて](./versions.md){.internal-link target=_blank}で読んだのと同じアイデアを使用して、バージョンの範囲を設定します。 +もちろん、[FastAPI バージョンについて](versions.md){.internal-link target=_blank}で読んだのと同じアイデアを使用して、バージョンの範囲を設定します。 例えば、`requirements.txt` は次のようになります: @@ -139,10 +142,13 @@ Successfully installed fastapi pydantic uvicorn
-!!! info - パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。 +/// info + +パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。 - Poetryを使った例は、後述するセクションでご紹介します。👇 +Poetryを使った例は、後述するセクションでご紹介します。👇 + +/// ### **FastAPI**コードを作成する @@ -207,8 +213,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 4. 要件ファイルにあるパッケージの依存関係をインストールします `--no-cache-dir` オプションはダウンロードしたパッケージをローカルに保存しないように `pip` に指示します。これは、同じパッケージをインストールするために `pip` を再度実行する場合にのみ有効ですが、コンテナで作業する場合はそうではないです。 - !!! note - `--no-cache-dir`は`pip`に関連しているだけで、Dockerやコンテナとは何の関係もないです。 + /// note + + `--no-cache-dir`は`pip`に関連しているだけで、Dockerやコンテナとは何の関係もないです。 + + /// `--upgrade` オプションは、パッケージが既にインストールされている場合、`pip` にアップグレードするように指示します。 @@ -230,8 +239,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] そのためプログラムは `/code` で開始しその中にあなたのコードがある `./app` ディレクトリがあるので、**Uvicorn** は `app.main` から `app` を参照し、**インポート** することができます。 -!!! tip - コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆 +/// tip + +コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆 + +/// これで、次のようなディレクトリ構造になるはずです: @@ -305,10 +317,13 @@ $ docker build -t myimage . -!!! tip - 末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。 +/// tip + +末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。 - この場合、同じカレント・ディレクトリ(`.`)です。 +この場合、同じカレント・ディレクトリ(`.`)です。 + +/// ### Dockerコンテナの起動する @@ -384,7 +399,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## デプロイメントのコンセプト -コンテナという観点から、[デプロイのコンセプト](./concepts.md){.internal-link target=_blank}に共通するいくつかについて、もう一度説明しましょう。 +コンテナという観点から、[デプロイのコンセプト](concepts.md){.internal-link target=_blank}に共通するいくつかについて、もう一度説明しましょう。 コンテナは主に、アプリケーションの**ビルドとデプロイ**のプロセスを簡素化するためのツールですが、これらの**デプロイのコンセプト**を扱うための特定のアプローチを強制するものではないです。 @@ -405,8 +420,11 @@ FastAPI アプリケーションの **コンテナ・イメージ**(および 例えばTraefikのように、**HTTPS**と**証明書**の**自動**取得を扱う別のコンテナである可能性もあります。 -!!! tip - TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。 +/// tip + +TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。 + +/// あるいは、(コンテナ内でアプリケーションを実行しながら)クラウド・プロバイダーがサービスの1つとしてHTTPSを処理することもできます。 @@ -434,8 +452,11 @@ Kubernetesのような分散コンテナ管理システムの1つは通常、入 このコンポーネントはリクエストの **負荷** を受け、 (うまくいけば) その負荷を**バランスよく** ワーカーに分配するので、一般に **ロードバランサ** とも呼ばれます。 -!!! tip -  HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。 +/// tip + +HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。 + +/// そしてコンテナで作業する場合、コンテナの起動と管理に使用する同じシステムには、**ロードバランサー**(**TLS Termination Proxy**の可能性もある)から**ネットワーク通信**(HTTPリクエストなど)をアプリのあるコンテナ(複数可)に送信するための内部ツールが既にあるはずです。 @@ -461,7 +482,7 @@ Kubernetesのような分散コンテナ管理システムの1つは通常、入 もちろん、**特殊なケース**として、**Gunicornプロセスマネージャ**を持つ**コンテナ**内で複数の**Uvicornワーカープロセス**を起動させたい場合があります。 -このような場合、**公式のDockerイメージ**を使用することができます。このイメージには、複数の**Uvicornワーカープロセス**を実行するプロセスマネージャとして**Gunicorn**が含まれており、現在のCPUコアに基づいてワーカーの数を自動的に調整するためのデフォルト設定がいくつか含まれています。詳しくは後述の[Gunicornによる公式Dockerイメージ - Uvicorn](#gunicornによる公式dockerイメージ---Uvicorn)で説明します。 +このような場合、**公式のDockerイメージ**を使用することができます。このイメージには、複数の**Uvicornワーカープロセス**を実行するプロセスマネージャとして**Gunicorn**が含まれており、現在のCPUコアに基づいてワーカーの数を自動的に調整するためのデフォルト設定がいくつか含まれています。詳しくは後述の[Gunicornによる公式Dockerイメージ - Uvicorn](#gunicorndocker-uvicorn)で説明します。 以下は、それが理にかなっている場合の例です: @@ -520,8 +541,11 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ 複数の**コンテナ**があり、おそらくそれぞれが**単一のプロセス**を実行している場合(**Kubernetes**クラスタなど)、レプリケートされたワーカーコンテナを実行する**前に**、単一のコンテナで**事前のステップ**の作業を行う**別のコンテナ**を持ちたいと思うでしょう。 -!!! info - もしKubernetesを使用している場合, これはおそらくInit コンテナでしょう。 +/// info + +もしKubernetesを使用している場合, これはおそらくInit コンテナでしょう。 + +/// ユースケースが事前のステップを**並列で複数回**実行するのに問題がない場合(例:データベースの準備チェック)、メインプロセスを開始する前に、それらのステップを各コンテナに入れることが可能です。 @@ -531,14 +555,17 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ ## Gunicornによる公式Dockerイメージ - Uvicorn -前の章で詳しく説明したように、Uvicornワーカーで動作するGunicornを含む公式のDockerイメージがあります: [Server Workers - Gunicorn と Uvicorn](./server-workers.md){.internal-link target=_blank}で詳しく説明しています。 +前の章で詳しく説明したように、Uvicornワーカーで動作するGunicornを含む公式のDockerイメージがあります: [Server Workers - Gunicorn と Uvicorn](server-workers.md){.internal-link target=_blank}で詳しく説明しています。 このイメージは、主に上記で説明した状況で役に立つでしょう: [複数のプロセスと特殊なケースを持つコンテナ(Containers with Multiple Processes and Special Cases)](#containers-with-multiple-processes-and-special-cases) * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning - このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。 +/// warning + +このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。 + +/// このイメージには、利用可能なCPUコアに基づいて**ワーカー・プロセスの数**を設定する**オートチューニング**メカニズムが含まれています。 @@ -546,8 +573,11 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ また、スクリプトで**開始前の事前ステップ**を実行することもサポートしている。 -!!! tip - すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: tiangolo/uvicorn-gunicorn-fastapi +/// tip + +すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: tiangolo/uvicorn-gunicorn-fastapi + +/// ### 公式Dockerイメージのプロセス数 @@ -672,8 +702,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 9. 生成された `requirements.txt` ファイルにあるパッケージの依存関係をインストールします 10. app` ディレクトリを `/code` ディレクトリにコピーします 11. uvicorn` コマンドを実行して、`app.main` からインポートした `app` オブジェクトを使用するように指示します -!!! tip - "+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます +/// tip + +"+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます + +/// **Dockerステージ**は`Dockerfile`の一部で、**一時的なコンテナイメージ**として動作します。 diff --git a/docs/ja/docs/deployment/https.md b/docs/ja/docs/deployment/https.md index a291f870f..ac40b0982 100644 --- a/docs/ja/docs/deployment/https.md +++ b/docs/ja/docs/deployment/https.md @@ -4,8 +4,11 @@ HTTPSは単に「有効」か「無効」かで決まるものだと思いがち しかし、それよりもはるかに複雑です。 -!!! tip - もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。 +/// tip + +もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。 + +/// 利用者の視点から **HTTPS の基本を学ぶ**に当たっては、次のリソースをオススメします: https://howhttps.works/. @@ -75,8 +78,11 @@ DNSサーバーでは、**取得したドメイン**をあなたのサーバー これはおそらく、最初の1回だけあり、すべてをセットアップするときに行うでしょう。 -!!! tip - ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。 +/// tip + +ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。 + +/// ### DNS @@ -124,8 +130,11 @@ TLS Termination Proxyは、1つ以上の**TLS証明書**(HTTPS証明書)に これが**HTTPS**であり、純粋な(暗号化されていない)TCP接続ではなく、**セキュアなTLS接続**の中に**HTTP**があるだけです。 -!!! tip - 通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。 +/// tip + +通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。 + +/// ### HTTPS リクエスト diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md index 67010a66f..4ea6bd8ff 100644 --- a/docs/ja/docs/deployment/manually.md +++ b/docs/ja/docs/deployment/manually.md @@ -4,66 +4,77 @@ 以下の様なASGI対応のサーバをインストールする必要があります: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, uvloopとhttptoolsを基にした高速なASGIサーバ。 +* Uvicorn, uvloopとhttptoolsを基にした高速なASGIサーバ。 -
+
- ```console - $ pip install "uvicorn[standard]" +```console +$ pip install "uvicorn[standard]" - ---> 100% - ``` +---> 100% +``` -
+
-!!! tip "豆知識" - `standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。 +//// - これには、`asyncio` の高性能な完全互換品である `uvloop` が含まれ、並行処理のパフォーマンスが大幅に向上します。 +/// tip | 豆知識 -=== "Hypercorn" +`standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。 - * Hypercorn, HTTP/2にも対応しているASGIサーバ。 +これには、`asyncio` の高性能な完全互換品である `uvloop` が含まれ、並行処理のパフォーマンスが大幅に向上します。 -
+/// - ```console - $ pip install hypercorn +//// tab | Hypercorn - ---> 100% - ``` +* Hypercorn, HTTP/2にも対応しているASGIサーバ。 -
+
- ...または、これら以外のASGIサーバ。 +```console +$ pip install hypercorn + +---> 100% +``` + +
+ +...または、これら以外のASGIサーバ。 + +//// そして、チュートリアルと同様な方法でアプリケーションを起動して下さい。ただし、以下の様に`--reload` オプションは使用しないで下さい: -=== "Uvicorn" +//// tab | Uvicorn + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 -
+INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +
- INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// -
+//// tab | Hypercorn -=== "Hypercorn" +
-
+```console +$ hypercorn main:app --bind 0.0.0.0:80 - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +
-
+//// 停止した場合に自動的に再起動させるツールを設定したいかもしれません。 diff --git a/docs/ja/docs/deployment/server-workers.md b/docs/ja/docs/deployment/server-workers.md index e1ea165a2..38ceab017 100644 --- a/docs/ja/docs/deployment/server-workers.md +++ b/docs/ja/docs/deployment/server-workers.md @@ -13,15 +13,18 @@ アプリケーションをデプロイする際には、**複数のコア**を利用し、そしてより多くのリクエストを処理できるようにするために、プロセスの**レプリケーション**を持つことを望むでしょう。 -前のチャプターである[デプロイメントのコンセプト](./concepts.md){.internal-link target=_blank}にて見てきたように、有効な戦略がいくつかあります。 +前のチャプターである[デプロイメントのコンセプト](concepts.md){.internal-link target=_blank}にて見てきたように、有効な戦略がいくつかあります。 ここでは**Gunicorn**が**Uvicornのワーカー・プロセス**を管理する場合の使い方について紹介していきます。 -!!! info - - DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank} +/// info - 特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。 + +DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank} + +特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。 + +/// ## GunicornによるUvicornのワーカー・プロセスの管理 @@ -167,7 +170,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## コンテナとDocker -次章の[コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}では、その他の**デプロイのコンセプト**を扱うために実施するであろう戦略をいくつか紹介します。 +次章の[コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}では、その他の**デプロイのコンセプト**を扱うために実施するであろう戦略をいくつか紹介します。 また、**GunicornとUvicornワーカー**を含む**公式Dockerイメージ**と、簡単なケースに役立ついくつかのデフォルト設定も紹介します。 diff --git a/docs/ja/docs/deployment/versions.md b/docs/ja/docs/deployment/versions.md index 03cccb3f3..7575fc4f7 100644 --- a/docs/ja/docs/deployment/versions.md +++ b/docs/ja/docs/deployment/versions.md @@ -42,8 +42,11 @@ PoetryやPipenvなど、他のインストール管理ツールを使用して FastAPIでは「パッチ」バージョンはバグ修正と非破壊的な変更に留めるという規約に従っています。 -!!! tip "豆知識" - 「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。 +/// tip | 豆知識 + +「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。 + +/// 従って、以下の様なバージョンの固定が望ましいです: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 破壊的な変更と新機能実装は「マイナー」バージョンで加えられます。 -!!! tip "豆知識" - 「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。 +/// tip | 豆知識 + +「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。 + +/// ## FastAPIのバージョンのアップグレード diff --git a/docs/ja/docs/external-links.md b/docs/ja/docs/external-links.md deleted file mode 100644 index aca5d5b34..000000000 --- a/docs/ja/docs/external-links.md +++ /dev/null @@ -1,33 +0,0 @@ -# 外部リンク・記事 - -**FastAPI**には、絶えず成長している素晴らしいコミュニティがあります。 - -**FastAPI**に関連する投稿、記事、ツール、およびプロジェクトは多数あります。 - -それらの不完全なリストを以下に示します。 - -!!! tip "豆知識" - ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 プルリクエストして下さい。 - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## プロジェクト - -`fastapi`トピックの最新のGitHubプロジェクト: - -
-
diff --git a/docs/ja/docs/fastapi-people.md b/docs/ja/docs/fastapi-people.md deleted file mode 100644 index ff75dcbce..000000000 --- a/docs/ja/docs/fastapi-people.md +++ /dev/null @@ -1,179 +0,0 @@ -# FastAPI People - -FastAPIには、様々なバックグラウンドの人々を歓迎する素晴らしいコミュニティがあります。 - -## Creator - Maintainer - -こんにちは! 👋 - -これが私です: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
- -{% endif %} - -私は **FastAPI** の作成者および Maintainer です。詳しくは [FastAPIを応援 - ヘルプの入手 - 開発者とつながる](help-fastapi.md#開発者とつながる){.internal-link target=_blank} に記載しています。 - -...ところで、ここではコミュニティを紹介したいと思います。 - ---- - -**FastAPI** は、コミュニティから多くのサポートを受けています。そこで、彼らの貢献にスポットライトを当てたいと思います。 - -紹介するのは次のような人々です: - -* [GitHub issuesで他の人を助ける](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 -* [プルリクエストをする](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* プルリクエストのレビューをする ([特に翻訳に重要](contributing.md#translations){.internal-link target=_blank})。 - -彼らに大きな拍手を。👏 🙇 - -## 先月最もアクティブだったユーザー - -彼らは、先月の[GitHub issuesで最も多くの人を助けた](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}ユーザーです。☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Experts - -**FastAPI experts** を紹介します。🤓 - -彼らは、*これまでに* [GitHub issuesで最も多くの人を助けた](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}ユーザーです。 - -多くの人を助けることでexpertsであると示されています。✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Top Contributors - -**Top Contributors** を紹介します。👷 - -彼らは、*マージされた* [最も多くのプルリクエストを作成した](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}ユーザーです。 - -ソースコード、ドキュメント、翻訳などに貢献してくれました。📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -他にもたくさん (100人以上) の contributors がいます。FastAPI GitHub Contributors ページですべての contributors を確認できます。👷 - -## Top Reviewers - -以下のユーザーは **Top Reviewers** です。🕵️ - -### 翻訳のレビュー - -私は少しの言語しか話せません (もしくはあまり上手ではありません😅)。したがって、reviewers は、ドキュメントの[**翻訳を承認する権限**](contributing.md#translations){.internal-link target=_blank}を持っています。それらがなければ、いくつかの言語のドキュメントはなかったでしょう。 - ---- - -**Top Reviewers** 🕵️は、他の人からのプルリクエストのほとんどをレビューし、コード、ドキュメント、特に**翻訳**の品質を保証しています。 - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsors - -**Sponsors** を紹介します。😎 - -彼らは、GitHub Sponsors を介して私の **FastAPI** などに関する活動を支援してくれています。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### Gold Sponsors - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Silver Sponsors - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronze Sponsors - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Individual Sponsors - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## データについて - 技術詳細 - -このページの目的は、他の人を助けるためのコミュニティの努力にスポットライトを当てるためです。 - -特に、他の人の issues を支援したり、翻訳のプルリクエストを確認したりするなど、通常は目立たず、多くの場合、より困難な作業を含みます。 - -データは毎月集計されます。ソースコードはこちらで確認できます。 - -ここでは、スポンサーの貢献も強調しています。 - -アルゴリズム、セクション、閾値などは更新されるかもしれません (念のために 🤷)。 diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index 98c59e7c4..4024590cf 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -62,10 +62,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info "情報" - `**second_user_data` は以下を意味します: +/// info | 情報 - `second_user_data`辞書のキーと値を直接、キーと値の引数として渡します。これは、`User(id=4, name="Mary", joined="2018-11-30")`と同等です。 +`**second_user_data` は以下を意味します: + +`second_user_data`辞書のキーと値を直接、キーと値の引数として渡します。これは、`User(id=4, name="Mary", joined="2018-11-30")`と同等です。 + +/// ### エディタのサポート diff --git a/docs/ja/docs/help-fastapi.md b/docs/ja/docs/help-fastapi.md index e753b7ce3..d999fa127 100644 --- a/docs/ja/docs/help-fastapi.md +++ b/docs/ja/docs/help-fastapi.md @@ -12,13 +12,13 @@ FastAPIやユーザーや開発者を応援したいですか? ## GitHubで **FastAPI** にStar -GitHubでFastAPIに「Star」をつけることができます (右上部のStarボタンをクリック): https://github.com/tiangolo/fastapi. ⭐️ +GitHubでFastAPIに「Star」をつけることができます (右上部のStarボタンをクリック): https://github.com/fastapi/fastapi. ⭐️ スターを増やすことで、他のユーザーの目につきやすくなり、多くの人にとって便利なものであることを示せます。 ## GitHubレポジトリのリリースをWatch -GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリック): https://github.com/tiangolo/fastapi. 👀 +GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリック): https://github.com/fastapi/fastapi. 👀 そこで「Releases only」を選択できます。 @@ -42,7 +42,7 @@ GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリ ## **FastAPI** に関するツイート -**FastAPI** についてツイートし、開発者や他の人にどこが気に入ったのか教えてください。🎉 +**FastAPI** についてツイートし、開発者や他の人にどこが気に入ったのか教えてください。🎉 **FastAPI** がどのように使われ、どこが気に入られ、どんなプロジェクト/会社で使われているかなどについて知りたいです。 @@ -54,11 +54,11 @@ GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリ ## GitHub issuesで他の人を助ける -既存のissuesを確認して、他の人を助けてみてください。皆さんが回答を知っているかもしれない質問がほとんどです。🤓 +既存のissuesを確認して、他の人を助けてみてください。皆さんが回答を知っているかもしれない質問がほとんどです。🤓 ## GitHubレポジトリをWatch -GitHubでFastAPIを「watch」できます (右上部の「watch」ボタンをクリック): https://github.com/tiangolo/fastapi. 👀 +GitHubでFastAPIを「watch」できます (右上部の「watch」ボタンをクリック): https://github.com/fastapi/fastapi. 👀 「Releases only」ではなく「Watching」を選択すると、新たなissueが立てられた際に通知されます。 @@ -66,7 +66,7 @@ GitHubでFastAPIを「watch」できます (右上部の「watch」ボタンを ## issuesを立てる -GitHubレポジトリで新たなissueを立てられます。例えば: +GitHubレポジトリで新たなissueを立てられます。例えば: * 質問、または、問題の報告 * 新機能の提案 @@ -75,7 +75,7 @@ GitHubレポジトリでプルリクエストを作成できます: +以下の様なプルリクエストを作成できます: * ドキュメントのタイプミスを修正。 * 新たなドキュメントセクションを提案。 diff --git a/docs/ja/docs/history-design-future.md b/docs/ja/docs/history-design-future.md index 5d53cf77a..bc4a160ea 100644 --- a/docs/ja/docs/history-design-future.md +++ b/docs/ja/docs/history-design-future.md @@ -1,6 +1,6 @@ # 歴史、設計、そしてこれから -少し前に、**FastAPI** +少し前に、**FastAPI** のユーザーに以下の様に尋ねられました: > このプロジェクトの歴史は?何もないところから、数週間ですごいものができているようです。 [...] diff --git a/docs/ja/docs/how-to/conditional-openapi.md b/docs/ja/docs/how-to/conditional-openapi.md index b892ed6c6..053d481f7 100644 --- a/docs/ja/docs/how-to/conditional-openapi.md +++ b/docs/ja/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ 例えば、 ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` ここでは `openapi_url` の設定を、デフォルトの `"/openapi.json"` のまま宣言しています。 diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 4f66b1a40..682c94e83 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ FastAPI framework, high performance, easy to learn, fast to code, ready for production

- - Build Status + + Build Status - - Coverage + + Coverage Package version @@ -20,15 +26,15 @@ **ドキュメント**: https://fastapi.tiangolo.com -**ソースコード**: https://github.com/tiangolo/fastapi +**ソースコード**: https://github.com/fastapi/fastapi --- -FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 +FastAPI は、Pythonの標準である型ヒントに基づいてPython 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 主な特徴: -- **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげです)。 [最も高速な Python フレームワークの一つです](#performance). +- **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげです)。 [最も高速な Python フレームワークの一つです](#_10). - **高速なコーディング**: 開発速度を約 200%~300%向上させます。 \* - **少ないバグ**: 開発者起因のヒューマンエラーを約 40%削減します。 \* @@ -61,7 +67,7 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以 "_[...] 最近 **FastAPI** を使っています。 [...] 実際に私のチームの全ての **Microsoft の機械学習サービス** で使用する予定です。 そのうちのいくつかのコアな**Windows**製品と**Office**製品に統合されつつあります。_" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -85,7 +91,7 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以 "_正直、超堅実で洗練されているように見えます。いろんな意味で、それは私がハグしたかったものです。_" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -107,8 +113,6 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以 ## 必要条件 -Python 3.8+ - FastAPI は巨人の肩の上に立っています。 - Web の部分はStarlette @@ -126,7 +130,7 @@ $ pip install fastapi -本番環境では、Uvicorn または、 Hypercornのような、 ASGI サーバーが必要になります。 +本番環境では、Uvicorn または、 Hypercornのような、 ASGI サーバーが必要になります。
@@ -431,7 +435,7 @@ item: Item Pydantic によって使用されるもの: -- email_validator - E メールの検証 +- email-validator - E メールの検証 Starlette によって使用されるもの: @@ -441,12 +445,12 @@ Starlette によって使用されるもの: - itsdangerous - `SessionMiddleware` サポートのためには必要です。 - pyyaml - Starlette の `SchemaGenerator` サポートのために必要です。 (FastAPI では必要ないでしょう。) - graphene - `GraphQLApp` サポートのためには必要です。 -- ujson - `UJSONResponse`を使用する場合は必須です。 FastAPI / Starlette に使用されるもの: - uvicorn - アプリケーションをロードしてサーブするサーバーのため。 - orjson - `ORJSONResponse`を使用したい場合は必要です。 +- ujson - `UJSONResponse`を使用する場合は必須です。 これらは全て `pip install fastapi[all]`でインストールできます。 diff --git a/docs/ja/docs/learn/index.md b/docs/ja/docs/learn/index.md new file mode 100644 index 000000000..2f24c670a --- /dev/null +++ b/docs/ja/docs/learn/index.md @@ -0,0 +1,5 @@ +# 学習 + +ここでは、**FastAPI** を学習するための入門セクションとチュートリアルを紹介します。 + +これは、FastAPIを学習するにあたっての**書籍**や**コース**であり、**公式**かつ推奨される方法とみなすことができます 😎 diff --git a/docs/ja/docs/project-generation.md b/docs/ja/docs/project-generation.md index 4b6f0f9fd..daef52efa 100644 --- a/docs/ja/docs/project-generation.md +++ b/docs/ja/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: **FastAPI** バックエンド: +* Python **FastAPI** バックエンド: * **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげ)。 * **直感的**: 素晴らしいエディタのサポートや 補完。 デバッグ時間の短縮。 * **簡単**: 簡単に利用、習得できるようなデザイン。ドキュメントを読む時間を削減。 diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md index f8e02fdc3..77ddf4654 100644 --- a/docs/ja/docs/python-types.md +++ b/docs/ja/docs/python-types.md @@ -12,15 +12,18 @@ しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。 -!!! note "備考" - もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 +/// note | 備考 + +もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 + +/// ## 動機 簡単な例から始めてみましょう: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` このプログラムを実行すると以下が出力されます: @@ -36,7 +39,7 @@ John Doe * 真ん中にスペースを入れて連結します。 ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### 編集 @@ -80,7 +83,7 @@ John Doe それが「型ヒント」です: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` これは、以下のようにデフォルト値を宣言するのと同じではありません: @@ -110,7 +113,7 @@ John Doe この関数を見てください。すでに型ヒントを持っています: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。 @@ -120,7 +123,7 @@ John Doe これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 型の宣言 @@ -141,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 型パラメータを持つジェネリック型 @@ -159,7 +162,7 @@ John Doe `typing`から`List`をインポートします(大文字の`L`を含む): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 同じようにコロン(`:`)の構文で変数を宣言します。 @@ -169,13 +172,16 @@ John Doe リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。 ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "豆知識" - 角括弧内の内部の型は「型パラメータ」と呼ばれています。 +/// tip | 豆知識 + +角括弧内の内部の型は「型パラメータ」と呼ばれています。 + +この場合、`str`は`List`に渡される型パラメータです。 - この場合、`str`は`List`に渡される型パラメータです。 +/// つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。 @@ -194,7 +200,7 @@ John Doe `tuple`と`set`の宣言も同様です: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` つまり: @@ -212,7 +218,7 @@ John Doe 2番目の型パラメータは`dict`の値です。 ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` つまり: @@ -226,7 +232,7 @@ John Doe また、`Optional`を使用して、変数が`str`のような型を持つことを宣言することもできますが、それは「オプション」であり、`None`にすることもできます。 ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` ただの`str`の代わりに`Optional[str]`を使用することで、エディタは値が常に`str`であると仮定している場合に実際には`None`である可能性があるエラーを検出するのに役立ちます。 @@ -251,13 +257,13 @@ John Doe 例えば、`Person`クラスという名前のクラスがあるとしましょう: ```Python hl_lines="1 2 3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 変数の型を`Person`として宣言することができます: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` そして、再び、すべてのエディタのサポートを得ることができます: @@ -279,11 +285,14 @@ John Doe Pydanticの公式ドキュメントから引用: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` -!!! info "情報" - Pydanticについてより学びたい方はドキュメントを参照してください. +/// info | 情報 + +Pydanticについてより学びたい方はドキュメントを参照してください. + +/// **FastAPI** はすべてPydanticをベースにしています。 @@ -311,5 +320,8 @@ Pydanticの公式ドキュメントから引用: 重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。 -!!! info "情報" - すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください +/// info | 情報 + +すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください + +/// diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md index 6094c370f..6f9340817 100644 --- a/docs/ja/docs/tutorial/background-tasks.md +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。 @@ -34,7 +34,7 @@ また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。 ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## バックグラウンドタスクの追加 @@ -42,7 +42,7 @@ *path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。 ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` は以下の引数を受け取ります: @@ -58,7 +58,7 @@ **FastAPI** は、それぞれの場合の処理​​方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。 ```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} +{!../../docs_src/background_tasks/tutorial002.py!} ``` この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。 diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md index 8f01e8216..5b3b3622b 100644 --- a/docs/ja/docs/tutorial/body-fields.md +++ b/docs/ja/docs/tutorial/body-fields.md @@ -7,33 +7,42 @@ まず、以下のようにインポートします: ```Python hl_lines="4" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` -!!! warning "注意" - `Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 +/// warning | 注意 + +`Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 + +/// ## モデルの属性の宣言 以下のように`Field`をモデルの属性として使用することができます: ```Python hl_lines="11 12 13 14" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` `Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 -!!! note "技術詳細" - 実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 +/// note | 技術詳細 + +実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 + +また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。 + +`Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。 + +`fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。 - また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。 +/// - `Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。 +/// tip | 豆知識 - `fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。 +型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 -!!! tip "豆知識" - 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 +/// ## 追加情報の追加 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md index 2ba10c583..982c23565 100644 --- a/docs/ja/docs/tutorial/body-multiple-params.md +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -9,11 +9,14 @@ また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます: ```Python hl_lines="19 20 21" -{!../../../docs_src/body_multiple_params/tutorial001.py!} +{!../../docs_src/body_multiple_params/tutorial001.py!} ``` -!!! note "備考" - この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 +/// note | 備考 + +この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 + +/// ## 複数のボディパラメータ @@ -31,7 +34,7 @@ しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます: ```Python hl_lines="22" -{!../../../docs_src/body_multiple_params/tutorial002.py!} +{!../../docs_src/body_multiple_params/tutorial002.py!} ``` この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。 @@ -53,8 +56,11 @@ } ``` -!!! note "備考" - 以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 +/// note | 備考 + +以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 + +/// **FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。 @@ -72,7 +78,7 @@ ```Python hl_lines="23" -{!../../../docs_src/body_multiple_params/tutorial003.py!} +{!../../docs_src/body_multiple_params/tutorial003.py!} ``` この場合、**FastAPI** は以下のようなボディを期待します: @@ -109,12 +115,14 @@ q: str = None 以下において: ```Python hl_lines="27" -{!../../../docs_src/body_multiple_params/tutorial004.py!} +{!../../docs_src/body_multiple_params/tutorial004.py!} ``` -!!! info "情報" - `Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 +/// info | 情報 + +`Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 +/// ## 単一のボディパラメータの埋め込み @@ -131,7 +139,7 @@ item: Item = Body(..., embed=True) 以下において: ```Python hl_lines="17" -{!../../../docs_src/body_multiple_params/tutorial005.py!} +{!../../docs_src/body_multiple_params/tutorial005.py!} ``` この場合、**FastAPI** は以下のようなボディを期待します: diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index 092e25798..dc2d5e81a 100644 --- a/docs/ja/docs/tutorial/body-nested-models.md +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -7,7 +7,7 @@ 属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます: ```Python hl_lines="12" -{!../../../docs_src/body_nested_models/tutorial001.py!} +{!../../docs_src/body_nested_models/tutorial001.py!} ``` これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。 @@ -21,7 +21,7 @@ まず、Pythonの標準の`typing`モジュールから`List`をインポートします: ```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ### タイプパラメータを持つ`List`の宣言 @@ -44,7 +44,7 @@ my_list: List[str] そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ## セット型 @@ -56,7 +56,7 @@ my_list: List[str] そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます: ```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} +{!../../docs_src/body_nested_models/tutorial003.py!} ``` これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。 @@ -80,7 +80,7 @@ Pydanticモデルの各属性には型があります。 例えば、`Image`モデルを定義することができます: ```Python hl_lines="9 10 11" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` ### サブモデルを型として使用 @@ -88,7 +88,7 @@ Pydanticモデルの各属性には型があります。 そして、それを属性の型として使用することができます: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` これは **FastAPI** が以下のようなボディを期待することを意味します: @@ -123,7 +123,7 @@ Pydanticモデルの各属性には型があります。 例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます: ```Python hl_lines="4 10" -{!../../../docs_src/body_nested_models/tutorial005.py!} +{!../../docs_src/body_nested_models/tutorial005.py!} ``` 文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。 @@ -133,7 +133,7 @@ Pydanticモデルの各属性には型があります。 Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial006.py!} +{!../../docs_src/body_nested_models/tutorial006.py!} ``` これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど): @@ -162,19 +162,25 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する } ``` -!!! info "情報" - `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 +/// info | 情報 + +`images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 + +/// ## 深くネストされたモデル 深くネストされた任意のモデルを定義することができます: ```Python hl_lines="9 14 20 23 27" -{!../../../docs_src/body_nested_models/tutorial007.py!} +{!../../docs_src/body_nested_models/tutorial007.py!} ``` -!!! info "情報" - `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 +/// info | 情報 + +`Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 + +/// ## 純粋なリストのボディ @@ -187,7 +193,7 @@ images: List[Image] 以下のように: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial008.py!} +{!../../docs_src/body_nested_models/tutorial008.py!} ``` ## あらゆる場所でのエディタサポート @@ -219,17 +225,20 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial009.py!} +{!../../docs_src/body_nested_models/tutorial009.py!} ``` -!!! tip "豆知識" - JSONはキーとして`str`しかサポートしていないことに注意してください。 +/// tip | 豆知識 + +JSONはキーとして`str`しかサポートしていないことに注意してください。 + +しかしPydanticには自動データ変換機能があります。 - しかしPydanticには自動データ変換機能があります。 +これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。 - これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。 +そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。 - そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index 7a56ef2b9..fcaeb0d16 100644 --- a/docs/ja/docs/tutorial/body-updates.md +++ b/docs/ja/docs/tutorial/body-updates.md @@ -7,7 +7,7 @@ `jsonable_encoder`を用いて、入力データをJSON形式で保存できるデータに変換することができます(例:NoSQLデータベース)。例えば、`datetime`を`str`に変換します。 ```Python hl_lines="30 31 32 33 34 35" -{!../../../docs_src/body_updates/tutorial001.py!} +{!../../docs_src/body_updates/tutorial001.py!} ``` 既存のデータを置き換えるべきデータを受け取るために`PUT`は使用されます。 @@ -34,14 +34,17 @@ つまり、更新したいデータだけを送信して、残りはそのままにしておくことができます。 -!!! Note "備考" - `PATCH`は`PUT`よりもあまり使われておらず、知られていません。 +/// note | 備考 - また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。 +`PATCH`は`PUT`よりもあまり使われておらず、知られていません。 - **FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。 +また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。 - しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。 +**FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。 + +しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。 + +/// ### Pydanticの`exclude_unset`パラメータの使用 @@ -54,7 +57,7 @@ これを使うことで、デフォルト値を省略して、設定された(リクエストで送られた)データのみを含む`dict`を生成することができます: ```Python hl_lines="34" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### Pydanticの`update`パラメータ @@ -64,7 +67,7 @@ `stored_item_model.copy(update=update_data)`のように: ```Python hl_lines="35" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### 部分的更新のまとめ @@ -83,17 +86,23 @@ * 更新されたモデルを返します。 ```Python hl_lines="30 31 32 33 34 35 36 37" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` -!!! tip "豆知識" - 実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。 +/// tip | 豆知識 + +実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。 + +しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。 + +/// + +/// note | 備考 - しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。 +入力モデルがまだ検証されていることに注目してください。 -!!! note "備考" - 入力モデルがまだ検証されていることに注目してください。 +そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。 - そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。 +**更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。 - **更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。 +/// diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index 12332991d..277ee79c8 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -8,19 +8,22 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ **リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。 -!!! info "情報" - データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 +/// info | 情報 - GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。 +データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 - 非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。 +GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。 + +非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。 + +/// ## Pydanticの `BaseModel` をインポート ます初めに、 `pydantic` から `BaseModel` をインポートする必要があります: ```Python hl_lines="2" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ## データモデルの作成 @@ -30,7 +33,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ すべての属性にpython標準の型を使用します: ```Python hl_lines="5-9" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` クエリパラメータの宣言と同様に、モデル属性がデフォルト値をもつとき、必須な属性ではなくなります。それ以外は必須になります。オプショナルな属性にしたい場合は `None` を使用してください。 @@ -60,7 +63,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ *パスオペレーション* に加えるために、パスパラメータやクエリパラメータと同じ様に宣言します: ```Python hl_lines="16" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ...そして、作成したモデル `Item` で型を宣言します。 @@ -110,23 +113,26 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ -!!! tip "豆知識" - PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。 +/// tip | 豆知識 + +PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。 - 以下のエディターサポートが強化されます: +以下のエディターサポートが強化されます: - * 自動補完 - * 型チェック - * リファクタリング - * 検索 - * インスペクション +* 自動補完 +* 型チェック +* リファクタリング +* 検索 +* インスペクション + +/// ## モデルの使用 関数内部で、モデルの全ての属性に直接アクセスできます: ```Python hl_lines="19" -{!../../../docs_src/body/tutorial002.py!} +{!../../docs_src/body/tutorial002.py!} ``` ## リクエストボディ + パスパラメータ @@ -136,7 +142,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ **FastAPI** はパスパラメータである関数パラメータは**パスから受け取り**、Pydanticモデルによって宣言された関数パラメータは**リクエストボディから受け取る**ということを認識します。 ```Python hl_lines="15-16" -{!../../../docs_src/body/tutorial003.py!} +{!../../docs_src/body/tutorial003.py!} ``` ## リクエストボディ + パスパラメータ + クエリパラメータ @@ -146,7 +152,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ **FastAPI** はそれぞれを認識し、適切な場所からデータを取得します。 ```Python hl_lines="16" -{!../../../docs_src/body/tutorial004.py!} +{!../../docs_src/body/tutorial004.py!} ``` 関数パラメータは以下の様に認識されます: @@ -155,11 +161,14 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ * パラメータが**単数型** (`int`、`float`、`str`、`bool` など)の場合は**クエリ**パラメータとして解釈されます。 * パラメータが **Pydantic モデル**型で宣言された場合、リクエスト**ボディ**として解釈されます。 -!!! note "備考" - FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 +/// note | 備考 + +FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 + +`Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。 - `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。 +/// ## Pydanticを使わない方法 -もしPydanticモデルを使用したくない場合は、**Body**パラメータが利用できます。[Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}を確認してください。 +もしPydanticモデルを使用したくない場合は、**Body**パラメータが利用できます。[Body - Multiple Parameters: Singular values in body](body-multiple-params.md#_2){.internal-link target=_blank}を確認してください。 diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 193be305f..7f029b483 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -7,7 +7,7 @@ まず、`Cookie`をインポートします: ```Python hl_lines="3" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!../../docs_src/cookie_params/tutorial001.py!} ``` ## `Cookie`のパラメータを宣言 @@ -17,16 +17,22 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます: ```Python hl_lines="9" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!../../docs_src/cookie_params/tutorial001.py!} ``` -!!! note "技術詳細" - `Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 +/// note | 技術詳細 - しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 +`Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 -!!! info "情報" - クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 +しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 + +/// + +/// info | 情報 + +クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 + +/// ## まとめ diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md index 9d6ce8cdc..9834a460b 100644 --- a/docs/ja/docs/tutorial/cors.md +++ b/docs/ja/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 特定のHTTPヘッダー、またはワイルドカード `"*"`を使用してすべて許可。 ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` `CORSMiddleware` 実装のデフォルトのパラメータはCORSに関して制限を与えるものになっているので、ブラウザにドメインを跨いで特定のオリジン、メソッド、またはヘッダーを使用可能にするためには、それらを明示的に有効にする必要があります @@ -78,7 +78,10 @@ CORSについてより詳しい情報は、Mozilla CORS documentation を参照して下さい。 -!!! note "技術詳細" - `from starlette.middleware.cors import CORSMiddleware` も使用できます。 +/// note | 技術詳細 - **FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。 +`from starlette.middleware.cors import CORSMiddleware` も使用できます。 + +**FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。 + +/// diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index 35e1ca7ad..7413332a8 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ Visual Studio CodeやPyCharmなどを使用して、エディター上でデバ FastAPIアプリケーション上で、`uvicorn` を直接インポートして実行します: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### `__name__ == "__main__"` について @@ -74,8 +74,11 @@ from myapp import app は実行されません。 -!!! info "情報" - より詳しい情報は、公式Pythonドキュメントを参照してください。 +/// info | 情報 + +より詳しい情報は、公式Pythonドキュメントを参照してください。 + +/// ## デバッガーでコードを実行 diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md index 5c150d00c..55885a61f 100644 --- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -7,7 +7,7 @@ 前の例では、依存関係("dependable")から`dict`を返していました: ```Python hl_lines="9" -{!../../../docs_src/dependencies/tutorial001.py!} +{!../../docs_src/dependencies/tutorial001.py!} ``` しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。 @@ -72,19 +72,19 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します: ```Python hl_lines="11 12 13 14 15" -{!../../../docs_src/dependencies/tutorial002.py!} +{!../../docs_src/dependencies/tutorial002.py!} ``` クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください: ```Python hl_lines="12" -{!../../../docs_src/dependencies/tutorial002.py!} +{!../../docs_src/dependencies/tutorial002.py!} ``` ...以前の`common_parameters`と同じパラメータを持っています: ```Python hl_lines="8" -{!../../../docs_src/dependencies/tutorial001.py!} +{!../../docs_src/dependencies/tutorial001.py!} ``` これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。 @@ -102,7 +102,7 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 これで、このクラスを使用して依存関係を宣言することができます。 ```Python hl_lines="19" -{!../../../docs_src/dependencies/tutorial002.py!} +{!../../docs_src/dependencies/tutorial002.py!} ``` **FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。 @@ -144,7 +144,7 @@ commons = Depends(CommonQueryParams) 以下にあるように: ```Python hl_lines="19" -{!../../../docs_src/dependencies/tutorial003.py!} +{!../../docs_src/dependencies/tutorial003.py!} ``` しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます: @@ -180,12 +180,15 @@ commons: CommonQueryParams = Depends() 同じ例では以下のようになります: ```Python hl_lines="19" -{!../../../docs_src/dependencies/tutorial004.py!} +{!../../docs_src/dependencies/tutorial004.py!} ``` ...そして **FastAPI** は何をすべきか知っています。 -!!! tip "豆知識" - 役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 +/// tip | 豆知識 - それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。 +役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 + +それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。 + +/// diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 1684d9ca1..3b78f4e0b 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -15,17 +15,20 @@ それは`Depends()`の`list`であるべきです: ```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 -!!! tip "豆知識" - エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。 +/// tip | 豆知識 - `dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。 +エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。 - また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。 +`dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。 + +また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。 + +/// ## 依存関係のエラーと戻り値 @@ -36,7 +39,7 @@ これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます: ```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 例外の発生 @@ -44,7 +47,7 @@ これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます: ```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 戻り値 @@ -54,7 +57,7 @@ つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます: ```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ## *path operations*のグループに対する依存関係 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index 2a89e51d2..bd4e689bf 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,27 +4,36 @@ FastAPIは、いくつかのContext Managersのおかげで動作します。 +/// note | 技術詳細 + +これはPythonのContext Managersのおかげで動作します。 - **FastAPI** はこれを実現するために内部的に使用しています。 +**FastAPI** はこれを実現するために内部的に使用しています。 + +/// ## `yield`と`HTTPException`を持つ依存関係 @@ -108,7 +123,7 @@ FastAPIは、いくつかの以下の2つのメソッドを持つクラスを作成する: `__enter__()`と`__exit__()`ことでコンテキストマネージャを作成することができます。 また、依存関数の中で`with`や`async with`文を使用することによって`yield`を持つ **FastAPI** の依存関係の中でそれらを使用することができます: ```Python hl_lines="1 2 3 4 5 6 7 8 9 13" -{!../../../docs_src/dependencies/tutorial010.py!} +{!../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip "豆知識" - コンテキストマネージャを作成するもう一つの方法はwithです: +/// tip | 豆知識 + +コンテキストマネージャを作成するもう一つの方法はwithです: + +* `@contextlib.contextmanager` または +* `@contextlib.asynccontextmanager` - * `@contextlib.contextmanager` または - * `@contextlib.asynccontextmanager` +これらを使って、関数を単一の`yield`でデコレートすることができます。 - これらを使って、関数を単一の`yield`でデコレートすることができます。 +これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。 - これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。 +しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。 - しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。 +FastAPIが内部的にやってくれます。 - FastAPIが内部的にやってくれます。 +/// diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md index ec563a16d..8965b602f 100644 --- a/docs/ja/docs/tutorial/dependencies/index.md +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -32,7 +32,7 @@ 以下のように、*path operation関数*と同じパラメータを全て取ることができる関数にすぎません: ```Python hl_lines="8 9" -{!../../../docs_src/dependencies/tutorial001.py!} +{!../../docs_src/dependencies/tutorial001.py!} ``` これだけです。 @@ -56,7 +56,7 @@ ### `Depends`のインポート ```Python hl_lines="3" -{!../../../docs_src/dependencies/tutorial001.py!} +{!../../docs_src/dependencies/tutorial001.py!} ``` ### "dependant"での依存関係の宣言 @@ -64,7 +64,7 @@ *path operation関数*のパラメータに`Body`や`Query`などを使用するのと同じように、新しいパラメータに`Depends`を使用することができます: ```Python hl_lines="13 18" -{!../../../docs_src/dependencies/tutorial001.py!} +{!../../docs_src/dependencies/tutorial001.py!} ``` 関数のパラメータに`Depends`を使用するのは`Body`や`Query`などと同じですが、`Depends`の動作は少し異なります。 @@ -75,8 +75,11 @@ そして、その関数は、*path operation関数*が行うのと同じ方法でパラメータを取ります。 -!!! tip "豆知識" - 次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。 +/// tip | 豆知識 + +次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。 + +/// 新しいリクエストが到着するたびに、**FastAPI** が以下のような処理を行います: @@ -97,10 +100,13 @@ common_parameters --> read_users この方法では、共有されるコードを一度書き、**FastAPI** が*path operations*のための呼び出しを行います。 -!!! check "確認" - 特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。 +/// check | 確認 + +特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。 - `Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。 +`Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。 + +/// ## `async`にするかどうか @@ -112,8 +118,11 @@ common_parameters --> read_users それは重要ではありません。**FastAPI** は何をすべきかを知っています。 -!!! note "備考" - わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。 +/// note | 備考 + +わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。 + +/// ## OpenAPIとの統合 diff --git a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md index 8848ac79e..11b5ff004 100644 --- a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md @@ -11,7 +11,7 @@ 以下のような最初の依存関係(「依存可能なもの」)を作成することができます: ```Python hl_lines="8 9" -{!../../../docs_src/dependencies/tutorial005.py!} +{!../../docs_src/dependencies/tutorial005.py!} ``` これはオプショナルのクエリパラメータ`q`を`str`として宣言し、それを返すだけです。 @@ -23,7 +23,7 @@ そして、別の依存関数(「依存可能なもの」)を作成して、同時にそれ自身の依存関係を宣言することができます(つまりそれ自身も「依存」です): ```Python hl_lines="13" -{!../../../docs_src/dependencies/tutorial005.py!} +{!../../docs_src/dependencies/tutorial005.py!} ``` 宣言されたパラメータに注目してみましょう: @@ -38,13 +38,16 @@ 以下のように依存関係を使用することができます: ```Python hl_lines="21" -{!../../../docs_src/dependencies/tutorial005.py!} +{!../../docs_src/dependencies/tutorial005.py!} ``` -!!! info "情報" - *path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。 +/// info | 情報 - しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。 +*path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。 + +しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。 + +/// ```mermaid graph TB @@ -78,9 +81,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False しかし、それでも非常に強力で、任意の深くネストされた依存関係「グラフ」(ツリー)を宣言することができます。 -!!! tip "豆知識" - これらの単純な例では、全てが役に立つとは言えないかもしれません。 +/// tip | 豆知識 + +これらの単純な例では、全てが役に立つとは言えないかもしれません。 + +しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。 - しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。 +そして、あなたを救うコードの量もみることになるでしょう。 - そして、あなたを救うコードの量もみることになるでしょう。 +/// diff --git a/docs/ja/docs/tutorial/encoder.md b/docs/ja/docs/tutorial/encoder.md index 305867ab7..3ce7e604e 100644 --- a/docs/ja/docs/tutorial/encoder.md +++ b/docs/ja/docs/tutorial/encoder.md @@ -21,7 +21,7 @@ JSON互換のデータのみを受信するデータベース`fase_db`がある Pydanticモデルのようなオブジェクトを受け取り、JSON互換版を返します: ```Python hl_lines="5 22" -{!../../../docs_src/encoder/tutorial001.py!} +{!../../docs_src/encoder/tutorial001.py!} ``` この例では、Pydanticモデルを`dict`に、`datetime`を`str`に変換します。 @@ -30,5 +30,8 @@ Pydanticモデルのようなオブジェクトを受け取り、JSON互換版 これはJSON形式のデータを含む大きな`str`を(文字列として)返しません。JSONと互換性のある値とサブの値を持つPython標準のデータ構造(例:`dict`)を返します。 -!!! note "備考" - `jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。 +/// note | 備考 + +`jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。 + +/// diff --git a/docs/ja/docs/tutorial/extra-data-types.md b/docs/ja/docs/tutorial/extra-data-types.md index c0fdbd58c..7f1b14648 100644 --- a/docs/ja/docs/tutorial/extra-data-types.md +++ b/docs/ja/docs/tutorial/extra-data-types.md @@ -56,11 +56,11 @@ ここでは、上記の型のいくつかを使用したパラメータを持つ*path operation*の例を示します。 ```Python hl_lines="1 2 12-16" -{!../../../docs_src/extra_data_types/tutorial001.py!} +{!../../docs_src/extra_data_types/tutorial001.py!} ``` 関数内のパラメータは自然なデータ型を持っていることに注意してください。そして、以下のように通常の日付操作を行うことができます: ```Python hl_lines="18 19" -{!../../../docs_src/extra_data_types/tutorial001.py!} +{!../../docs_src/extra_data_types/tutorial001.py!} ``` diff --git a/docs/ja/docs/tutorial/extra-models.md b/docs/ja/docs/tutorial/extra-models.md index aa2e5ffdc..5ff5db47d 100644 --- a/docs/ja/docs/tutorial/extra-models.md +++ b/docs/ja/docs/tutorial/extra-models.md @@ -8,17 +8,20 @@ * **出力モデル**はパスワードをもつべきではありません。 * **データベースモデル**はおそらくハッシュ化されたパスワードが必要になるでしょう。 -!!! danger "危険" - ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。 +/// danger | 危険 - 知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。 +ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。 + +知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。 + +/// ## 複数のモデル ここでは、パスワードフィールドをもつモデルがどのように見えるのか、また、どこで使われるのか、大まかなイメージを紹介します: ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!../../../docs_src/extra_models/tutorial001.py!} +{!../../docs_src/extra_models/tutorial001.py!} ``` ### `**user_in.dict()`について @@ -131,8 +134,11 @@ UserInDB( ) ``` -!!! warning "注意" - サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。 +/// warning | 注意 + +サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。 + +/// ## 重複の削減 @@ -151,7 +157,7 @@ UserInDB( このようにして、モデル間の違いだけを宣言することができます: ```Python hl_lines="9 15 16 19 20 23 24" -{!../../../docs_src/extra_models/tutorial002.py!} +{!../../docs_src/extra_models/tutorial002.py!} ``` ## `Union`または`anyOf` @@ -163,7 +169,7 @@ OpenAPIでは`anyOf`で定義されます。 そのためには、標準的なPythonの型ヒント`typing.Union`を使用します: ```Python hl_lines="1 14 15 18 19 20 33" -{!../../../docs_src/extra_models/tutorial003.py!} +{!../../docs_src/extra_models/tutorial003.py!} ``` ## モデルのリスト @@ -173,7 +179,7 @@ OpenAPIでは`anyOf`で定義されます。 そのためには、標準のPythonの`typing.List`を使用する: ```Python hl_lines="1 20" -{!../../../docs_src/extra_models/tutorial004.py!} +{!../../docs_src/extra_models/tutorial004.py!} ``` ## 任意の`dict`を持つレスポンス @@ -185,7 +191,7 @@ OpenAPIでは`anyOf`で定義されます。 この場合、`typing.Dict`を使用することができます: ```Python hl_lines="1 8" -{!../../../docs_src/extra_models/tutorial005.py!} +{!../../docs_src/extra_models/tutorial005.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md index c696f7d48..3691d13d2 100644 --- a/docs/ja/docs/tutorial/first-steps.md +++ b/docs/ja/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ 最もシンプルなFastAPIファイルは以下のようになります: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` これを`main.py`にコピーします。 @@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note "備考" - `uvicorn main:app`は以下を示します: +/// note | 備考 - * `main`: `main.py`ファイル (Python "module")。 - * `app`: `main.py`内部で作られるobject(`app = FastAPI()`のように記述される)。 - * `--reload`: コードの変更時にサーバーを再起動させる。開発用。 +`uvicorn main:app`は以下を示します: + +* `main`: `main.py`ファイル (Python "module")。 +* `app`: `main.py`内部で作られるobject(`app = FastAPI()`のように記述される)。 +* `--reload`: コードの変更時にサーバーを再起動させる。開発用。 + +/// 出力には次のような行があります: @@ -131,20 +134,23 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ ### Step 1: `FastAPI`をインポート ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI`は、APIのすべての機能を提供するPythonクラスです。 -!!! note "技術詳細" - `FastAPI`は`Starlette`を直接継承するクラスです。 +/// note | 技術詳細 + +`FastAPI`は`Starlette`を直接継承するクラスです。 - `FastAPI`でもStarletteのすべての機能を利用可能です。 +`FastAPI`でもStarletteのすべての機能を利用可能です。 + +/// ### Step 2: `FastAPI`の「インスタンス」を生成 ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` ここで、`app`変数が`FastAPI`クラスの「インスタンス」になります。 @@ -165,7 +171,7 @@ $ uvicorn main:app --reload 以下のようなアプリを作成したとき: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` そして、それを`main.py`ファイルに置き、次のように`uvicorn`を呼び出します: @@ -198,8 +204,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "情報" - 「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。 +/// info | 情報 + +「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。 + +/// APIを構築する際、「パス」は「関心事」と「リソース」を分離するための主要な方法です。 @@ -241,23 +250,26 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを #### *パスオペレーションデコレータ*を定義 ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")`は直下の関数が下記のリクエストの処理を担当することを**FastAPI**に伝えます: * パス `/` * get オペレーション -!!! info "`@decorator` について" - Pythonにおける`@something`シンタックスはデコレータと呼ばれます。 +/// info | `@decorator` について - 「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。 +Pythonにおける`@something`シンタックスはデコレータと呼ばれます。 - 「デコレータ」は直下の関数を受け取り、それを使って何かを行います。 +「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。 - 私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。 +「デコレータ」は直下の関数を受け取り、それを使って何かを行います。 - これが「*パスオペレーションデコレータ*」です。 +私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。 + +これが「*パスオペレーションデコレータ*」です。 + +/// 他のオペレーションも使用できます: @@ -272,14 +284,17 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを * `@app.patch()` * `@app.trace()` -!!! tip "豆知識" - 各オペレーション (HTTPメソッド)は自由に使用できます。 +/// tip | 豆知識 + +各オペレーション (HTTPメソッド)は自由に使用できます。 - **FastAPI**は特定の意味づけを強制しません。 +**FastAPI**は特定の意味づけを強制しません。 - ここでの情報は、要件ではなくガイドラインとして提示されます。 +ここでの情報は、要件ではなくガイドラインとして提示されます。 - 例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。 +例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。 + +/// ### Step 4: **パスオペレーション**を定義 @@ -290,7 +305,7 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを * **関数**: 「デコレータ」の直下にある関数 (`@app.get("/")`の直下) です。 ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` これは、Pythonの関数です。 @@ -304,16 +319,19 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを `async def`の代わりに通常の関数として定義することもできます: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "備考" - 違いが分からない場合は、[Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}を確認してください。 +/// note | 備考 + +違いが分からない場合は、[Async: *"急いでいますか?"*](../async.md#_1){.internal-link target=_blank}を確認してください。 + +/// ### Step 5: コンテンツの返信 ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `dict`、`list`、`str`、`int`などを返すことができます。 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md index 0b95cae0f..d270fd75b 100644 --- a/docs/ja/docs/tutorial/handling-errors.md +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -26,7 +26,7 @@ HTTPレスポンスをエラーでクライアントに返すには、`HTTPExcep ### `HTTPException`のインポート ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### コード内での`HTTPException`の発生 @@ -42,7 +42,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### レスポンス結果 @@ -63,12 +63,15 @@ Pythonの例外なので、`return`ではなく、`raise`です。 } ``` -!!! tip "豆知識" - `HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。 +/// tip | 豆知識 - `dist`や`list`などを渡すことができます。 +`HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。 - これらは **FastAPI** によって自動的に処理され、JSONに変換されます。 +`dist`や`list`などを渡すことができます。 + +これらは **FastAPI** によって自動的に処理され、JSONに変換されます。 + +/// ## カスタムヘッダーの追加 @@ -79,7 +82,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` ## カスタム例外ハンドラのインストール @@ -93,7 +96,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 カスタム例外ハンドラを`@app.exception_handler()`で追加することができます: ```Python hl_lines="5 6 7 13 14 15 16 17 18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。 @@ -106,10 +109,13 @@ Pythonの例外なので、`return`ではなく、`raise`です。 {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "技術詳細" - また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。 +/// note | 技術詳細 + +また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。 - **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。 +/// ## デフォルトの例外ハンドラのオーバーライド @@ -130,7 +136,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 この例外ハンドラは`Requset`と例外を受け取ります。 ```Python hl_lines="2 14 15 16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` これで、`/items/foo`にアクセスすると、デフォルトのJSONエラーの代わりに以下が返されます: @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError`と`ValidationError` -!!! warning "注意" - これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。 +/// warning | 注意 + +これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。 + +/// `RequestValidationError`はPydanticの`ValidationError`のサブクラスです。 @@ -180,13 +189,16 @@ path -> item_id 例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます: ```Python hl_lines="3 4 9 10 11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "技術詳細" - また、`from starlette.responses import PlainTextResponse`を使用することもできます。 +/// note | 技術詳細 + +また、`from starlette.responses import PlainTextResponse`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ### `RequestValidationError`のボディの使用 @@ -195,7 +207,7 @@ path -> item_id アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。 ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} +{!../../docs_src/handling_errors/tutorial005.py!} ``` ここで、以下のような無効な項目を送信してみてください: @@ -257,7 +269,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException デフォルトの例外ハンドラを`fastapi.exception_handlers`からインポートして再利用することができます: ```Python hl_lines="2 3 4 5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` この例では、非常に表現力のあるメッセージでエラーを`print`しています。 diff --git a/docs/ja/docs/tutorial/header-params.md b/docs/ja/docs/tutorial/header-params.md index 1bf8440bb..c741005d3 100644 --- a/docs/ja/docs/tutorial/header-params.md +++ b/docs/ja/docs/tutorial/header-params.md @@ -7,7 +7,7 @@ まず、`Header`をインポートします: ```Python hl_lines="3" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` ## `Header`のパラメータの宣言 @@ -17,16 +17,22 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます。 ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` -!!! note "技術詳細" - `Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 +/// note | 技術詳細 - しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 +`Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 -!!! info "情報" - ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。 +しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 + +/// + +/// info | 情報 + +ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。 + +/// ## 自動変換 @@ -45,12 +51,14 @@ もしなんらかの理由でアンダースコアからハイフンへの自動変換を無効にする必要がある場合は、`Header`の`convert_underscores`に`False`を設定してください: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial002.py!} +{!../../docs_src/header_params/tutorial002.py!} ``` -!!! warning "注意" - `convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。 +/// warning | 注意 + +`convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。 +/// ## ヘッダーの重複 @@ -63,7 +71,7 @@ 例えば、複数回出現する可能性のある`X-Token`のヘッダを定義するには、以下のように書くことができます: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial003.py!} +{!../../docs_src/header_params/tutorial003.py!} ``` もし、その*path operation*で通信する場合は、次のように2つのHTTPヘッダーを送信します: diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md index 856cde44b..87d3751fd 100644 --- a/docs/ja/docs/tutorial/index.md +++ b/docs/ja/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...これには、コードを実行するサーバーとして使用できる `uvicorn`も含まれます。 -!!! note "備考" - パーツ毎にインストールすることも可能です。 +/// note | 備考 - 以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです: +パーツ毎にインストールすることも可能です。 - ``` - pip install fastapi - ``` +以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです: - また、サーバーとして動作するように`uvicorn` をインストールします: +``` +pip install fastapi +``` + +また、サーバーとして動作するように`uvicorn` をインストールします: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +そして、使用したい依存関係をそれぞれ同様にインストールします。 - そして、使用したい依存関係をそれぞれ同様にインストールします。 +/// ## 高度なユーザーガイド diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md index 73d7f02b2..201322cb4 100644 --- a/docs/ja/docs/tutorial/metadata.md +++ b/docs/ja/docs/tutorial/metadata.md @@ -14,7 +14,7 @@ これらを設定するには、パラメータ `title`、`description`、`version` を使用します: ```Python hl_lines="4-6" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` この設定では、自動APIドキュメントは以下の様になります: @@ -42,24 +42,30 @@ タグのためのメタデータを作成し、それを `openapi_tags` パラメータに渡します。 ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` 説明文 (description) の中で Markdown を使用できることに注意してください。たとえば、「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。 -!!! tip "豆知識" - 使用するすべてのタグにメタデータを追加する必要はありません。 +/// tip | 豆知識 + +使用するすべてのタグにメタデータを追加する必要はありません。 + +/// ### 自作タグの使用 `tags` パラメーターを使用して、それぞれの *path operations* (および `APIRouter`) を異なるタグに割り当てます: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` -!!! info "情報" - タグのより詳しい説明を知りたい場合は [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank} を参照して下さい。 +/// info | 情報 + +タグのより詳しい説明を知りたい場合は [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank} を参照して下さい。 + +/// ### ドキュメントの確認 @@ -82,7 +88,7 @@ たとえば、`/api/v1/openapi.json` で提供されるように設定するには: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を設定できます。これにより、それを使用するドキュメントUIも無効になります。 @@ -101,5 +107,5 @@ OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を たとえば、`/documentation` でSwagger UIが提供されるように設定し、ReDocを無効にするには: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/ja/docs/tutorial/middleware.md b/docs/ja/docs/tutorial/middleware.md index 973eb2b1a..3a3d8bb22 100644 --- a/docs/ja/docs/tutorial/middleware.md +++ b/docs/ja/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * その**レスポンス**に対して何かを実行したり、必要なコードを実行したりできます。 * そして、**レスポンス**を返します。 -!!! note "技術詳細" - `yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。 +/// note | 技術詳細 - バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。 +`yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。 + +バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。 + +/// ## ミドルウェアの作成 @@ -29,18 +32,24 @@ * その後、`response` を返す前にさらに `response` を変更することもできます。 ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` -!!! tip "豆知識" - 'X-'プレフィックスを使用してカスタムの独自ヘッダーを追加できます。 +/// tip | 豆知識 + +'X-'プレフィックスを使用してカスタムの独自ヘッダーを追加できます。 + +ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank}) + +/// + +/// note | 技術詳細 - ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank}) +`from starlette.requests import Request` を使用することもできます。 -!!! note "技術詳細" - `from starlette.requests import Request` を使用することもできます。 +**FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。 - **FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。 +/// ### `response` の前後 @@ -51,7 +60,7 @@ 例えば、リクエストの処理とレスポンスの生成にかかった秒数を含むカスタムヘッダー `X-Process-Time` を追加できます: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## その他のミドルウェア diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md new file mode 100644 index 000000000..36223d35d --- /dev/null +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,109 @@ +# Path Operationの設定 + +*path operationデコレータ*を設定するためのパラメータがいくつかあります。 + +/// warning | 注意 + +これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。 + +/// + +## レスポンスステータスコード + +*path operation*のレスポンスで使用する(HTTP)`status_code`を定義することができます。 + +`404`のように`int`のコードを直接渡すことができます。 + +しかし、それぞれの番号コードが何のためのものか覚えていない場合は、`status`のショートカット定数を使用することができます: + +```Python hl_lines="3 17" +{!../../docs_src/path_operation_configuration/tutorial001.py!} +``` + +そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 + +/// note | 技術詳細 + +また、`from starlette import status`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 + +/// + +## タグ + +`tags`パラメータを`str`の`list`(通常は1つの`str`)と一緒に渡すと、*path operation*にタグを追加できます: + +```Python hl_lines="17 22 27" +{!../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +これらはOpenAPIスキーマに追加され、自動ドキュメントのインターフェースで使用されます: + + + +## 概要と説明 + +`summary`と`description`を追加できます: + +```Python hl_lines="20-21" +{!../../docs_src/path_operation_configuration/tutorial003.py!} +``` + +## docstringを用いた説明 + +説明文は長くて複数行におよぶ傾向があるので、関数docstring内に*path operation*の説明文を宣言できます。すると、**FastAPI** は説明文を読み込んでくれます。 + +docstringにMarkdownを記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して) + +```Python hl_lines="19-27" +{!../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +これは対話的ドキュメントで使用されます: + + + +## レスポンスの説明 + +`response_description`パラメータでレスポンスの説明をすることができます。 + +```Python hl_lines="21" +{!../../docs_src/path_operation_configuration/tutorial005.py!} +``` + +/// info | 情報 + +`respnse_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。 + +/// + +/// check | 確認 + +OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。 + +そのため、それを提供しない場合は、**FastAPI** が自動的に「成功のレスポンス」を生成します。 + +/// + + + +## 非推奨の*path operation* + +*path operation*をdeprecatedとしてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します: + +```Python hl_lines="16" +{!../../docs_src/path_operation_configuration/tutorial006.py!} +``` + +対話的ドキュメントでは非推奨と明記されます: + + + +*path operations*が非推奨である場合とそうでない場合でどのように見えるかを確認してください: + + + +## まとめ + +*path operationデコレータ*にパラメータを渡すことで、*path operations*のメタデータを簡単に設定・追加することができます。 diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md index 551aeabb3..7d55ad30c 100644 --- a/docs/ja/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -7,7 +7,7 @@ まず初めに、`fastapi`から`Path`をインポートします: ```Python hl_lines="1" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` ## メタデータの宣言 @@ -17,15 +17,18 @@ 例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします: ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` -!!! note "備考" - パスの一部でなければならないので、パスパラメータは常に必須です。 +/// note | 備考 - そのため、`...`を使用して必須と示す必要があります。 +パスの一部でなければならないので、パスパラメータは常に必須です。 - それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。 +そのため、`...`を使用して必須と示す必要があります。 + +それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。 + +/// ## 必要に応じてパラメータを並び替える @@ -44,7 +47,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 そのため、以下のように関数を宣言することができます: ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## 必要に応じてパラメータを並び替えるトリック @@ -56,7 +59,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。 ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## 数値の検証: 以上 @@ -66,7 +69,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## 数値の検証: より大きいと小なりイコール @@ -77,7 +80,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `le`: 小なりイコール(`l`ess than or `e`qual) ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## 数値の検証: 浮動小数点、 大なり小なり @@ -91,7 +94,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 これはltも同じです。 ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## まとめ @@ -105,18 +108,24 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `lt`: より小さい(`l`ess `t`han) * `le`: 以下(`l`ess than or `e`qual) -!!! info "情報" - `Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません) +/// info | 情報 + +`Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません) + +そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。 + +/// + +/// note | 技術詳細 - そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。 +`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 -!!! note "技術詳細" - `fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 +呼び出されると、同じ名前のクラスのインスタンスを返します。 - 呼び出されると、同じ名前のクラスのインスタンスを返します。 +そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。 - そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。 +これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。 - これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。 +この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。 - この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。 +/// diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index b395dc41d..d86a27cb4 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます: ```Python hl_lines="6 7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。 @@ -19,13 +19,16 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます: ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` ここでは、 `item_id` は `int` として宣言されています。 -!!! check "確認" - これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。 +/// check | 確認 + +これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。 + +/// ## データ変換 @@ -35,10 +38,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {"item_id":3} ``` -!!! check "確認" - 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。 +/// check | 確認 + +関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。 + +したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。 - したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。 +/// ## データバリデーション @@ -63,12 +69,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー http://127.0.0.1:8000/items/4.2 で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。 -!!! check "確認" - したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 +/// check | 確認 - 表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。 +したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 - これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。 +表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。 + +これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。 + +/// ## ドキュメント @@ -76,10 +85,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー -!!! check "確認" - 繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。 +/// check | 確認 + +繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。 + +パスパラメータが整数として宣言されていることに注意してください。 - パスパラメータが整数として宣言されていることに注意してください。 +/// ## 標準であることのメリット、ドキュメンテーションの代替物 @@ -110,7 +122,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー *path operations* は順に評価されるので、 `/users/me` が `/users/{user_id}` よりも先に宣言されているか確認する必要があります: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` それ以外の場合、 `/users/{users_id}` は `/users/me` としてもマッチします。値が「"me"」であるパラメータ `user_id` を受け取ると「考え」ます。 @@ -128,21 +140,27 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー そして、固定値のクラス属性を作ります。すると、その値が使用可能な値となります: ```Python hl_lines="1 6 7 8 9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! info "情報" - Enumerations (もしくは、enums)はPython 3.4以降で利用できます。 +/// info | 情報 -!!! tip "豆知識" - "AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。 +Enumerations (もしくは、enums)はPython 3.4以降で利用できます。 + +/// + +/// tip | 豆知識 + +"AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。 + +/// ### *パスパラメータ*の宣言 次に、作成したenumクラスである`ModelName`を使用した型アノテーションをもつ*パスパラメータ*を作成します: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### ドキュメントの確認 @@ -160,7 +178,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー これは、作成した列挙型 `ModelName` の*列挙型メンバ*と比較できます: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### *列挙値*の取得 @@ -168,11 +186,14 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー `model_name.value` 、もしくは一般に、 `your_enum_member.value` を使用して実際の値 (この場合は `str`) を取得できます。 ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "豆知識" - `ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。 +/// tip | 豆知識 + +`ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。 + +/// #### *列挙型メンバ*の返却 @@ -181,7 +202,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー それらはクライアントに返される前に適切な値 (この場合は文字列) に変換されます。 ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` クライアントは以下の様なJSONレスポンスを得ます: @@ -222,13 +243,16 @@ Starletteのオプションを直接使用することで、以下のURLの様 したがって、以下の様に使用できます: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "豆知識" - 最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。 +/// tip | 豆知識 + +最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。 + +この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。 - この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index 8d375d7ce..6450c91c4 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -5,15 +5,19 @@ 以下のアプリケーションを例にしてみましょう: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} +{!../../docs_src/query_params_str_validations/tutorial001.py!} ``` クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。 -!!! note "備考" - FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。 +/// note | 備考 + +FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。 + +`Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。 + +/// - `Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。 ## バリデーションの追加 `q`はオプショナルですが、もし値が渡されてきた場合には、**50文字を超えないこと**を強制してみましょう。 @@ -23,7 +27,7 @@ そのために、まずは`fastapi`から`Query`をインポートします: ```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` ## デフォルト値として`Query`を使用 @@ -31,7 +35,7 @@ パラメータのデフォルト値として使用し、パラメータ`max_length`を50に設定します: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` デフォルト値`None`を`Query(default=None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。 @@ -50,22 +54,25 @@ q: Optional[str] = None しかし、これはクエリパラメータとして明示的に宣言しています。 -!!! info "情報" - FastAPIは以下の部分を気にすることを覚えておいてください: +/// info | 情報 + +FastAPIは以下の部分を気にすることを覚えておいてください: + +```Python += None +``` - ```Python - = None - ``` +もしくは: - もしくは: +```Python += Query(default=None) +``` - ```Python - = Query(default=None) - ``` +そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。 - そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。 +`Optional` の部分は、エディターによるより良いサポートを可能にします。 - `Optional` の部分は、エディターによるより良いサポートを可能にします。 +/// そして、さらに多くのパラメータを`Query`に渡すことができます。この場合、文字列に適用される、`max_length`パラメータを指定します。 @@ -80,7 +87,7 @@ q: Union[str, None] = Query(default=None, max_length=50) パラメータ`min_length`も追加することができます: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} +{!../../docs_src/query_params_str_validations/tutorial003.py!} ``` ## 正規表現の追加 @@ -88,7 +95,7 @@ q: Union[str, None] = Query(default=None, max_length=50) パラメータが一致するべき正規表現を定義することができます: ```Python hl_lines="11" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` この特定の正規表現は受け取ったパラメータの値をチェックします: @@ -108,11 +115,14 @@ q: Union[str, None] = Query(default=None, max_length=50) クエリパラメータ`q`の`min_length`を`3`とし、デフォルト値を`fixedquery`としてみましょう: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "備考" - デフォルト値を指定すると、パラメータは任意になります。 +/// note | 備考 + +デフォルト値を指定すると、パラメータは任意になります。 + +/// ## 必須にする @@ -137,11 +147,14 @@ q: Union[str, None] = Query(default=None, min_length=3) そのため、`Query`を使用して必須の値を宣言する必要がある場合は、第一引数に`...`を使用することができます: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info "情報" - これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。 +/// info | 情報 + +これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。 + +/// これは **FastAPI** にこのパラメータが必須であることを知らせます。 @@ -152,7 +165,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 例えば、URL内に複数回出現するクエリパラメータ`q`を宣言するには以下のように書きます: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` そしてURLは以下です: @@ -174,8 +187,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "豆知識" - 上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。 +/// tip | 豆知識 + +上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。 + +/// 対話的APIドキュメントは複数の値を許可するために自動的に更新されます。 @@ -186,7 +202,7 @@ http://localhost:8000/items/?q=foo&q=bar また、値が指定されていない場合はデフォルトの`list`を定義することもできます。 ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` 以下のURLを開くと: @@ -211,13 +227,16 @@ http://localhost:8000/items/ `List[str]`の代わりに直接`list`を使うこともできます: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note "備考" - この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。 +/// note | 備考 - 例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。 +この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。 + +例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。 + +/// ## より多くのメタデータを宣言する @@ -225,21 +244,24 @@ http://localhost:8000/items/ その情報は、生成されたOpenAPIに含まれ、ドキュメントのユーザーインターフェースや外部のツールで使用されます。 -!!! note "備考" - ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。 +/// note | 備考 + +ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。 + +その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。 - その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。 +/// `title`を追加できます: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` `description`を追加できます: ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## エイリアスパラメータ @@ -261,7 +283,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems それならば、`alias`を宣言することができます。エイリアスはパラメータの値を見つけるのに使用されます: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## 非推奨パラメータ @@ -273,7 +295,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems その場合、`Query`にパラメータ`deprecated=True`を渡します: ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` ドキュメントは以下のようになります: diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 957726b9f..71f78eca5 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -1,10 +1,9 @@ - # クエリパラメータ パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。 ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` クエリはURL内で `?` の後に続くキーとバリューの組で、 `&` で区切られています。 @@ -65,20 +64,23 @@ http://127.0.0.1:8000/items/?skip=20 同様に、デフォルト値を `None` とすることで、オプショナルなクエリパラメータを宣言できます: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} +{!../../docs_src/query_params/tutorial002.py!} ``` この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 -!!! check "確認" - パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 +/// check | 確認 + +パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 + +/// ## クエリパラメータの型変換 `bool` 型も宣言できます。これは以下の様に変換されます: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} +{!../../docs_src/query_params/tutorial003.py!} ``` この場合、以下にアクセスすると: @@ -122,7 +124,7 @@ http://127.0.0.1:8000/items/foo?short=yes 名前で判別されます: ```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} +{!../../docs_src/query_params/tutorial004.py!} ``` ## 必須のクエリパラメータ @@ -134,7 +136,7 @@ http://127.0.0.1:8000/items/foo?short=yes しかしクエリパラメータを必須にしたい場合は、ただデフォルト値を宣言しなければよいです: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです @@ -180,7 +182,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy そして当然、あるパラメータを必須に、別のパラメータにデフォルト値を設定し、また別のパラメータをオプショナルにできます: ```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} +{!../../docs_src/query_params/tutorial006.py!} ``` この場合、3つのクエリパラメータがあります。: @@ -189,6 +191,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`、デフォルト値を `0` とする `int` 。 * `limit`、オプショナルな `int` 。 -!!! tip "豆知識" +/// tip | 豆知識 + +[パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。 - [パスパラメータ](path-params.md#predefined-values){.internal-link target=_blank}と同様に `Enum` を使用できます。 +/// diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..1e4237b20 --- /dev/null +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,41 @@ +# リクエストフォームとファイル + +`File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。 + +/// info | 情報 + +アップロードされたファイルやフォームデータを受信するには、まず`python-multipart`をインストールします。 + +例えば、`pip install python-multipart`のように。 + +/// + +## `File`と`Form`のインポート + +```Python hl_lines="1" +{!../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +## `File`と`Form`のパラメータの定義 + +ファイルやフォームのパラメータは`Body`や`Query`の場合と同じように作成します: + +```Python hl_lines="8" +{!../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +ファイルとフォームフィールドがフォームデータとしてアップロードされ、ファイルとフォームフィールドを受け取ります。 + +また、いくつかのファイルを`bytes`として、いくつかのファイルを`UploadFile`として宣言することができます。 + +/// warning | 注意 + +*path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。 + +これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。 + +/// + +## まとめ + +同じリクエストでデータやファイルを受け取る必要がある場合は、`File` と`Form`を一緒に使用します。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index f90c49746..f130c067f 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -2,17 +2,20 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。 -!!! info "情報" - フォームを使うためには、まず`python-multipart`をインストールします。 +/// info | 情報 - たとえば、`pip install python-multipart`のように。 +フォームを使うためには、まず`python-multipart`をインストールします。 + +たとえば、`pip install python-multipart`のように。 + +/// ## `Form`のインポート `fastapi`から`Form`をインポートします: ```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` ## `Form`のパラメータの定義 @@ -20,7 +23,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `Body`や`Query`の場合と同じようにフォームパラメータを作成します: ```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` 例えば、OAuth2仕様が使用できる方法の1つ(「パスワードフロー」と呼ばれる)では、フォームフィールドとして`username`と`password`を送信する必要があります。 @@ -29,11 +32,17 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `Form`では`Body`(および`Query`や`Path`、`Cookie`)と同じメタデータとバリデーションを宣言することができます。 -!!! info "情報" - `Form`は`Body`を直接継承するクラスです。 +/// info | 情報 + +`Form`は`Body`を直接継承するクラスです。 + +/// + +/// tip | 豆知識 -!!! tip "豆知識" - フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。 +フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。 + +/// ## 「フォームフィールド」について @@ -41,17 +50,23 @@ HTMLフォーム(`
`)がサーバにデータを送信する方 **FastAPI** は、JSONの代わりにそのデータを適切な場所から読み込むようにします。 -!!! note "技術詳細" - フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。 +/// note | 技術詳細 + +フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。 + +しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。 + +これらのエンコーディングやフォームフィールドの詳細については、MDNPOSTのウェブドキュメントを参照してください。 + +/// - しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。 +/// warning | 注意 - これらのエンコーディングやフォームフィールドの詳細については、MDNPOSTのウェブドキュメントを参照してください。 +*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。 -!!! warning "注意" - *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。 +これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。 - これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index b8b6978d4..97821f125 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -9,11 +9,14 @@ * など。 ```Python hl_lines="17" -{!../../../docs_src/response_model/tutorial001.py!} +{!../../docs_src/response_model/tutorial001.py!} ``` -!!! note "備考" - `response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。 +/// note | 備考 + +`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。 + +/// Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。 @@ -28,21 +31,24 @@ FastAPIは`response_model`を使って以下のことをします: * 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。 -!!! note "技術詳細" - レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 +/// note | 技術詳細 + +レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 + +/// ## 同じ入力データの返却 ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています: ```Python hl_lines="9 11" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています: ```Python hl_lines="17 18" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。 @@ -51,27 +57,30 @@ FastAPIは`response_model`を使って以下のことをします: しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。 -!!! danger "危険" - ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 +/// danger | 危険 + +ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 + +/// ## 出力モデルの追加 代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます: ```Python hl_lines="9 11 16" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` ...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません: ```Python hl_lines="22" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。 @@ -91,7 +100,7 @@ FastAPIは`response_model`を使って以下のことをします: レスポンスモデルにはデフォルト値を設定することができます: ```Python hl_lines="11 13 14" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` * `description: str = None`は`None`がデフォルト値です。 @@ -107,7 +116,7 @@ FastAPIは`response_model`を使って以下のことをします: *path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。 @@ -121,16 +130,22 @@ FastAPIは`response_model`を使って以下のことをします: } ``` -!!! info "情報" - FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。 +/// info | 情報 + +FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。 + +/// -!!! info "情報" - 以下も使用することができます: +/// info | 情報 - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +以下も使用することができます: - `exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。 +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +`exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。 + +/// #### デフォルト値を持つフィールドの値を持つデータ @@ -165,9 +180,12 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d そのため、それらはJSONレスポンスに含まれることになります。 -!!! tip "豆知識" - デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 - 例えば、リスト(`[]`)や`10.5`の`float`などです。 +/// tip | 豆知識 + +デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 +例えば、リスト(`[]`)や`10.5`の`float`などです。 + +/// ### `response_model_include`と`response_model_exclude` @@ -177,28 +195,34 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。 -!!! tip "豆知識" - それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 +/// tip | 豆知識 - これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。 +それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 - 同様に動作する`response_model_by_alias`にも当てはまります。 +これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。 + +同様に動作する`response_model_by_alias`にも当てはまります。 + +/// ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial005.py!} +{!../../docs_src/response_model/tutorial005.py!} ``` -!!! tip "豆知識" - `{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 +/// tip | 豆知識 + +`{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 + +これは`set(["name", "description"])`と同等です。 - これは`set(["name", "description"])`と同等です。 +/// #### `set`の代わりに`list`を使用する もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します: ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial006.py!} +{!../../docs_src/response_model/tutorial006.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md index ead2addda..56bcdaf6c 100644 --- a/docs/ja/docs/tutorial/response-status-code.md +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -9,16 +9,22 @@ * など。 ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "備考" - `status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 +/// note | 備考 + +`status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 + +/// `status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。 -!!! info "情報" - `status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。 +/// info | 情報 + +`status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。 + +/// これは: @@ -27,15 +33,21 @@ -!!! note "備考" - いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 +/// note | 備考 + +いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 + +FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。 - FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。 +/// ## HTTPステータスコードについて -!!! note "備考" - すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 +/// note | 備考 + +すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 + +/// HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。 @@ -54,15 +66,18 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス * クライアントからの一般的なエラーについては、`400`を使用することができます。 * `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。 -!!! tip "豆知識" - それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。 +/// tip | 豆知識 + +それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。 + +/// ## 名前を覚えるための近道 先ほどの例をもう一度見てみましょう: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201`は「作成完了」のためのステータスコードです。 @@ -72,17 +87,20 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス `fastapi.status`の便利な変数を利用することができます。 ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` それらは便利です。それらは同じ番号を保持しており、その方法ではエディタの自動補完を使用してそれらを見つけることができます。 -!!! note "技術詳細" - また、`from starlette import status`を使うこともできます。 +/// note | 技術詳細 + +また、`from starlette import status`を使うこともできます。 + +**FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 - **FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 +/// ## デフォルトの変更 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index d96163b82..44dfad737 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 Pydanticのドキュメント: スキーマのカスタマイズで説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: ```Python hl_lines="15 16 17 18 19 20 21 22 23" -{!../../../docs_src/schema_extra_example/tutorial001.py!} +{!../../docs_src/schema_extra_example/tutorial001.py!} ``` その追加情報はそのまま出力され、JSON Schemaに追加されます。 @@ -21,11 +21,14 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます: ```Python hl_lines="4 10 11 12 13" -{!../../../docs_src/schema_extra_example/tutorial002.py!} +{!../../docs_src/schema_extra_example/tutorial002.py!} ``` -!!! warning "注意" - これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 +/// warning | 注意 + +これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 + +/// ## `Body`の追加引数 @@ -34,7 +37,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 例えば、`Body`にボディリクエストの`example`を渡すことができます: ```Python hl_lines="21 22 23 24 25 26" -{!../../../docs_src/schema_extra_example/tutorial003.py!} +{!../../docs_src/schema_extra_example/tutorial003.py!} ``` ## ドキュメントのUIの例 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index f1c43b7b4..6ace1b542 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -21,17 +21,20 @@ `main.py`に、下記の例をコピーします: ```Python -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ## 実行 -!!! info "情報" - まず`python-multipart`をインストールします。 +/// info | 情報 - 例えば、`pip install python-multipart`。 +まず`python-multipart`をインストールします。 - これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。 +例えば、`pip install python-multipart`。 + +これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。 + +/// 例を実行します: @@ -53,17 +56,23 @@ $ uvicorn main:app --reload -!!! check "Authorizeボタン!" - すでにピカピカの新しい「Authorize」ボタンがあります。 +/// check | Authorizeボタン! + +すでにピカピカの新しい「Authorize」ボタンがあります。 + +そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。 - そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。 +/// それをクリックすると、`ユーザー名`と`パスワード` (およびその他のオプションフィールド) を入力する小さな認証フォームが表示されます: -!!! note "備考" - フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。 +/// note | 備考 + +フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。 + +/// もちろんエンドユーザーのためのフロントエンドではありません。しかし、すべてのAPIをインタラクティブにドキュメント化するための素晴らしい自動ツールです。 @@ -105,36 +114,45 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー この例では、**Bearer**トークンを使用して**OAuth2**を**パスワード**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。 -!!! info "情報" - 「bearer」トークンが、唯一の選択肢ではありません。 +/// info | 情報 + +「bearer」トークンが、唯一の選択肢ではありません。 - しかし、私たちのユースケースには最適です。 +しかし、私たちのユースケースには最適です。 - あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。 +あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。 - その場合、**FastAPI**はそれを構築するためのツールも提供します。 +その場合、**FastAPI**はそれを構築するためのツールも提供します。 + +/// `OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。 ```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` -!!! tip "豆知識" - ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。 +/// tip | 豆知識 + +ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。 - 相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。 +相対URLを使っているので、APIが`https://example.com/`にある場合、`https://example.com/token`を参照します。しかし、APIが`https://example.com/api/v1/`にある場合は`https://example.com/api/v1/token`を参照することになります。 - 相対 URL を使うことは、[プロキシと接続](./.../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。 +相対 URL を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。 + +/// このパラメーターはエンドポイント/ *path operation*を作成しません。しかし、URL`/token`はクライアントがトークンを取得するために使用するものであると宣言します。この情報は OpenAPI やインタラクティブな API ドキュメントシステムで使われます。 実際のpath operationもすぐに作ります。 -!!! info "情報" - 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。 +/// info | 情報 + +非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。 - それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。 +それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。 + +/// 変数`oauth2_scheme`は`OAuth2PasswordBearer`のインスタンスですが、「呼び出し可能」です。 @@ -151,17 +169,20 @@ oauth2_scheme(some, parameters) これで`oauth2_scheme`を`Depends`で依存関係に渡すことができます。 ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` この依存関係は、*path operation function*のパラメーター`token`に代入される`str`を提供します。 **FastAPI**は、この依存関係を使用してOpenAPIスキーマ (および自動APIドキュメント) で「セキュリティスキーム」を定義できることを知っています。 -!!! info "技術詳細" - **FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。 +/// info | 技術詳細 + +**FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。 + +OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。 - OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。 +/// ## どのように動作するか diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md index 7f8dcaad2..898bbd797 100644 --- a/docs/ja/docs/tutorial/security/get-current-user.md +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -3,7 +3,7 @@ 一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation関数* に `str` として `token` を与えていました: ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` しかし、それはまだそんなに有用ではありません。 @@ -17,7 +17,7 @@ ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます: ```Python hl_lines="5 12-16" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## 依存関係 `get_current_user` を作成 @@ -31,7 +31,7 @@ 以前直接 *path operation* の中でしていたのと同じように、新しい依存関係である `get_current_user` は `str` として `token` を受け取るようになります: ```Python hl_lines="25" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## ユーザーの取得 @@ -39,7 +39,7 @@ `get_current_user` は作成した(偽物の)ユーティリティ関数を使って、 `str` としてトークンを受け取り、先ほどのPydanticの `User` モデルを返却します: ```Python hl_lines="19-22 26-27" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## 現在のユーザーの注入 @@ -47,24 +47,28 @@ ですので、 `get_current_user` に対して同様に *path operation* の中で `Depends` を利用できます。 ```Python hl_lines="31" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` Pydanticモデルの `User` として、 `current_user` の型を宣言することに注意してください。 その関数の中ですべての入力補完や型チェックを行う際に役に立ちます。 -!!! tip "豆知識" - リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。 +/// tip | 豆知識 - ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。 +リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。 +ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。 -!!! check "確認" - 依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。 +/// - 同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。 +/// check | 確認 +依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。 + +同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。 + +/// ## 別のモデル @@ -100,7 +104,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ さらに、こうした何千もの *path operations* は、たった3行で表現できるのです: ```Python hl_lines="30-32" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/security/index.md b/docs/ja/docs/tutorial/security/index.md index 390f21047..37b8bb958 100644 --- a/docs/ja/docs/tutorial/security/index.md +++ b/docs/ja/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth 1というものもありましたが、これはOAuth2とは全く異な OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。 -!!! tip "豆知識" - **デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。 +/// tip | 豆知識 +**デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。 + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPIでは、以下のセキュリティスキームを定義しています: * この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。 -!!! tip "豆知識" - Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。 +/// tip | 豆知識 + +Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。 + +最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。 - 最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。 +/// ## **FastAPI** ユーティリティ diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index d5b179aa0..825a1b2b3 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -44,10 +44,13 @@ $ pip install python-jose[cryptography] ここでは、推奨されているものを使用します:pyca/cryptography。 -!!! tip "豆知識" - このチュートリアルでは以前、PyJWTを使用していました。 +/// tip | 豆知識 - しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。 +このチュートリアルでは以前、PyJWTを使用していました。 + +しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。 + +/// ## パスワードのハッシュ化 @@ -83,13 +86,15 @@ $ pip install passlib[bcrypt] -!!! tip "豆知識" - `passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。 +/// tip | 豆知識 + +`passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。 - 例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。 +例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。 - また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。 +また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。 +/// ## パスワードのハッシュ化と検証 @@ -97,12 +102,15 @@ $ pip install passlib[bcrypt] PassLib の「context」を作成します。これは、パスワードのハッシュ化と検証に使用されるものです。 -!!! tip "豆知識" - PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。 +/// tip | 豆知識 - 例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。 +PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。 - そして、同時にそれらはすべてに互換性があります。 +例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。 + +そして、同時にそれらはすべてに互換性があります。 + +/// ユーザーから送られてきたパスワードをハッシュ化するユーティリティー関数を作成します。 @@ -111,11 +119,14 @@ PassLib の「context」を作成します。これは、パスワードのハ さらに、ユーザーを認証して返す関数も作成します。 ```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` -!!! note "備考" - 新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"` +/// note | 備考 + +新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"` + +/// ## JWTトークンの取り扱い @@ -146,7 +157,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し 新しいアクセストークンを生成するユーティリティ関数を作成します。 ```Python hl_lines="6 12-14 28-30 78-86" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` ## 依存関係の更新 @@ -158,7 +169,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し トークンが無効な場合は、すぐにHTTPエラーを返します。 ```Python hl_lines="89-106" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` ## `/token` パスオペレーションの更新 @@ -168,7 +179,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し JWTアクセストークンを作成し、それを返します。 ```Python hl_lines="115-130" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` ### JWTの"subject" `sub` についての技術的な詳細 @@ -208,8 +219,11 @@ IDの衝突を回避するために、ユーザーのJWTトークンを作成す Username: `johndoe` Password: `secret` -!!! check "確認" - コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 +/// check | 確認 + +コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 + +/// @@ -230,8 +244,11 @@ Password: `secret` -!!! note "備考" - ヘッダーの`Authorization`には、`Bearer`で始まる値があります。 +/// note | 備考 + +ヘッダーの`Authorization`には、`Bearer`で始まる値があります。 + +/// ## `scopes` を使った高度なユースケース diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index 1d9c434c3..37ea22dd7 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -8,13 +8,16 @@ * `StaticFiles()` インスタンスを生成し、特定のパスに「マウント」。 ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` -!!! note "技術詳細" - `from starlette.staticfiles import StaticFiles` も使用できます。 +/// note | 技術詳細 - **FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。 +`from starlette.staticfiles import StaticFiles` も使用できます。 + +**FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。 + +/// ### 「マウント」とは diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index 037e9628f..b7e80cb8d 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -19,23 +19,32 @@ チェックしたい Python の標準的な式と共に、シンプルに `assert` 文を記述します。 ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip "豆知識" - テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 +/// tip | 豆知識 - また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。 +テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 - これにより、煩雑にならずに、`pytest` を直接使用できます。 +また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。 -!!! note "技術詳細" - `from starlette.testclient import TestClient` も使用できます。 +これにより、煩雑にならずに、`pytest` を直接使用できます。 - **FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。 +/// -!!! tip "豆知識" - FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。 +/// note | 技術詳細 + +`from starlette.testclient import TestClient` も使用できます。 + +**FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。 + +/// + +/// tip | 豆知識 + +FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。 + +/// ## テストの分離 @@ -48,7 +57,7 @@ **FastAPI** アプリに `main.py` ファイルがあるとします: ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### テストファイル @@ -56,7 +65,7 @@ 次に、テストを含む `test_main.py` ファイルを作成し、`main` モジュール (`main.py`) から `app` をインポートします: ```Python -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ## テスト: 例の拡張 @@ -74,24 +83,28 @@ これらの *path operation* には `X-Token` ヘッダーが必要です。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### 拡張版テストファイル 次に、先程のものに拡張版のテストを加えた、`test_main_b.py` を作成します。 ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` リクエストに情報を渡せるクライアントが必要で、その方法がわからない場合はいつでも、`httpx` での実現方法を検索 (Google) できます。 @@ -108,10 +121,13 @@ (`httpx` または `TestClient` を使用して) バックエンドにデータを渡す方法の詳細は、HTTPXのドキュメントを確認してください。 -!!! info "情報" - `TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 +/// info | 情報 + +`TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 + +テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。 - テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。 +/// ## 実行 diff --git a/docs/ko/docs/advanced/advanced-dependencies.md b/docs/ko/docs/advanced/advanced-dependencies.md new file mode 100644 index 000000000..aa5a332f8 --- /dev/null +++ b/docs/ko/docs/advanced/advanced-dependencies.md @@ -0,0 +1,179 @@ +# 고급 의존성 + +## 매개변수화된 의존성 + +지금까지 본 모든 의존성은 고정된 함수 또는 클래스입니다. + +하지만 여러 개의 함수나 클래스를 선언하지 않고도 의존성에 매개변수를 설정해야 하는 경우가 있을 수 있습니다. + +예를 들어, `q` 쿼리 매개변수가 특정 고정된 내용을 포함하고 있는지 확인하는 의존성을 원한다고 가정해 봅시다. + +이때 해당 고정된 내용을 매개변수화할 수 있길 바랍니다. + +## "호출 가능한" 인스턴스 + +Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법이 있습니다. + +클래스 자체(이미 호출 가능함)가 아니라 해당 클래스의 인스턴스에 대해 호출 가능하게 하는 것입니다. + +이를 위해 `__call__` 메서드를 선언합니다: + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 참고 + +가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +이 경우, **FastAPI**는 추가 매개변수와 하위 의존성을 확인하기 위해 `__call__`을 사용하게 되며, +나중에 *경로 연산 함수*에서 매개변수에 값을 전달할 때 이를 호출하게 됩니다. + +## 인스턴스 매개변수화하기 + +이제 `__init__`을 사용하여 의존성을 "매개변수화"할 수 있는 인스턴스의 매개변수를 선언할 수 있습니다: + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 참고 + +가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +이 경우, **FastAPI**는 `__init__`에 전혀 관여하지 않으며, 우리는 이 메서드를 코드에서 직접 사용하게 됩니다. + +## 인스턴스 생성하기 + +다음과 같이 이 클래스의 인스턴스를 생성할 수 있습니다: + +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 참고 + +가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. + +/// + +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +이렇게 하면 `checker.fixed_content` 속성에 `"bar"`라는 값을 담아 의존성을 "매개변수화"할 수 있습니다. + +## 인스턴스를 의존성으로 사용하기 + +그런 다음, `Depends(FixedContentQueryChecker)` 대신 `Depends(checker)`에서 이 `checker` 인스턴스를 사용할 수 있으며, +클래스 자체가 아닌 인스턴스 `checker`가 의존성이 됩니다. + +의존성을 해결할 때 **FastAPI**는 이 `checker`를 다음과 같이 호출합니다: + +```Python +checker(q="somequery") +``` + +...그리고 이때 반환되는 값을 *경로 연산 함수*의 `fixed_content_included` 매개변수로 전달합니다: + +//// tab | Python 3.9+ + +```Python hl_lines="22" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 참고 + +가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. + +/// + +```Python hl_lines="20" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +/// tip | 참고 + +이 모든 과정이 복잡하게 느껴질 수 있습니다. 그리고 지금은 이 방법이 얼마나 유용한지 명확하지 않을 수도 있습니다. + +이 예시는 의도적으로 간단하게 만들었지만, 전체 구조가 어떻게 작동하는지 보여줍니다. + +보안 관련 장에서는 이와 같은 방식으로 구현된 편의 함수들이 있습니다. + +이 모든 과정을 이해했다면, 이러한 보안 도구들이 내부적으로 어떻게 작동하는지 이미 파악한 것입니다. + +/// diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md new file mode 100644 index 000000000..273c9a479 --- /dev/null +++ b/docs/ko/docs/advanced/events.md @@ -0,0 +1,57 @@ +# 이벤트: startup과 shutdown + +필요에 따라 응용 프로그램이 시작되기 전이나 종료될 때 실행되는 이벤트 핸들러(함수)를 정의할 수 있습니다. + +이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다. + +/// warning | 경고 + +이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다. + +/// + +## `startup` 이벤트 + +응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다: + +```Python hl_lines="8" +{!../../docs_src/events/tutorial001.py!} +``` + +이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다. + +하나 이상의 이벤트 핸들러 함수를 추가할 수도 있습니다. + +그리고 응용 프로그램은 모든 `startup` 이벤트 핸들러가 완료될 때까지 요청을 받지 않습니다. + +## `shutdown` 이벤트 + +응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다: + +```Python hl_lines="6" +{!../../docs_src/events/tutorial002.py!} +``` + +이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. + +/// info | 정보 + +`open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다. + +/// + +/// tip | 팁 + +이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다. + +따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다. + +그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다. + +/// + +/// info | 정보 + +이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다. + +/// diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md index 5fd1711a1..31704727c 100644 --- a/docs/ko/docs/advanced/index.md +++ b/docs/ko/docs/advanced/index.md @@ -6,10 +6,13 @@ 이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다. -!!! tip "팁" - 다음 장들이 **반드시 "심화"**인 것은 아닙니다. +/// tip | 팁 - 그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다. +다음 장들이 **반드시 "심화"**인 것은 아닙니다. + +그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다. + +/// ## 자습서를 먼저 읽으십시오 diff --git a/docs/ko/docs/advanced/response-change-status-code.md b/docs/ko/docs/advanced/response-change-status-code.md new file mode 100644 index 000000000..f3cdd2ba5 --- /dev/null +++ b/docs/ko/docs/advanced/response-change-status-code.md @@ -0,0 +1,33 @@ +# 응답 - 상태 코드 변경 + +기본 [응답 상태 코드 설정](../tutorial/response-status-code.md){.internal-link target=_blank}이 가능하다는 걸 이미 알고 계실 겁니다. + +하지만 경우에 따라 기본 설정과 다른 상태 코드를 반환해야 할 때가 있습니다. + +## 사용 예 + +예를 들어 기본적으로 HTTP 상태 코드 "OK" `200`을 반환하고 싶다고 가정해 봅시다. + +하지만 데이터가 존재하지 않으면 이를 새로 생성하고, HTTP 상태 코드 "CREATED" `201`을 반환하고자 할 때가 있을 수 있습니다. + +이때도 여전히 `response_model`을 사용하여 반환하는 데이터를 필터링하고 변환하고 싶을 수 있습니다. + +이런 경우에는 `Response` 파라미터를 사용할 수 있습니다. + +## `Response` 파라미터 사용하기 + +*경로 작동 함수*에 `Response` 타입의 파라미터를 선언할 수 있습니다. (쿠키와 헤더에 대해 선언하는 것과 유사하게) + +그리고 이 *임시* 응답 객체에서 `status_code`를 설정할 수 있습니다. + +```Python hl_lines="1 9 12" +{!../../docs_src/response_change_status_code/tutorial001.py!} +``` + +그리고 평소처럼 원하는 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +`response_model`을 선언했다면 반환된 객체는 여전히 필터링되고 변환됩니다. + +**FastAPI**는 이 *임시* 응답 객체에서 상태 코드(쿠키와 헤더 포함)를 추출하여, `response_model`로 필터링된 반환 값을 최종 응답에 넣습니다. + +또한, 의존성에서도 `Response` 파라미터를 선언하고 그 안에서 상태 코드를 설정할 수 있습니다. 단, 마지막으로 설정된 상태 코드가 우선 적용된다는 점을 유의하세요. diff --git a/docs/ko/docs/advanced/response-cookies.md b/docs/ko/docs/advanced/response-cookies.md new file mode 100644 index 000000000..f762e94b5 --- /dev/null +++ b/docs/ko/docs/advanced/response-cookies.md @@ -0,0 +1,53 @@ +# 응답 쿠키 + +## `Response` 매개변수 사용하기 + +*경로 작동 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다. + +그런 다음 해당 *임시* 응답 객체에서 쿠키를 설정할 수 있습니다. + +```Python hl_lines="1 8-9" +{!../../docs_src/response_cookies/tutorial002.py!} +``` + +그런 다음 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +그리고 `response_model`을 선언했다면 반환한 객체를 거르고 변환하는 데 여전히 사용됩니다. + +**FastAPI**는 그 *임시* 응답에서 쿠키(또한 헤더 및 상태 코드)를 추출하고, 반환된 값이 포함된 최종 응답에 이를 넣습니다. 이 값은 `response_model`로 걸러지게 됩니다. + +또한 의존관계에서 `Response` 매개변수를 선언하고, 해당 의존성에서 쿠키(및 헤더)를 설정할 수도 있습니다. + +## `Response`를 직접 반환하기 + +코드에서 `Response`를 직접 반환할 때도 쿠키를 생성할 수 있습니다. + +이를 위해 [Response를 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성할 수 있습니다. + +그런 다음 쿠키를 설정하고 반환하면 됩니다: +```Python hl_lines="1 18" +{!../../docs_src/response_directly/tutorial002.py!} +``` +/// tip + +`Response` 매개변수를 사용하지 않고 응답을 직접 반환하는 경우, FastAPI는 이를 직접 반환한다는 점에 유의하세요. + +따라서 데이터가 올바른 유형인지 확인해야 합니다. 예: `JSONResponse`를 반환하는 경우, JSON과 호환되는지 확인하세요. + +또한 `response_model`로 걸러져야 할 데이터가 전달되지 않도록 확인하세요. + +/// + +### 추가 정보 + +/// note | 기술적 세부사항 + +`from starlette.responses import Response` 또는 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자의 편의를 위해 `fastapi.responses`로 동일한 `starlette.responses`를 제공합니다. 그러나 대부분의 응답은 Starlette에서 직접 제공됩니다. + +또한 `Response`는 헤더와 쿠키를 설정하는 데 자주 사용되므로, **FastAPI**는 이를 `fastapi.Response`로도 제공합니다. + +/// + +사용 가능한 모든 매개변수와 옵션은 Starlette 문서에서 확인할 수 있습니다. diff --git a/docs/ko/docs/advanced/response-directly.md b/docs/ko/docs/advanced/response-directly.md new file mode 100644 index 000000000..aedebff9d --- /dev/null +++ b/docs/ko/docs/advanced/response-directly.md @@ -0,0 +1,67 @@ +# 응답을 직접 반환하기 + +**FastAPI**에서 *경로 작업(path operation)*을 생성할 때, 일반적으로 `dict`, `list`, Pydantic 모델, 데이터베이스 모델 등의 데이터를 반환할 수 있습니다. + +기본적으로 **FastAPI**는 [JSON 호환 가능 인코더](../tutorial/encoder.md){.internal-link target=_blank}에 설명된 `jsonable_encoder`를 사용해 해당 반환 값을 자동으로 `JSON`으로 변환합니다. + +그런 다음, JSON 호환 데이터(예: `dict`)를 `JSONResponse`에 넣어 사용자의 응답을 전송하는 방식으로 처리됩니다. + +그러나 *경로 작업*에서 `JSONResponse`를 직접 반환할 수도 있습니다. + +예를 들어, 사용자 정의 헤더나 쿠키를 반환해야 하는 경우에 유용할 수 있습니다. + +## `Response` 반환하기 + +사실, `Response` 또는 그 하위 클래스를 반환할 수 있습니다. + +/// tip + +`JSONResponse` 자체도 `Response`의 하위 클래스입니다. + +/// + +그리고 `Response`를 반환하면 **FastAPI**가 이를 그대로 전달합니다. + +Pydantic 모델로 데이터 변환을 수행하지 않으며, 내용을 다른 형식으로 변환하지 않습니다. + +이로 인해 많은 유연성을 얻을 수 있습니다. 어떤 데이터 유형이든 반환할 수 있고, 데이터 선언이나 유효성 검사를 재정의할 수 있습니다. + +## `Response`에서 `jsonable_encoder` 사용하기 + +**FastAPI**는 반환하는 `Response`에 아무런 변환을 하지 않으므로, 그 내용이 준비되어 있어야 합니다. + +예를 들어, Pydantic 모델을 `dict`로 변환해 `JSONResponse`에 넣지 않으면 JSON 호환 유형으로 변환된 데이터 유형(예: `datetime`, `UUID` 등)이 사용되지 않습니다. + +이러한 경우, 데이터를 응답에 전달하기 전에 `jsonable_encoder`를 사용하여 변환할 수 있습니다: + +```Python hl_lines="6-7 21-22" +{!../../docs_src/response_directly/tutorial001.py!} +``` + +/// note | 기술적 세부 사항 + +`from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자의 편의를 위해 `starlette.responses`를 `fastapi.responses`로 제공합니다. 그러나 대부분의 가능한 응답은 Starlette에서 직접 제공합니다. + +/// + +## 사용자 정의 `Response` 반환하기 +위 예제는 필요한 모든 부분을 보여주지만, 아직 유용하지는 않습니다. 사실 데이터를 직접 반환하면 **FastAPI**가 이를 `JSONResponse`에 넣고 `dict`로 변환하는 등 모든 작업을 자동으로 처리합니다. + +이제, 사용자 정의 응답을 반환하는 방법을 알아보겠습니다. + +예를 들어 XML 응답을 반환하고 싶다고 가정해보겠습니다. + +XML 내용을 문자열에 넣고, 이를 `Response`에 넣어 반환할 수 있습니다: + +```Python hl_lines="1 18" +{!../../docs_src/response_directly/tutorial002.py!} +``` + +## 참고 사항 +`Response`를 직접 반환할 때, 그 데이터는 자동으로 유효성 검사되거나, 변환(직렬화)되거나, 문서화되지 않습니다. + +그러나 [OpenAPI에서 추가 응답](additional-responses.md){.internal-link target=_blank}에서 설명된 대로 문서화할 수 있습니다. + +이후 단락에서 자동 데이터 변환, 문서화 등을 사용하면서 사용자 정의 `Response`를 선언하는 방법을 확인할 수 있습니다. diff --git a/docs/ko/docs/advanced/response-headers.md b/docs/ko/docs/advanced/response-headers.md new file mode 100644 index 000000000..974a06969 --- /dev/null +++ b/docs/ko/docs/advanced/response-headers.md @@ -0,0 +1,45 @@ +# 응답 헤더 + +## `Response` 매개변수 사용하기 + +여러분은 *경로 작동 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다 (쿠키와 같이 사용할 수 있습니다). + +그런 다음, 여러분은 해당 *임시* 응답 객체에서 헤더를 설정할 수 있습니다. + +```Python hl_lines="1 7-8" +{!../../docs_src/response_headers/tutorial002.py!} +``` + +그 후, 일반적으로 사용하듯이 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +`response_model`을 선언한 경우, 반환한 객체를 필터링하고 변환하는 데 여전히 사용됩니다. + +**FastAPI**는 해당 *임시* 응답에서 헤더(쿠키와 상태 코드도 포함)를 추출하여, 여러분이 반환한 값을 포함하는 최종 응답에 `response_model`로 필터링된 값을 넣습니다. + +또한, 종속성에서 `Response` 매개변수를 선언하고 그 안에서 헤더(및 쿠키)를 설정할 수 있습니다. + +## `Response` 직접 반환하기 + +`Response`를 직접 반환할 때에도 헤더를 추가할 수 있습니다. + +[응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성하고, 헤더를 추가 매개변수로 전달하세요. + +```Python hl_lines="10-12" +{!../../docs_src/response_headers/tutorial001.py!} +``` + +/// note | 기술적 세부사항 + +`from starlette.responses import Response`나 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 `starlette.responses`를 `fastapi.responses`로 개발자의 편의를 위해 직접 제공하지만, 대부분의 응답은 Starlette에서 직접 제공됩니다. + +그리고 `Response`는 헤더와 쿠키를 설정하는 데 자주 사용될 수 있으므로, **FastAPI**는 `fastapi.Response`로도 이를 제공합니다. + +/// + +## 커스텀 헤더 + +‘X-’ 접두어를 사용하여 커스텀 사설 헤더를 추가할 수 있습니다. + +하지만, 여러분이 브라우저에서 클라이언트가 볼 수 있기를 원하는 커스텀 헤더가 있는 경우, CORS 설정에 이를 추가해야 합니다([CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}에서 자세히 알아보세요). `expose_headers` 매개변수를 사용하여 Starlette의 CORS 설명서에 문서화된 대로 설정할 수 있습니다. diff --git a/docs/ko/docs/advanced/testing-events.md b/docs/ko/docs/advanced/testing-events.md new file mode 100644 index 000000000..dc082412a --- /dev/null +++ b/docs/ko/docs/advanced/testing-events.md @@ -0,0 +1,7 @@ +# 이벤트 테스트: 시작 - 종료 + +테스트에서 이벤트 핸들러(`startup` 및 `shutdown`)를 실행해야 하는 경우, `with` 문과 함께 `TestClient`를 사용할 수 있습니다. + +```Python hl_lines="9-12 20-24" +{!../../docs_src/app_testing/tutorial003.py!} +``` diff --git a/docs/ko/docs/advanced/testing-websockets.md b/docs/ko/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..f1580c3c3 --- /dev/null +++ b/docs/ko/docs/advanced/testing-websockets.md @@ -0,0 +1,15 @@ +# WebSocket 테스트하기 + +`TestClient`를 사용하여 WebSocket을 테스트할 수 있습니다. + +이를 위해 `with` 문에서 `TestClient`를 사용하여 WebSocket에 연결합니다: + +```Python hl_lines="27-31" +{!../../docs_src/app_testing/tutorial002.py!} +``` + +/// note | 참고 + +자세한 내용은 Starlette의 WebSocket 테스트에 관한 설명서를 참고하시길 바랍니다. + +/// diff --git a/docs/ko/docs/advanced/using-request-directly.md b/docs/ko/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..027ea9fad --- /dev/null +++ b/docs/ko/docs/advanced/using-request-directly.md @@ -0,0 +1,58 @@ +# `Request` 직접 사용하기 + +지금까지 요청에서 필요한 부분을 각 타입으로 선언하여 사용해 왔습니다. + +다음과 같은 곳에서 데이터를 가져왔습니다: + +* 경로의 파라미터로부터. +* 헤더. +* 쿠키. +* 기타 등등. + +이렇게 함으로써, **FastAPI**는 데이터를 검증하고 변환하며, API에 대한 문서를 자동화로 생성합니다. + +하지만 `Request` 객체에 직접 접근해야 하는 상황이 있을 수 있습니다. + +## `Request` 객체에 대한 세부 사항 + +**FastAPI**는 실제로 내부에 **Starlette**을 사용하며, 그 위에 여러 도구를 덧붙인 구조입니다. 따라서 여러분이 필요할 때 Starlette의 `Request` 객체를 직접 사용할 수 있습니다. + +`Request` 객체에서 데이터를 직접 가져오는 경우(예: 본문을 읽기)에는 FastAPI가 해당 데이터를 검증하거나 변환하지 않으며, 문서화(OpenAPI를 통한 문서 자동화(로 생성된) API 사용자 인터페이스)도 되지 않습니다. + +그러나 다른 매개변수(예: Pydantic 모델을 사용한 본문)는 여전히 검증, 변환, 주석 추가 등이 이루어집니다. + +하지만 특정한 경우에는 `Request` 객체에 직접 접근하는 것이 유용할 수 있습니다. + +## `Request` 객체를 직접 사용하기 + +여러분이 클라이언트의 IP 주소/호스트 정보를 *경로 작동 함수* 내부에서 가져와야 한다고 가정해 보겠습니다. + +이를 위해서는 요청에 직접 접근해야 합니다. + +```Python hl_lines="1 7-8" +{!../../docs_src/using_request_directly/tutorial001.py!} +``` + +*경로 작동 함수* 매개변수를 `Request` 타입으로 선언하면 **FastAPI**가 해당 매개변수에 `Request` 객체를 전달하는 것을 알게 됩니다. + +/// tip | 팁 + +이 경우, 요청 매개변수와 함께 경로 매개변수를 선언한 것을 볼 수 있습니다. + +따라서, 경로 매개변수는 추출되고 검증되며 지정된 타입으로 변환되고 OpenAPI로 주석이 추가됩니다. + +이와 같은 방식으로, 다른 매개변수들을 평소처럼 선언하면서, 부가적으로 `Request`도 가져올 수 있습니다. + +/// + +## `Request` 설명서 + +여러분은 `Request` 객체에 대한 더 자세한 내용을 공식 Starlette 설명서 사이트에서 읽어볼 수 있습니다. + +/// note | 기술 세부사항 + +`from starlette.requests import Request`를 사용할 수도 있습니다. + +**FastAPI**는 여러분(개발자)를 위한 편의를 위해 이를 직접 제공하지만, 실제로는 Starlette에서 가져온 것입니다. + +/// diff --git a/docs/ko/docs/advanced/wsgi.md b/docs/ko/docs/advanced/wsgi.md new file mode 100644 index 000000000..87aabf203 --- /dev/null +++ b/docs/ko/docs/advanced/wsgi.md @@ -0,0 +1,37 @@ +# WSGI 포함하기 - Flask, Django 그 외 + +[서브 응용 프로그램 - 마운트](sub-applications.md){.internal-link target=_blank}, [프록시 뒤편에서](behind-a-proxy.md){.internal-link target=_blank}에서 보았듯이 WSGI 응용 프로그램들을 다음과 같이 마운트 할 수 있습니다. + +`WSGIMiddleware`를 사용하여 WSGI 응용 프로그램(예: Flask, Django 등)을 감쌀 수 있습니다. + +## `WSGIMiddleware` 사용하기 + +`WSGIMiddleware`를 불러와야 합니다. + +그런 다음, WSGI(예: Flask) 응용 프로그램을 미들웨어로 포장합니다. + +그 후, 해당 경로에 마운트합니다. + +```Python hl_lines="2-3 23" +{!../../docs_src/wsgi/tutorial001.py!} +``` + +## 확인하기 + +이제 `/v1/` 경로에 있는 모든 요청은 Flask 응용 프로그램에서 처리됩니다. + +그리고 나머지는 **FastAPI**에 의해 처리됩니다. + +실행하면 http://localhost:8000/v1/으로 이동해서 Flask의 응답을 볼 수 있습니다: + +```txt +Hello, World from Flask! +``` + +그리고 다음으로 이동하면 http://localhost:8000/v2 Flask의 응답을 볼 수 있습니다: + +```JSON +{ + "message": "Hello World" +} +``` diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md index 9bcebd367..fa0d20488 100644 --- a/docs/ko/docs/async.md +++ b/docs/ko/docs/async.md @@ -2,7 +2,7 @@ *경로 작동 함수*에서의 `async def` 문법에 대한 세부사항과 비동기 코드, 동시성 및 병렬성에 대한 배경 -## 바쁘신 경우 +## 바쁘신 경우 요약 @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "참고" - `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. +/// note | 참고 + +`async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. + +/// --- @@ -263,7 +266,7 @@ CPU에 묶인 연산에 관한 흔한 예시는 복잡한 수학 처리를 필 파이썬이 **데이터 사이언스**, 머신러닝과 특히 딥러닝에 의 주된 언어라는 간단한 사실에 더해서, 이것은 FastAPI를 데이터 사이언스 / 머신러닝 웹 API와 응용프로그램에 (다른 것들보다) 좋은 선택지가 되게 합니다. -배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](/ko/deployment){.internal-link target=_blank}문서를 참고하십시오. +배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](deployment/index.md){.internal-link target=_blank}문서를 참고하십시오. ## `async`와 `await` @@ -366,12 +369,15 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 I/O를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다. -하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](index.md#performance){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다. +하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](index.md#_11){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다. ### 의존성 @@ -401,4 +407,4 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 가장 빠른 Python 프레임워크 중 하나로 실행되며, Starlette와 Uvicorn 자체(내부적으로 FastAPI가 사용하는 도구)보다 조금 아래에 위치합니다. + +그러나 벤치마크와 비교를 확인할 때 다음 사항을 염두에 두어야 합니다. + +## 벤치마크와 속도 + +벤치마크를 확인할 때, 일반적으로 여러 가지 유형의 도구가 동등한 것으로 비교되는 것을 볼 수 있습니다. + +특히, Uvicorn, Starlette, FastAPI가 함께 비교되는 경우가 많습니다(다른 여러 도구와 함께). + +도구가 해결하는 문제가 단순할수록 성능이 더 좋아집니다. 그리고 대부분의 벤치마크는 도구가 제공하는 추가 기능을 테스트하지 않습니다. + +계층 구조는 다음과 같습니다: + +* **Uvicorn**: ASGI 서버 + * **Starlette**: (Uvicorn 사용) 웹 마이크로 프레임워크 + * **FastAPI**: (Starlette 사용) API 구축을 위한 데이터 검증 등 여러 추가 기능이 포함된 API 마이크로 프레임워크 + +* **Uvicorn**: + * 서버 자체 외에는 많은 추가 코드가 없기 때문에 최고의 성능을 발휘합니다. + * 직접 Uvicorn으로 응용 프로그램을 작성하지는 않을 것입니다. 즉, 사용자의 코드에는 적어도 Starlette(또는 **FastAPI**)에서 제공하는 모든 코드가 포함되어야 합니다. 그렇게 하면 최종 응용 프로그램은 프레임워크를 사용하고 앱 코드와 버그를 최소화하는 것과 동일한 오버헤드를 갖게 됩니다. + * Uvicorn을 비교할 때는 Daphne, Hypercorn, uWSGI 등의 응용 프로그램 서버와 비교하세요. +* **Starlette**: + * Uvicorn 다음으로 좋은 성능을 발휘합니다. 사실 Starlette는 Uvicorn을 사용하여 실행됩니다. 따라서 더 많은 코드를 실행해야 하기 때문에 Uvicorn보다 "느려질" 수밖에 없습니다. + * 하지만 경로 기반 라우팅 등 간단한 웹 응용 프로그램을 구축할 수 있는 도구를 제공합니다. + * Starlette를 비교할 때는 Sanic, Flask, Django 등의 웹 프레임워크(또는 마이크로 프레임워크)와 비교하세요. +* **FastAPI**: + * Starlette가 Uvicorn을 사용하므로 Uvicorn보다 빨라질 수 없는 것과 마찬가지로, **FastAPI**는 Starlette를 사용하므로 더 빠를 수 없습니다. + * FastAPI는 Starlette에 추가적으로 더 많은 기능을 제공합니다. API를 구축할 때 거의 항상 필요한 데이터 검증 및 직렬화와 같은 기능들이 포함되어 있습니다. 그리고 이를 사용하면 문서 자동화 기능도 제공됩니다(문서 자동화는 응용 프로그램 실행 시 오버헤드를 추가하지 않고 시작 시 생성됩니다). + * FastAPI를 사용하지 않고 직접 Starlette(또는 Sanic, Flask, Responder 등)를 사용했다면 데이터 검증 및 직렬화를 직접 구현해야 합니다. 따라서 최종 응용 프로그램은 FastAPI를 사용한 것과 동일한 오버헤드를 가지게 될 것입니다. 많은 경우 데이터 검증 및 직렬화가 응용 프로그램에서 작성된 코드 중 가장 많은 부분을 차지합니다. + * 따라서 FastAPI를 사용함으로써 개발 시간, 버그, 코드 라인을 줄일 수 있으며, FastAPI를 사용하지 않았을 때와 동일하거나 더 나은 성능을 얻을 수 있습니다(코드에서 모두 구현해야 하기 때문에). + * FastAPI를 비교할 때는 Flask-apispec, NestJS, Molten 등 데이터 검증, 직렬화 및 문서화가 통합된 자동 데이터 검증, 직렬화 및 문서화를 제공하는 웹 응용 프로그램 프레임워크(또는 도구 집합)와 비교하세요. diff --git a/docs/ko/docs/deployment/docker.md b/docs/ko/docs/deployment/docker.md index 1c7bced2c..e8b2746c5 100644 --- a/docs/ko/docs/deployment/docker.md +++ b/docs/ko/docs/deployment/docker.md @@ -4,8 +4,11 @@ FastAPI 어플리케이션을 배포할 때 일반적인 접근 방법은 **리 리눅스 컨테이너를 사용하는 데에는 **보안**, **반복 가능성**, **단순함** 등의 장점이 있습니다. -!!! tip "팁" - 시간에 쫓기고 있고 이미 이런것들을 알고 있다면 [`Dockerfile`👇](#build-a-docker-image-for-fastapi)로 점프할 수 있습니다. +/// tip | 팁 + +시간에 쫓기고 있고 이미 이런것들을 알고 있다면 [`Dockerfile`👇](#build-a-docker-image-for-fastapi)로 점프할 수 있습니다. + +///
도커파일 미리보기 👀 @@ -108,7 +111,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 가장 일반적인 방법은 패키지 이름과 버전이 줄 별로 기록된 `requirements.txt` 파일을 만드는 것입니다. -버전의 범위를 설정하기 위해서는 [FastAPI 버전들에 대하여](./versions.md){.internal-link target=_blank}에 쓰여진 것과 같은 아이디어를 사용합니다. +버전의 범위를 설정하기 위해서는 [FastAPI 버전들에 대하여](versions.md){.internal-link target=_blank}에 쓰여진 것과 같은 아이디어를 사용합니다. 예를 들어, `requirements.txt` 파일은 다음과 같을 수 있습니다: @@ -130,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info "정보" - 패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다. +/// info | 정보 + +패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다. - 나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇 +나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇 + +/// ### **FastAPI** 코드 생성하기 @@ -199,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 옵션은 `pip`에게 다운로드한 패키지들을 로컬 환경에 저장하지 않도록 전달합니다. 이는 마치 같은 패키지를 설치하기 위해 오직 `pip`만 다시 실행하면 될 것 같지만, 컨테이너로 작업하는 경우 그렇지는 않습니다. - !!! 노트 - `--no-cache-dir` 는 오직 `pip`와 관련되어 있으며, 도커나 컨테이너와는 무관합니다. + /// note | 노트 + + `--no-cache-dir` 는 오직 `pip`와 관련되어 있으며, 도커나 컨테이너와는 무관합니다. + + /// `--upgrade` 옵션은 `pip`에게 설치된 패키지들을 업데이트하도록 합니다. @@ -222,8 +231,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 프로그램이 `/code`에서 시작하고 그 속에 `./app` 디렉터리가 여러분의 코드와 함께 들어있기 때문에, **Uvicorn**은 이를 보고 `app`을 `app.main`으로부터 **불러 올** 것입니다. -!!! tip "팁" - 각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆 +/// tip | 팁 + +각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆 + +/// 이제 여러분은 다음과 같은 디렉터리 구조를 가지고 있을 것입니다: @@ -293,10 +305,13 @@ $ docker build -t myimage . -!!! tip "팁" - 맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다. +/// tip | 팁 + +맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다. - 이 경우에는 현재 디렉터리(`.`)와 같습니다. +이 경우에는 현재 디렉터리(`.`)와 같습니다. + +/// ### 도커 컨테이너 시작하기 @@ -373,7 +388,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## 배포 개념 -이제 컨테이너의 측면에서 [배포 개념](./concepts.md){.internal-link target=_blank}에서 다루었던 것과 같은 배포 개념에 대해 이야기해 보겠습니다. +이제 컨테이너의 측면에서 [배포 개념](concepts.md){.internal-link target=_blank}에서 다루었던 것과 같은 배포 개념에 대해 이야기해 보겠습니다. 컨테이너는 주로 어플리케이션을 빌드하고 배포하기 위한 과정을 단순화하는 도구이지만, **배포 개념**에 대한 특정한 접근법을 강요하지 않기 때문에 가능한 배포 전략에는 여러가지가 있습니다. @@ -394,8 +409,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] **HTTPS**와 **인증서**의 **자동** 취득을 다루는 것은 다른 컨테이너가 될 수 있는데, 예를 들어 Traefik을 사용하는 것입니다. -!!! tip "팁" - Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다. +/// tip | 팁 + +Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다. + +/// 대안적으로, HTTPS는 클라우드 제공자에 의해 서비스의 일환으로 다루어질 수도 있습니다 (이때도 어플리케이션은 여전히 컨테이너에서 실행될 것입니다). @@ -423,8 +441,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 이 요소가 요청들의 **로드**를 읽어들이고 각 워커에게 (바라건대) **균형적으로** 분배한다면, 이 요소는 일반적으로 **로드 밸런서**라고 불립니다. -!!! tip "팁" - HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다. +/// tip | 팁 + +HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다. + +/// 또한 컨테이너로 작업할 때, 컨테이너를 시작하고 관리하기 위해 사용한 것과 동일한 시스템은 이미 해당 **로드 밸런서**로 부터 여러분의 앱에 해당하는 컨테이너로 **네트워크 통신**(예를 들어, HTTP 요청)을 전송하는 내부적인 도구를 가지고 있을 것입니다 (여기서도 로드 밸런서는 **TLS 종료 프록시**일 수 있습니다). @@ -503,8 +524,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 만약 여러분이 **여러개의 컨테이너**를 가지고 있다면, 아마도 각각의 컨테이너는 **하나의 프로세스**를 가지고 있을 것입니다(예를 들어, **쿠버네티스** 클러스터에서). 그러면 여러분은 복제된 워커 컨테이너를 실행하기 **이전에**, 하나의 컨테이너에 있는 **이전의 단계들을** 수행하는 단일 프로세스를 가지는 **별도의 컨테이너들**을 가지고 싶을 것입니다. -!!! info "정보" - 만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 Init Container일 것입니다. +/// info | 정보 + +만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 Init Container일 것입니다. + +/// 만약 여러분의 이용 사례에서 이전 단계들을 **병렬적으로 여러번** 수행하는데에 문제가 없다면 (예를 들어 데이터베이스 이전을 실행하지 않고 데이터베이스가 준비되었는지 확인만 하는 경우), 메인 프로세스를 시작하기 전에 이 단계들을 각 컨테이너에 넣을 수 있습니다. @@ -514,14 +538,17 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Gunicorn과 함께하는 공식 도커 이미지 - Uvicorn -앞 챕터에서 자세하게 설명된 것 처럼, Uvicorn 워커와 같이 실행되는 Gunicorn을 포함하는 공식 도커 이미지가 있습니다: [서버 워커 - Uvicorn과 함께하는 Gunicorn](./server-workers.md){.internal-link target=_blank}. +앞 챕터에서 자세하게 설명된 것 처럼, Uvicorn 워커와 같이 실행되는 Gunicorn을 포함하는 공식 도커 이미지가 있습니다: [서버 워커 - Uvicorn과 함께하는 Gunicorn](server-workers.md){.internal-link target=_blank}. 이 이미지는 주로 위에서 설명된 상황에서 유용할 것입니다: [다중 프로세스를 가지는 컨테이너와 특수한 경우들](#containers-with-multiple-processes-and-special-cases). * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning "경고" - 여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다. +/// warning | 경고 + +여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다. + +/// 이 이미지는 가능한 CPU 코어에 기반한 **몇개의 워커 프로세스**를 설정하는 **자동-튜닝** 메커니즘을 포함하고 있습니다. @@ -529,8 +556,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 또한 스크립트를 통해 **시작하기 전 사전 단계**를 실행하는 것을 지원합니다. -!!! tip "팁" - 모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: tiangolo/uvicorn-gunicorn-fastapi. +/// tip | 팁 + +모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### 공식 도커 이미지에 있는 프로세스 개수 @@ -657,8 +687,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. `uvicorn` 커맨드를 실행하여, `app.main`에서 불러온 `app` 객체를 사용하도록 합니다. -!!! tip "팁" - 버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다. +/// tip | 팁 + +버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다. + +/// **도커 스테이지**란 `Dockefile`의 일부로서 나중에 사용하기 위한 파일들을 생성하기 위한 **일시적인 컨테이너 이미지**로 작동합니다. diff --git a/docs/ko/docs/deployment/server-workers.md b/docs/ko/docs/deployment/server-workers.md index 5653c55e3..b40b25cd8 100644 --- a/docs/ko/docs/deployment/server-workers.md +++ b/docs/ko/docs/deployment/server-workers.md @@ -13,14 +13,17 @@ 애플리케이션을 배포할 때 **다중 코어**를 활용하고 더 많은 요청을 처리할 수 있도록 **프로세스 복제본**이 필요합니다. -전 과정이었던 [배포 개념들](./concepts.md){.internal-link target=_blank}에서 본 것처럼 여러가지 방법이 존재합니다. +전 과정이었던 [배포 개념들](concepts.md){.internal-link target=_blank}에서 본 것처럼 여러가지 방법이 존재합니다. 지금부터 **구니콘**을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다. -!!! 정보 - 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](./docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. +/// info | 정보 - 특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다. +만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. + +특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다. + +/// ## 구니콘과 유비콘 워커 @@ -165,7 +168,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## 컨테이너와 도커 -다음 장인 [FastAPI와 컨테이너 - 도커](./docker.md){.internal-link target=_blank}에서 다른 **배포 개념들**을 다루는 전략들을 알려드리겠습니다. +다음 장인 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 다른 **배포 개념들**을 다루는 전략들을 알려드리겠습니다. 또한 간단한 케이스에서 사용할 수 있는, **구니콘과 유비콘 워커**가 포함돼 있는 **공식 도커 이미지**와 함께 몇 가지 기본 구성을 보여드리겠습니다. diff --git a/docs/ko/docs/deployment/versions.md b/docs/ko/docs/deployment/versions.md index 074c15158..559a892ab 100644 --- a/docs/ko/docs/deployment/versions.md +++ b/docs/ko/docs/deployment/versions.md @@ -43,8 +43,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI는 오류를 수정하고, 일반적인 변경사항을 위해 "패치"버전의 관습을 따릅니다. -!!! tip "팁" - 여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다. +/// tip | 팁 + +여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다. + +/// 따라서 다음과 같이 버전을 표시할 수 있습니다: @@ -54,8 +57,11 @@ fastapi>=0.45.0,<0.46.0 수정된 사항과 새로운 요소들이 "마이너" 버전에 추가되었습니다. -!!! tip "팁" - "마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다. +/// tip | 팁 + +"마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다. + +/// ## FastAPI 버전의 업그레이드 diff --git a/docs/ko/docs/environment-variables.md b/docs/ko/docs/environment-variables.md new file mode 100644 index 000000000..1e6af3ceb --- /dev/null +++ b/docs/ko/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 환경 변수 + +/// tip | 팁 + +만약 "환경 변수"가 무엇이고, 어떻게 사용하는지 알고 계시다면, 이 챕터를 스킵하셔도 좋습니다. + +/// + +환경 변수는 파이썬 코드의 **바깥**인, **운영 체제**에 존재하는 변수입니다. 파이썬 코드나 다른 프로그램에서 읽을 수 있습니다. + +환경 변수는 애플리케이션 **설정**을 처리하거나, 파이썬의 **설치** 과정의 일부로 유용합니다. + +## 환경 변수를 만들고 사용하기 + +파이썬 없이도, **셸 (터미널)** 에서 환경 변수를 **생성** 하고 사용할 수 있습니다. + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" + +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 파이썬에서 환경 변수 읽기 + +파이썬 **바깥**인 터미널에서(다른 도구로도 가능) 환경 변수를 생성도 할 수도 있고, 이를 **파이썬에서 읽을 수 있습니다.** + +예를 들어 다음과 같은 `main.py` 파일이 있다고 합시다: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip | 팁 + +`os.getenv()` 의 두 번째 인자는 반환할 기본값입니다. + +여기서는 `"World"`를 넣었기에 기본값으로써 사용됩니다. 넣지 않으면 `None` 이 기본값으로 사용됩니다. + +/// + +그러면 해당 파이썬 프로그램을 다음과 같이 호출할 수 있습니다: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ $Env:MY_NAME = "Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +환경변수는 코드 바깥에서 설정될 수 있지만, 코드에서 읽을 수 있고, 나머지 파일과 함께 저장(`git`에 커밋)할 필요가 없으므로, 구성이나 **설정** 에 사용하는 것이 일반적입니다. + +**특정 프로그램 호출**에 대해서만 사용할 수 있는 환경 변수를 만들 수도 있습니다. 해당 프로그램에서만 사용할 수 있고, 해당 프로그램이 실행되는 동안만 사용할 수 있습니다. + +그렇게 하려면 프로그램 바로 앞, 같은 줄에 환경 변수를 만들어야 합니다: + +
+ +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
+ +/// tip | 팁 + +The Twelve-Factor App: Config 에서 좀 더 자세히 알아볼 수 있습니다. + +/// + +## 타입과 검증 + +이 환경변수들은 오직 **텍스트 문자열**로만 처리할 수 있습니다. 텍스트 문자열은 파이썬 외부에 있으며 다른 프로그램 및 나머지 시스템(Linux, Windows, macOS 등 다른 운영 체제)과 호환되어야 합니다. + +즉, 파이썬에서 환경 변수로부터 읽은 **모든 값**은 **`str`**이 되고, 다른 타입으로의 변환이나 검증은 코드에서 수행해야 합니다. + +**애플리케이션 설정**을 처리하기 위한 환경 변수 사용에 대한 자세한 내용은 [고급 사용자 가이드 - 설정 및 환경 변수](./advanced/settings.md){.internal-link target=\_blank} 에서 확인할 수 있습니다. + +## `PATH` 환경 변수 + +**`PATH`**라고 불리는, **특별한** 환경변수가 있습니다. 운영체제(Linux, Windows, macOS 등)에서 실행할 프로그램을 찾기위해 사용됩니다. + +변수 `PATH`의 값은 Linux와 macOS에서는 콜론 `:`, Windows에서는 세미콜론 `;`으로 구분된 디렉토리로 구성된 긴 문자열입니다. + +예를 들어, `PATH` 환경 변수는 다음과 같습니다: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +이는 시스템이 다음 디렉토리에서 프로그램을 찾아야 함을 의미합니다: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +이는 시스템이 다음 디렉토리에서 프로그램을 찾아야 함을 의미합니다: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +터미널에 **명령어**를 입력하면 운영 체제는 `PATH` 환경 변수에 나열된 **각 디렉토리**에서 프로그램을 **찾습니다.** + +예를 들어 터미널에 `python`을 입력하면 운영 체제는 해당 목록의 **첫 번째 디렉토리**에서 `python`이라는 프로그램을 찾습니다. + +찾으면 **사용합니다**. 그렇지 않으면 **다른 디렉토리**에서 계속 찾습니다. + +### 파이썬 설치와 `PATH` 업데이트 + +파이썬을 설치할 때, 아마 `PATH` 환경 변수를 업데이트 할 것이냐고 물어봤을 겁니다. + +//// tab | Linux, macOS + +파이썬을 설치하고 그것이 `/opt/custompython/bin` 디렉토리에 있다고 가정해 보겠습니다. + +`PATH` 환경 변수를 업데이트하도록 "예"라고 하면 설치 관리자가 `/opt/custompython/bin`을 `PATH` 환경 변수에 추가합니다. + +다음과 같이 보일 수 있습니다: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +이렇게 하면 터미널에 `python`을 입력할 때, 시스템이 `/opt/custompython/bin`(마지막 디렉토리)에서 파이썬 프로그램을 찾아 사용합니다. + +//// + +//// tab | Windows + +파이썬을 설치하고 그것이 `C:\opt\custompython\bin` 디렉토리에 있다고 가정해 보겠습니다. + +`PATH` 환경 변수를 업데이트하도록 "예"라고 하면 설치 관리자가 `C:\opt\custompython\bin`을 `PATH` 환경 변수에 추가합니다. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +이렇게 하면 터미널에 `python`을 입력할 때, 시스템이 `C:\opt\custompython\bin`(마지막 디렉토리)에서 파이썬 프로그램을 찾아 사용합니다. + +//// + +그래서, 다음과 같이 입력한다면: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +시스템은 `/opt/custompython/bin`에서 `python` 프로그램을 **찾아** 실행합니다. + +다음과 같이 입력하는 것과 거의 같습니다: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +시스템은 `C:\opt\custompython\bin\python`에서 `python` 프로그램을 **찾아** 실행합니다. + +다음과 같이 입력하는 것과 거의 같습니다: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +이 정보는 [가상 환경](virtual-environments.md){.internal-link target=\_blank} 에 대해 알아볼 때 유용할 것입니다. + +## 결론 + +이 문서를 읽고 **환경 변수**가 무엇이고 파이썬에서 어떻게 사용하는지 기본적으로 이해하셨을 겁니다. + +또한 환경 변수에 대한 위키피디아(한국어)에서 이에 대해 자세히 알아볼 수 있습니다. + +많은 경우에서, 환경 변수가 어떻게 유용하고 적용 가능한지 바로 명확하게 알 수는 없습니다. 하지만 개발할 때 다양한 시나리오에서 계속 나타나므로 이에 대해 아는 것이 좋습니다. + +예를 들어, 다음 섹션인 [가상 환경](virtual-environments.md)에서 이 정보가 필요합니다. diff --git a/docs/ko/docs/fastapi-cli.md b/docs/ko/docs/fastapi-cli.md new file mode 100644 index 000000000..3a976af36 --- /dev/null +++ b/docs/ko/docs/fastapi-cli.md @@ -0,0 +1,83 @@ +# FastAPI CLI + +**FastAPI CLI**는 FastAPI 애플리케이션을 실행하고, 프로젝트를 관리하는 등 다양한 작업을 수행할 수 있는 커맨드 라인 프로그램입니다. + +FastAPI를 설치할 때 (예: `pip install "fastapi[standard]"` 명령어를 사용할 경우), `fastapi-cli`라는 패키지가 포함됩니다. 이 패키지는 터미널에서 사용할 수 있는 `fastapi` 명령어를 제공합니다. + +개발용으로 FastAPI 애플리케이션을 실행하려면 다음과 같이 `fastapi dev` 명령어를 사용할 수 있습니다: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +`fastapi`라고 불리는 명령어 프로그램은 **FastAPI CLI**입니다. + +FastAPI CLI는 Python 프로그램의 경로(예: `main.py`)를 인수로 받아, `FastAPI` 인스턴스(일반적으로 `app`으로 명명)를 자동으로 감지하고 올바른 임포트 과정을 결정한 후 이를 실행합니다. + +프로덕션 환경에서는 `fastapi run` 명령어를 사용합니다. 🚀 + +내부적으로, **FastAPI CLI**는 고성능의, 프로덕션에 적합한, ASGI 서버인 Uvicorn을 사용합니다. 😎 + +## `fastapi dev` + +`fastapi dev` 명령을 실행하면 개발 모드가 시작됩니다. + +기본적으로 **자동 재시작(auto-reload)** 기능이 활성화되어, 코드에 변경이 생기면 서버를 자동으로 다시 시작합니다. 하지만 이 기능은 리소스를 많이 사용하며, 비활성화했을 때보다 안정성이 떨어질 수 있습니다. 따라서 개발 환경에서만 사용하는 것이 좋습니다. 또한, 서버는 컴퓨터가 자체적으로 통신할 수 있는 IP 주소(`localhost`)인 `127.0.0.1`에서 연결을 대기합니다. + +## `fastapi run` + +`fastapi run` 명령을 실행하면 기본적으로 프로덕션 모드로 FastAPI가 시작됩니다. + +기본적으로 **자동 재시작(auto-reload)** 기능이 비활성화되어 있습니다. 또한, 사용 가능한 모든 IP 주소인 `0.0.0.0`에서 연결을 대기하므로 해당 컴퓨터와 통신할 수 있는 모든 사람이 공개적으로 액세스할 수 있습니다. 이는 일반적으로 컨테이너와 같은 프로덕션 환경에서 실행하는 방법입니다. + +애플리케이션을 배포하는 방식에 따라 다르지만, 대부분 "종료 프록시(termination proxy)"를 활용해 HTTPS를 처리하는 것이 좋습니다. 배포 서비스 제공자가 이 작업을 대신 처리해줄 수도 있고, 직접 설정해야 할 수도 있습니다. + +/// tip + +자세한 내용은 [deployment documentation](deployment/index.md){.internal-link target=\_blank}에서 확인할 수 있습니다. + +/// diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md index 54479165e..5e880c298 100644 --- a/docs/ko/docs/features.md +++ b/docs/ko/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # 기능 ## FastAPI의 기능 @@ -68,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! 정보 - `**second_user_data`가 뜻하는 것: +/// info | 정보 + +`**second_user_data`가 뜻하는 것: + +`second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")` - `second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")` +/// ### 편집기 지원 diff --git a/docs/ko/docs/help-fastapi.md b/docs/ko/docs/help-fastapi.md new file mode 100644 index 000000000..932952b4a --- /dev/null +++ b/docs/ko/docs/help-fastapi.md @@ -0,0 +1,162 @@ +* # FastAPI 지원 - 도움말 받기 + + **FastAPI** 가 마음에 드시나요? + + FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요? + + 혹은 **FastAPI** 에 대해 도움이 필요하신가요? + + 아주 간단하게 응원할 수 있습니다 (몇 번의 클릭만으로). + + 또한 도움을 받을 수 있는 방법도 몇 가지 있습니다. + + ## 뉴스레터 구독 + + [**FastAPI와 친구** 뉴스레터](https://github.com/fastapi/fastapi/blob/master/newsletter)를 구독하여 최신 정보를 유지할 수 있습니다{.internal-link target=_blank}: + + - FastAPI 와 그 친구들에 대한 뉴스 🚀 + - 가이드 📝 + - 특징 ✨ + - 획기적인 변화 🚨 + - 팁과 요령 ✅ + + ## 트위터에서 FastAPI 팔로우하기 + + [Follow @fastapi on **Twitter**](https://twitter.com/fastapi) 를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦 + + ## Star **FastAPI** in GitHub + + GitHub에서 FastAPI에 "star"를 붙일 수 있습니다(오른쪽 상단의 star 버튼을 클릭): https://github.com/fastapi/fastapi. ⭐️ + + 스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다. + + ## GitHub 저장소에서 릴리즈 확인 + + GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 + + 여기서 "Releases only"을 선택할 수 있습니다. + + 이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다. + + ## 개발자와의 연결 + + 개발자인 [me (Sebastián Ramírez / `tiangolo`)](https://tiangolo.com/) 와 연락을 취할 수 있습니다. + + 여러분은 할 수 있습니다: + + - [**GitHub**에서 팔로우하기](https://github.com/tiangolo). + - 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오. + - 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오. + + - [**Twitter**에서 팔로우하기](https://twitter.com/tiangolo). + - FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다). + - 발표 또는 새로운 툴 출시할 때 들으십시오. + - [follow @fastapi on Twitter](https://twitter.com/fastapi) (별도 계정에서) 할 수 있습니다. + + - [**Linkedin**에서의 연결](https://www.linkedin.com/in/tiangolo/). + - 새로운 툴의 발표나 릴리스를 들을 수 있습니다 (단, Twitter를 더 자주 사용합니다 🤷‍♂). + + - [**Dev.to**](https://dev.to/tiangolo) 또는 [**Medium**](https://medium.com/@tiangolo)에서 제가 작성한 내용을 읽어 보십시오(또는 팔로우). + - 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오. + - 새로운 기사를 읽기 위해 팔로우 하십시오. + + ## **FastAPI**에 대한 트윗 + + [**FastAPI**에 대해 트윗](https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi) 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉 + + **FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다. + + ## FastAPI에 투표하기 + + - [Slant에서 **FastAPI** 에 대해 투표하십시오](https://www.slant.co/options/34241/~fastapi-review). + - [AlternativeTo**FastAPI** 에 대해 투표하십시오](https://alternativeto.net/software/fastapi/). + + ## GitHub의 이슈로 다른사람 돕기 + + [존재하는 이슈](https://github.com/fastapi/fastapi/issues)를 확인하고 그것을 시도하고 도와줄 수 있습니다. 대부분의 경우 이미 답을 알고 있는 질문입니다. 🤓 + + 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 가 될 수 있습니다{.internal-link target=_blank}. 🎉 + + ## GitHub 저장소 보기 + + GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 + + "Releases only" 대신 "Watching"을 선택하면 다른 사용자가 새로운 issue를 생성할 때 알림이 수신됩니다. + + 그런 다음 이런 issues를 해결 할 수 있도록 도움을 줄 수 있습니다. + + ## 이슈 생성하기 + + GitHub 저장소에 [새로운 이슈 생성](https://github.com/fastapi/fastapi/issues/new/choose) 을 할 수 있습니다, 예를들면 다음과 같습니다: + + - **질문**을 하거나 **문제**에 대해 질문합니다. + - 새로운 **기능**을 제안 합니다. + + **참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉 + + ## Pull Request를 만드십시오 + + Pull Requests를 이용하여 소스코드에 [컨트리뷰트](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md){.internal-link target=_blank} 할 수 있습니다. 예를 들면 다음과 같습니다: + + - 문서에서 찾은 오타를 수정할 때. + + - FastAPI를 [편집하여](https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml) 작성했거나 찾은 문서, 비디오 또는 팟캐스트를 공유할 때. + + - 해당 섹션의 시작 부분에 링크를 추가했는지 확인하십시오. + + - 당신의 언어로 [문서 번역하는데](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md#translations){.internal-link target=_blank} 기여할 때. + + - 또한 다른 사용자가 만든 번역을 검토하는데 도움을 줄 수도 있습니다. + + - 새로운 문서의 섹션을 제안할 때. + + - 기존 문제/버그를 수정할 때. + + - 새로운 feature를 추가할 때. + + ## 채팅에 참여하십시오 + + 👥 [디스코드 채팅 서버](https://discord.gg/VQjSZaeJmf) 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요. + + /// tip + + 질문이 있는 경우, [GitHub 이슈 ](https://github.com/fastapi/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} . + + /// + + ``` + 다른 일반적인 대화에서만 채팅을 사용하십시오. + ``` + + 기존 [지터 채팅](https://gitter.im/fastapi/fastapi) 이 있지만 채널과 고급기능이 없어서 대화를 하기가 조금 어렵기 때문에 지금은 디스코드가 권장되는 시스템입니다. + + ### 질문을 위해 채팅을 사용하지 마십시오 + + 채팅은 더 많은 "자유로운 대화"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다. + + GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅 + + 채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts)가 되는 것으로 간주되므로{.internal-link target=_blank} , GitHub 이슈에서 더 많은 관심을 받을 것입니다. + + 반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄 + + ## 개발자 스폰서가 되십시오 + + [GitHub 스폰서](https://github.com/sponsors/tiangolo) 를 통해 개발자를 경제적으로 지원할 수 있습니다. + + 감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄 + + 또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉 + + ## FastAPI를 강화하는 도구의 스폰서가 되십시오 + + 문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다. + + 다음의 스폰서가 될 수 있습니다 + + - [Samuel Colvin (Pydantic)](https://github.com/sponsors/samuelcolvin) + - [Encode (Starlette, Uvicorn)](https://github.com/sponsors/encode) + + ------ + + 감사합니다! 🚀 diff --git a/docs/ko/docs/help/index.md b/docs/ko/docs/help/index.md deleted file mode 100644 index fc023071a..000000000 --- a/docs/ko/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# 도움 - -도움을 주고 받고, 기여하고, 참여합니다. 🤝 diff --git a/docs/ko/docs/history-design-future.md b/docs/ko/docs/history-design-future.md new file mode 100644 index 000000000..6680a46e7 --- /dev/null +++ b/docs/ko/docs/history-design-future.md @@ -0,0 +1,81 @@ +# 역사, 디자인 그리고 미래 + +어느 날, [한 FastAPI 사용자](https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920)가 이렇게 물었습니다: + +> 이 프로젝트의 역사를 알려 주실 수 있나요? 몇 주 만에 멋진 결과를 낸 것 같아요. [...] + +여기서 그 역사에 대해 간단히 설명하겠습니다. + +--- + +## 대안 + +저는 여러 해 동안 머신러닝, 분산 시스템, 비동기 작업, NoSQL 데이터베이스 같은 복잡한 요구사항을 가진 API를 개발하며 여러 팀을 이끌어 왔습니다. + +이 과정에서 많은 대안을 조사하고, 테스트하며, 사용해야 했습니다. **FastAPI**의 역사는 그 이전에 나왔던 여러 도구의 역사와 밀접하게 연관되어 있습니다. + +[대안](alternatives.md){.internal-link target=_blank} 섹션에서 언급된 것처럼: + +> **FastAPI**는 이전에 나왔던 많은 도구들의 노력 없이는 존재하지 않았을 것입니다. +> +> 이전에 개발된 여러 도구들이 이 프로젝트에 영감을 주었습니다. +> +> 저는 오랫동안 새로운 프레임워크를 만드는 것을 피하고자 했습니다. 처음에는 **FastAPI**가 제공하는 기능들을 다양한 프레임워크와 플러그인, 도구들을 조합해 해결하려 했습니다. +> +> 하지만 결국에는 이 모든 기능을 통합하는 도구가 필요해졌습니다. 이전 도구들로부터 최고의 아이디어들을 모으고, 이를 최적의 방식으로 조합해야만 했습니다. 이는 :term:Python 3.6+ 타입 힌트 와 같은, 이전에는 사용할 수 없었던 언어 기능이 가능했기 때문입니다. + +--- + +## 조사 + +여러 대안을 사용해 보며 다양한 도구에서 배운 점들을 모아 저와 개발팀에게 가장 적합한 방식을 찾았습니다. + +예를 들어, 표준 :term:Python 타입 힌트 에 기반하는 것이 이상적이라는 점이 명확했습니다. + +또한, 이미 존재하는 표준을 활용하는 것이 가장 좋은 접근법이라 판단했습니다. + +그래서 **FastAPI**의 코드를 작성하기 전에 몇 달 동안 OpenAPI, JSON Schema, OAuth2 명세를 연구하며 이들의 관계와 겹치는 부분, 차이점을 이해했습니다. + +--- + +## 디자인 + +그 후, **FastAPI** 사용자가 될 개발자로서 사용하고 싶은 개발자 "API"를 디자인했습니다. + +[Python Developer Survey](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)에 따르면 약 80%의 Python 개발자가 PyCharm, VS Code, Jedi 기반 편집기 등에서 개발합니다. 이 과정에서 여러 아이디어를 테스트했습니다. + +대부분의 다른 편집기도 유사하게 동작하기 때문에, **FastAPI**의 이점은 거의 모든 편집기에서 누릴 수 있습니다. + +이 과정을 통해 코드 중복을 최소화하고, 모든 곳에서 자동 완성, 타입 검사, 에러 확인 기능이 제공되는 최적의 방식을 찾아냈습니다. + +이 모든 것은 개발자들에게 최고의 개발 경험을 제공하기 위해 설계되었습니다. + +--- + +## 필요조건 + +여러 대안을 테스트한 후, [Pydantic](https://docs.pydantic.dev/)을 사용하기로 결정했습니다. + +이후 저는 **Pydantic**이 JSON Schema와 완벽히 호환되도록 개선하고, 다양한 제약 조건 선언을 지원하며, 여러 편집기에서의 자동 완성과 타입 검사 기능을 향상하기 위해 기여했습니다. + +또한, 또 다른 주요 필요조건이었던 [Starlette](https://www.starlette.io/)에도 기여했습니다. + +--- + +## 개발 + +**FastAPI**를 개발하기 시작할 즈음에는 대부분의 준비가 이미 완료된 상태였습니다. 설계가 정의되었고, 필요조건과 도구가 준비되었으며, 표준과 명세에 대한 지식도 충분했습니다. + +--- + +## 미래 + +현시점에서 **FastAPI**가 많은 사람들에게 유용하다는 것이 명백해졌습니다. + +여러 용도에 더 적합한 도구로서 기존 대안보다 선호되고 있습니다. +이미 많은 개발자와 팀들이 **FastAPI**에 의존해 프로젝트를 진행 중입니다 (저와 제 팀도 마찬가지입니다). + +하지만 여전히 개선해야 할 점과 추가할 기능들이 많이 남아 있습니다. + +**FastAPI**는 밝은 미래로 나아가고 있습니다. +그리고 [여러분의 도움](help-fastapi.md){.internal-link target=_blank}은 큰 힘이 됩니다. diff --git a/docs/ko/docs/how-to/conditional-openapi.md b/docs/ko/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..79c7f0dd2 --- /dev/null +++ b/docs/ko/docs/how-to/conditional-openapi.md @@ -0,0 +1,61 @@ +# 조건부적인 OpenAPI + +필요한 경우, 설정 및 환경 변수를 사용하여 환경에 따라 조건부로 OpenAPI를 구성하고 완전히 비활성화할 수도 있습니다. + +## 보안, API 및 docs에 대해서 + +프로덕션에서, 문서화된 사용자 인터페이스(UI)를 숨기는 것이 API를 보호하는 방법이 *되어서는 안 됩니다*. + +이는 API에 추가적인 보안을 제공하지 않으며, *경로 작업*은 여전히 동일한 위치에서 사용 할 수 있습니다. + +코드에 보안 결함이 있다면, 그 결함은 여전히 존재할 것입니다. + +문서를 숨기는 것은 API와 상호작용하는 방법을 이해하기 어렵게 만들며, 프로덕션에서 디버깅을 더 어렵게 만들 수 있습니다. 이는 단순히 '모호성에 의한 보안'의 한 형태로 간주될 수 있습니다. + +API를 보호하고 싶다면, 예를 들어 다음과 같은 더 나은 방법들이 있습니다: + +* 요청 본문과 응답에 대해 잘 정의된 Pydantic 모델을 사용하도록 하세요. + +* 종속성을 사용하여 필요한 권한과 역할을 구성하세요. + +* 평문 비밀번호를 절대 저장하지 말고, 오직 암호화된 비밀번호만 저장하세요. + +* Passlib과 JWT 토큰과 같은 잘 알려진 암호화 도구들을 구현하고 사용하세요. + +* 필요한 곳에 OAuth2 범위를 사용하여 더 세분화된 권한 제어를 추가하세요. + +* 등등.... + +그럼에도 불구하고, 특정 환경(예: 프로덕션)에서 또는 환경 변수의 설정에 따라 API 문서를 비활성화해야 하는 매우 특정한 사용 사례가 있을 수 있습니다. + +## 설정 및 환경변수의 조건부 OpenAPI + +동일한 Pydantic 설정을 사용하여 생성된 OpenAPI 및 문서 UI를 쉽게 구성할 수 있습니다. + +예를 들어: + +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} + +여기서 `openapi_url` 설정을 기본값인 `"/openapi.json"`으로 선언합니다. + +그런 뒤, 우리는 `FastAPI` 앱을 만들 때 그것을 사용합니다. + +환경 변수 `OPENAPI_URL`을 빈 문자열로 설정하여 OpenAPI(문서 UI 포함)를 비활성화할 수도 있습니다. 예를 들어: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +그리고 `/openapi.json`, `/docs` 또는 `/redoc`의 URL로 이동하면 `404 Not Found`라는 오류가 다음과 같이 표시됩니다: + +```JSON +{ + "detail": "Not Found" +} +``` diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index eeadc0363..8b00d90bc 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ FastAPI 프레임워크, 고성능, 간편한 학습, 빠른 코드 작성, 준비된 프로덕션

- - Test + + Test - - Coverage + + Coverage Package version @@ -20,15 +26,15 @@ **문서**: https://fastapi.tiangolo.com -**소스 코드**: https://github.com/tiangolo/fastapi +**소스 코드**: https://github.com/fastapi/fastapi --- -FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.8+의 API를 빌드하기 위한 웹 프레임워크입니다. +FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python의 API를 빌드하기 위한 웹 프레임워크입니다. 주요 특징으로: -* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#performance). +* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#_11). * **빠른 코드 작성**: 약 200%에서 300%까지 기능 개발 속도 증가. * * **적은 버그**: 사람(개발자)에 의한 에러 약 40% 감소. * @@ -61,7 +67,7 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트 "_[...] 저는 요즘 **FastAPI**를 많이 사용하고 있습니다. [...] 사실 우리 팀의 **마이크로소프트 ML 서비스** 전부를 바꿀 계획입니다. 그중 일부는 핵심 **Windows**와 몇몇의 **Office** 제품들이 통합되고 있습니다._" -

Kabir Khan - 마이크로소프트 (ref)
+
Kabir Khan - 마이크로소프트 (ref)
--- @@ -107,8 +113,6 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트 ## 요구사항 -Python 3.8+ - FastAPI는 거인들의 어깨 위에 서 있습니다: * 웹 부분을 위한 Starlette. @@ -126,7 +130,7 @@ $ pip install fastapi -프로덕션을 위해 Uvicorn 또는 Hypercorn과 같은 ASGI 서버도 필요할 겁니다. +프로덕션을 위해 Uvicorn 또는 Hypercorn과 같은 ASGI 서버도 필요할 겁니다.
@@ -323,7 +327,7 @@ def update_item(item_id: int, item: Item): 새로운 문법, 특정 라이브러리의 메소드나 클래스 등을 배울 필요가 없습니다. -그저 표준 **Python 3.8+** 입니다. +그저 표준 **Python** 입니다. 예를 들어, `int`에 대해선: @@ -437,7 +441,7 @@ item: Item Pydantic이 사용하는: -* email_validator - 이메일 유효성 검사. +* email-validator - 이메일 유효성 검사. Starlette이 사용하는: @@ -447,12 +451,12 @@ Starlette이 사용하는: * itsdangerous - `SessionMiddleware` 지원을 위해 필요. * pyyaml - Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요 없을 것입니다). * graphene - `GraphQLApp` 지원을 위해 필요. -* ujson - `UJSONResponse`를 사용하려면 필요. FastAPI / Starlette이 사용하는: * uvicorn - 애플리케이션을 로드하고 제공하는 서버. * orjson - `ORJSONResponse`을 사용하려면 필요. +* ujson - `UJSONResponse`를 사용하려면 필요. `pip install fastapi[all]`를 통해 이 모두를 설치 할 수 있습니다. diff --git a/docs/ko/docs/project-generation.md b/docs/ko/docs/project-generation.md new file mode 100644 index 000000000..dd11fca70 --- /dev/null +++ b/docs/ko/docs/project-generation.md @@ -0,0 +1,28 @@ +# Full Stack FastAPI 템플릿 + +템플릿은 일반적으로 특정 설정과 함께 제공되지만, 유연하고 커스터마이징이 가능하게 디자인 되었습니다. 이 특성들은 여러분이 프로젝트의 요구사항에 맞춰 수정, 적용을 할 수 있게 해주고, 템플릿이 완벽한 시작점이 되게 해줍니다. 🏁 + +많은 초기 설정, 보안, 데이터베이스 및 일부 API 엔드포인트가 이미 준비되어 있으므로, 여러분은 이 템플릿을 (프로젝트를) 시작하는 데 사용할 수 있습니다. + +GitHub 저장소: Full Stack FastAPI 템플릿 + +## Full Stack FastAPI 템플릿 - 기술 스택과 기능들 + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com): Python 백엔드 API. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com): Python SQL 데이터 상호작용을 위한 (ORM). + - 🔍 [Pydantic](https://docs.pydantic.dev): FastAPI에 의해 사용되는, 데이터 검증과 설정관리. + - 💾 [PostgreSQL](https://www.postgresql.org): SQL 데이터베이스. +- 🚀 [React](https://react.dev): 프론트엔드. + - 💃 TypeScript, hooks, [Vite](https://vitejs.dev) 및 기타 현대적인 프론트엔드 스택을 사용. + - 🎨 [Chakra UI](https://chakra-ui.com): 프론트엔드 컴포넌트. + - 🤖 자동으로 생성된 프론트엔드 클라이언트. + - 🧪 E2E 테스트를 위한 [Playwright](https://playwright.dev). + - 🦇 다크 모드 지원. +- 🐋 [Docker Compose](https://www.docker.com): 개발 환경과 프로덕션(운영). +- 🔒 기본으로 지원되는 안전한 비밀번호 해싱. +- 🔑 JWT 토큰 인증. +- 📫 이메일 기반 비밀번호 복구. +- ✅ [Pytest]를 이용한 테스트(https://pytest.org). +- 📞 [Traefik](https://traefik.io): 리버스 프록시 / 로드 밸런서. +- 🚢 Docker Compose를 이용한 배포 지침: 자동 HTTPS 인증서를 처리하기 위한 프론트엔드 Traefik 프록시 설정 방법을 포함. +- 🏭 GitHub Actions를 기반으로 CI (지속적인 통합) 및 CD (지속적인 배포). diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md index 267ce6c7e..7cc98ba76 100644 --- a/docs/ko/docs/python-types.md +++ b/docs/ko/docs/python-types.md @@ -12,15 +12,18 @@ 비록 **FastAPI**를 쓰지 않는다고 하더라도, 조금이라도 알아두면 도움이 될 것입니다. -!!! note "참고" - 파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요. +/// note | 참고 + +파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요. + +/// ## 동기 부여 간단한 예제부터 시작해봅시다: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` 이 프로그램을 실행한 결과값: @@ -36,7 +39,7 @@ John Doe * 두 단어를 중간에 공백을 두고 연결합니다. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### 코드 수정 @@ -80,7 +83,7 @@ John Doe 이게 "타입 힌트"입니다: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` 타입힌트는 다음과 같이 기본 값을 선언하는 것과는 다릅니다: @@ -110,7 +113,7 @@ John Doe 아래 함수를 보면, 이미 타입 힌트가 적용되어 있는 걸 볼 수 있습니다: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` 편집기가 변수의 타입을 알고 있기 때문에, 자동완성 뿐 아니라 에러도 확인할 수 있습니다: @@ -120,7 +123,7 @@ John Doe 이제 고쳐야하는 걸 알기 때문에, `age`를 `str(age)`과 같이 문자열로 바꾸게 됩니다: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 타입 선언 @@ -141,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 타입 매개변수를 활용한 Generic(제네릭) 타입 @@ -159,7 +162,7 @@ John Doe `typing`에서 `List`(대문자 `L`)를 import 합니다. ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 콜론(`:`) 문법을 이용하여 변수를 선언합니다. @@ -169,13 +172,16 @@ John Doe 이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다. ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "팁" - 대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다. +/// tip | 팁 + +대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다. + +이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다. - 이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다. +/// 이는 "`items`은 `list`인데, 배열에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다. @@ -194,7 +200,7 @@ John Doe `tuple`과 `set`도 동일하게 선언할 수 있습니다. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` 이 뜻은 아래와 같습니다: @@ -211,7 +217,7 @@ John Doe 두 번째 매개변수는 `dict`의 값(value)입니다. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` 이 뜻은 아래와 같습니다: @@ -225,7 +231,7 @@ John Doe `str`과 같이 타입을 선언할 때 `Optional`을 쓸 수도 있는데, "선택적(Optional)"이기때문에 `None`도 될 수 있습니다: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` `Optional[str]`을 `str` 대신 쓰게 되면, 특정 값이 실제로는 `None`이 될 수도 있는데 항상 `str`이라고 가정하는 상황에서 에디터가 에러를 찾게 도와줄 수 있습니다. @@ -250,13 +256,13 @@ John Doe 이름(name)을 가진 `Person` 클래스가 있다고 해봅시다. ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 그렇게 하면 변수를 `Person`이라고 선언할 수 있게 됩니다. ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 그리고 역시나 모든 에디터 도움을 받게 되겠죠. @@ -278,12 +284,14 @@ John Doe Pydantic 공식 문서 예시: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` -!!! info "정보" - Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요. +/// info | 정보 +Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요. + +/// **FastAPI**는 모두 Pydantic을 기반으로 되어 있습니다. @@ -311,5 +319,8 @@ Pydantic 공식 문서 예시: 가장 중요한 건, 표준 파이썬 타입을 한 곳에서(클래스를 더하거나, 데코레이터 사용하는 대신) 사용함으로써 **FastAPI**가 당신을 위해 많은 일을 해준다는 사실이죠. -!!! info "정보" - 만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다. +/// info | 정보 + +만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다. + +/// diff --git a/docs/ko/docs/security/index.md b/docs/ko/docs/security/index.md new file mode 100644 index 000000000..5a6c733f0 --- /dev/null +++ b/docs/ko/docs/security/index.md @@ -0,0 +1,19 @@ +# 고급 보안 + +## 추가 기능 + +[자습서 - 사용자 가이드: 보안](../../tutorial/security/index.md){.internal-link target=_blank} 문서에서 다룬 내용 외에도 보안 처리를 위한 몇 가지 추가 기능이 있습니다. + +/// tip + +다음 섹션은 **반드시 "고급"** 기능은 아닙니다. + +그리고 여러분의 사용 사례에 따라, 적합한 해결책이 그 중 하나에 있을 가능성이 있습니다. + +/// + +## 먼저 자습서 읽기 + +다음 섹션은 이미 [자습서 - 사용자 가이드: 보안](../../tutorial/security/index.md){.internal-link target=_blank} 문서를 읽었다고 가정합니다. + +이 섹션들은 모두 동일한 개념을 바탕으로 하며, 추가 기능을 제공합니다. diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md index ee83d6570..376c52524 100644 --- a/docs/ko/docs/tutorial/background-tasks.md +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 먼저 아래와 같이 `BackgroundTasks`를 임포트하고, `BackgroundTasks`를 _경로 작동 함수_ 에서 매개변수로 가져오고 정의합니다. ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** 는 `BackgroundTasks` 개체를 생성하고, 매개 변수로 전달합니다. @@ -34,7 +34,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 그리고 이 작업은 `async`와 `await`를 사용하지 않으므로 일반 `def` 함수로 선언합니다. ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## 백그라운드 작업 추가 @@ -42,7 +42,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _백그라운드 작업_ 개체에 전달합니다. ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` 함수는 다음과 같은 인자를 받습니다 : @@ -57,17 +57,21 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _ **FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다. -=== "Python 3.6 and above" +//// tab | Python 3.6 and above - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +```Python hl_lines="13 15 22 25" +{!> ../../docs_src/background_tasks/tutorial002.py!} +``` + +//// -=== "Python 3.10 and above" +//// tab | Python 3.10 and above + +```Python hl_lines="11 13 20 23" +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} +``` - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// 이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다. diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md index fc7209726..f6532f369 100644 --- a/docs/ko/docs/tutorial/body-fields.md +++ b/docs/ko/docs/tutorial/body-fields.md @@ -6,98 +6,139 @@ 먼저 이를 임포트해야 합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ - !!! 팁 - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | 팁 - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -!!! warning "경고" - `Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요. +/// + +```Python hl_lines="2" +{!> ../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | 팁 + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | 경고 + +`Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요. + +/// ## 모델 어트리뷰트 선언 그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +```Python hl_lines="12-15" +{!> ../../docs_src/body_fields/tutorial001_an.py!} +``` -=== "Python 3.10+ Annotated가 없는 경우" +//// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// tab | Python 3.10+ Annotated가 없는 경우 - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// tip | 팁 -=== "Python 3.8+ Annotated가 없는 경우" +가능하다면 `Annotated`가 달린 버전을 권장합니다. - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="9-12" +{!> ../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | 팁 + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다. -!!! note "기술적 세부사항" - 실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다. +/// note | 기술적 세부사항 - 그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다. +실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다. - `Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다. +그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다. - `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요. +`Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다. -!!! tip "팁" - 주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다. + `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요. + +/// + +/// tip | 팁 + +주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다. + +/// ## 별도 정보 추가 @@ -105,9 +146,12 @@ 여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다. -!!! warning "경고" - 별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다. - 이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다. +/// warning | 경고 + +별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다. +이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다. + +/// ## 요약 diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md index 2cf5df7f3..569ff016e 100644 --- a/docs/ko/docs/tutorial/body-multiple-params.md +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -11,11 +11,14 @@ 또한, 기본 값을 `None`으로 설정해 본문 매개변수를 선택사항으로 선언할 수 있습니다. ```Python hl_lines="19-21" -{!../../../docs_src/body_multiple_params/tutorial001.py!} +{!../../docs_src/body_multiple_params/tutorial001.py!} ``` -!!! note "참고" - 이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다. +/// note | 참고 + +이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다. + +/// ## 다중 본문 매개변수 @@ -33,7 +36,7 @@ 하지만, 다중 본문 매개변수 역시 선언할 수 있습니다. 예. `item`과 `user`: ```Python hl_lines="22" -{!../../../docs_src/body_multiple_params/tutorial002.py!} +{!../../docs_src/body_multiple_params/tutorial002.py!} ``` 이 경우에, **FastAPI**는 이 함수 안에 한 개 이상의 본문 매개변수(Pydantic 모델인 두 매개변수)가 있다고 알 것입니다. @@ -55,8 +58,11 @@ } ``` -!!! note "참고" - 이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다. +/// note | 참고 + +이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다. + +/// FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 특별한 내용으로 받도록 할 것입니다. @@ -74,7 +80,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 ```Python hl_lines="23" -{!../../../docs_src/body_multiple_params/tutorial003.py!} +{!../../docs_src/body_multiple_params/tutorial003.py!} ``` 이 경우에는 **FastAPI**는 본문을 이와 같이 예측할 것입니다: @@ -105,7 +111,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요가 없고, 아래처럼 할 수 있습니다: ```Python hl_lines="27" -{!../../../docs_src/body_multiple_params/tutorial004.py!} +{!../../docs_src/body_multiple_params/tutorial004.py!} ``` 이렇게: @@ -114,8 +120,11 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 q: Optional[str] = None ``` -!!! info "정보" - `Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다. +/// info | 정보 + +`Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다. + +/// ## 단일 본문 매개변수 삽입하기 @@ -126,7 +135,7 @@ Pydantic 모델 `Item`의 `item`을 본문 매개변수로 오직 한개만 갖 하지만, 만약 모델 내용에 `item `키를 가진 JSON으로 예측하길 원한다면, 추가적인 본문 매개변수를 선언한 것처럼 `Body`의 특별한 매개변수인 `embed`를 사용할 수 있습니다: ```Python hl_lines="17" -{!../../../docs_src/body_multiple_params/tutorial005.py!} +{!../../docs_src/body_multiple_params/tutorial005.py!} ``` 아래 처럼: diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index edf1a5f77..e9b1d2e18 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -6,7 +6,7 @@ 어트리뷰트를 서브타입으로 정의할 수 있습니다. 예를 들어 파이썬 `list`는: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial001.py!} +{!../../docs_src/body_nested_models/tutorial001.py!} ``` 이는 `tags`를 항목 리스트로 만듭니다. 각 항목의 타입을 선언하지 않더라도요. @@ -20,7 +20,7 @@ 먼저, 파이썬 표준 `typing` 모듈에서 `List`를 임포트합니다: ```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ### 타입 매개변수로 `List` 선언 @@ -43,19 +43,19 @@ my_list: List[str] 마찬가지로 예제에서 `tags`를 구체적으로 "문자열의 리스트"로 만들 수 있습니다: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ## 집합 타입 -그런데 생각해보니 태그는 반복되면 안 돼고, 고유한(Unique) 문자열이어야 할 것 같습니다. +그런데 생각해보니 태그는 반복되면 안 되고, 고유한(Unique) 문자열이어야 할 것 같습니다. 그리고 파이썬은 집합을 위한 특별한 데이터 타입 `set`이 있습니다. 그렇다면 `Set`을 임포트 하고 `tags`를 `str`의 `set`으로 선언할 수 있습니다: ```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} +{!../../docs_src/body_nested_models/tutorial003.py!} ``` 덕분에 중복 데이터가 있는 요청을 수신하더라도 고유한 항목들의 집합으로 변환됩니다. @@ -79,7 +79,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어, `Image` 모델을 선언할 수 있습니다: ```Python hl_lines="9-11" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` ### 서브모듈을 타입으로 사용 @@ -87,7 +87,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 그리고 어트리뷰트의 타입으로 사용할 수 있습니다: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` 이는 **FastAPI**가 다음과 유사한 본문을 기대한다는 것을 의미합니다: @@ -122,7 +122,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어 `Image` 모델 안에 `url` 필드를 `str` 대신 Pydantic의 `HttpUrl`로 선언할 수 있습니다: ```Python hl_lines="4 10" -{!../../../docs_src/body_nested_models/tutorial005.py!} +{!../../docs_src/body_nested_models/tutorial005.py!} ``` 이 문자열이 유효한 URL인지 검사하고 JSON 스키마/OpenAPI로 문서화 됩니다. @@ -132,7 +132,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. `list`, `set` 등의 서브타입으로 Pydantic 모델을 사용할 수도 있습니다: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial006.py!} +{!../../docs_src/body_nested_models/tutorial006.py!} ``` 아래와 같은 JSON 본문으로 예상(변환, 검증, 문서화 등을)합니다: @@ -161,19 +161,25 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. } ``` -!!! info "정보" - `images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요. +/// info | 정보 + +`images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요. + +/// ## 깊게 중첩된 모델 단독으로 깊게 중첩된 모델을 정의할 수 있습니다: ```Python hl_lines="9 14 20 23 27" -{!../../../docs_src/body_nested_models/tutorial007.py!} +{!../../docs_src/body_nested_models/tutorial007.py!} ``` -!!! info "정보" - `Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요 +/// info | 정보 + +`Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요 + +/// ## 순수 리스트의 본문 @@ -186,7 +192,7 @@ images: List[Image] 이를 아래처럼: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial008.py!} +{!../../docs_src/body_nested_models/tutorial008.py!} ``` ## 어디서나 편집기 지원 @@ -218,17 +224,20 @@ Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러 이 경우, `float` 값을 가진 `int` 키가 있는 모든 `dict`를 받아들입니다: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial009.py!} +{!../../docs_src/body_nested_models/tutorial009.py!} ``` -!!! tip "팁" - JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요. +/// tip | 팁 + +JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요. + +하지만 Pydantic은 자동 데이터 변환이 있습니다. - 하지만 Pydantic은 자동 데이터 변환이 있습니다. +즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다. - 즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다. +그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다. - 그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 8b98284bb..9e614ef1c 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -8,28 +8,35 @@ **요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 Pydantic 모델을 사용합니다. -!!! 정보 - 데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. +/// info | 정보 - `GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다. +데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. - `GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다. +`GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다. + +`GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다. + +/// ## Pydantic의 `BaseModel` 임포트 먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../docs_src/body/tutorial001.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// ## 여러분의 데이터 모델 만들기 @@ -37,17 +44,21 @@ 모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="5-9" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="7-11" +{!> ../../docs_src/body/tutorial001.py!} +``` + +//// 쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다. @@ -75,17 +86,21 @@ 여러분의 *경로 작동*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../docs_src/body/tutorial001.py!} +``` + +//// ...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다. @@ -134,32 +149,39 @@ -!!! 팁 - 만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다. +/// tip | 팁 + +만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다. - 다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다: +다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다: - * 자동 완성 - * 타입 확인 - * 리팩토링 - * 검색 - * 점검 +* 자동 완성 +* 타입 확인 +* 리팩토링 +* 검색 +* 점검 + +/// ## 모델 사용하기 함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/body/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="21" +{!> ../../docs_src/body/tutorial002.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// ## 요청 본문 + 경로 매개변수 @@ -167,17 +189,21 @@ **FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="15-16" +{!> ../../docs_src/body/tutorial003_py310.py!} +``` - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +```Python hl_lines="17-18" +{!> ../../docs_src/body/tutorial003.py!} +``` + +//// ## 요청 본문 + 경로 + 쿼리 매개변수 @@ -185,17 +211,21 @@ **FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../docs_src/body/tutorial004_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +```Python hl_lines="18" +{!> ../../docs_src/body/tutorial004.py!} +``` + +//// 함수 매개변수는 다음을 따라서 인지하게 됩니다: @@ -203,11 +233,14 @@ * 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다. * 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다. -!!! 참고 - FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. +/// note | 참고 + +FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. + +`Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다. - `Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다. +/// ## Pydantic없이 -만약 Pydantic 모델을 사용하고 싶지 않다면, **Body** 매개변수를 사용할 수도 있습니다. [Body - 다중 매개변수: 본문에 있는 유일한 값](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank} 문서를 확인하세요. +만약 Pydantic 모델을 사용하고 싶지 않다면, **Body** 매개변수를 사용할 수도 있습니다. [Body - 다중 매개변수: 본문에 있는 유일한 값](body-multiple-params.md#_2){.internal-link target=_blank} 문서를 확인하세요. diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md index d4f3d57a3..427539210 100644 --- a/docs/ko/docs/tutorial/cookie-params.md +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ 먼저 `Cookie`를 임포트합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | 팁 - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="1" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | 팁 + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## `Cookie` 매개변수 선언 @@ -48,49 +64,71 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ Annotated가 없는 경우 + +/// tip | 팁 + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ Annotated가 없는 경우 - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip | 팁 -=== "Python 3.8+" +가능하다면 `Annotated`가 달린 버전을 권장합니다. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ Annotated가 없는 경우" +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | 기술 세부사항 -=== "Python 3.8+ Annotated가 없는 경우" +`Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +`Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "기술 세부사항" - `Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. +/// info | 정보 - `Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요. +쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. -!!! info "정보" - 쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md index 39e9ea83f..0222e6258 100644 --- a/docs/ko/docs/tutorial/cors.md +++ b/docs/ko/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 특정한 HTTP 헤더 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 헤더. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` `CORSMiddleware` 에서 사용하는 기본 매개변수는 제한적이므로, 브라우저가 교차-도메인 상황에서 특정한 출처, 메소드, 헤더 등을 사용할 수 있도록 하려면 이들을 명시적으로 허용해야 합니다. @@ -78,7 +78,10 @@ CORS에 대한 더 많은 정보를 알고싶다면, Mozilla CORS 문서를 참고하기 바랍니다. -!!! note "기술적 세부 사항" - `from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다. +/// note | 기술적 세부 사항 - **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다. +`from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다. + +**FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다. + +/// diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md new file mode 100644 index 000000000..fcb68b565 --- /dev/null +++ b/docs/ko/docs/tutorial/debugging.md @@ -0,0 +1,115 @@ +# 디버깅 + +예를 들면 Visual Studio Code 또는 PyCharm을 사용하여 편집기에서 디버거를 연결할 수 있습니다. + +## `uvicorn` 호출 + +FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다 + +```Python hl_lines="1 15" +{!../../docs_src/debugging/tutorial001.py!} +``` + +### `__name__ == "__main__"` 에 대하여 + +`__name__ == "__main__"`의 주요 목적은 다음과 같이 파일이 호출될 때 실행되는 일부 코드를 갖는 것입니다. + +
+ +```console +$ python myapp.py +``` + +
+ +그러나 다음과 같이 다른 파일을 가져올 때는 호출되지 않습니다. + +```Python +from myapp import app +``` + +#### 추가 세부사항 + +파일 이름이 `myapp.py`라고 가정해 보겠습니다. + +다음과 같이 실행하면 + +
+ +```console +$ python myapp.py +``` + +
+ +Python에 의해 자동으로 생성된 파일의 내부 변수 `__name__`은 문자열 `"__main__"`을 값으로 갖게 됩니다. + +따라서 섹션 + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +이 실행됩니다. + +--- + +해당 모듈(파일)을 가져오면 이런 일이 발생하지 않습니다 + +그래서 다음과 같은 다른 파일 `importer.py`가 있는 경우: + +```Python +from myapp import app + +# Some more code +``` + +이 경우 `myapp.py` 내부의 자동 변수에는 값이 `"__main__"`인 변수 `__name__`이 없습니다. + +따라서 다음 행 + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +은 실행되지 않습니다. + +/// info | 정보 + +자세한 내용은 공식 Python 문서를 확인하세요 + +/// + +## 디버거로 코드 실행 + +코드에서 직접 Uvicorn 서버를 실행하고 있기 때문에 디버거에서 직접 Python 프로그램(FastAPI 애플리케이션)을 호출할 수 있습니다. + +--- + +예를 들어 Visual Studio Code에서 다음을 수행할 수 있습니다. + +* "Debug" 패널로 이동합니다. +* "Add configuration...". +* "Python"을 선택합니다. +* "`Python: Current File (Integrated Terminal)`" 옵션으로 디버거를 실행합니다. + +그런 다음 **FastAPI** 코드로 서버를 시작하고 중단점 등에서 중지합니다. + +다음과 같이 표시됩니다. + + + +--- + +Pycharm을 사용하는 경우 다음을 수행할 수 있습니다 + +* "Run" 메뉴를 엽니다 +* "Debug..." 옵션을 선택합니다. +* 그러면 상황에 맞는 메뉴가 나타납니다. +* 디버그할 파일을 선택합니다(이 경우 `main.py`). + +그런 다음 **FastAPI** 코드로 서버를 시작하고 중단점 등에서 중지합니다. + +다음과 같이 표시됩니다. + + diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index 38cdc2e1a..41e48aefc 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,21 @@ 이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="7" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다. @@ -77,45 +81,57 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다. -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="11-15" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="9-13" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// 클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` + +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// ...이전 `common_parameters`와 동일한 매개변수를 가집니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="6" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// 이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다 @@ -131,17 +147,21 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다. -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// **FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다. @@ -180,17 +200,21 @@ commons = Depends(CommonQueryParams) ..전체적인 코드는 아래와 같습니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial003.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial003_py310.py!} +``` + +//// 그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다. @@ -224,21 +248,28 @@ commons: CommonQueryParams = Depends() 아래에 같은 예제가 있습니다: -=== "파이썬 3.6 이상" +//// tab | 파이썬 3.6 이상 + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial004.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +//// -=== "파이썬 3.10 이상" +//// tab | 파이썬 3.10 이상 - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial004_py310.py!} +``` + +//// ...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다. -!!! tip "팁" - 만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다. +/// tip | 팁 + +만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다. + +이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다. - 이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다. +/// diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 92b2c7d1c..fab636b7f 100644 --- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,40 +14,55 @@ `Depends()`로 된 `list`이어야합니다: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 Annotated가 없는 경우" +```Python hl_lines="18" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 + +/// tip | 팁 + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// 이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다. -!!! tip "팁" - 일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다. +/// tip | 팁 + +일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다. - *경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다. +*경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다. - 또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다. +또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다. -!!! info "정보" - 이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다. +/// - 그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다. +/// info | 정보 + +이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다. + +그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다. + +/// ## 의존성 오류와 값 반환하기 @@ -57,51 +72,69 @@ (헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +```Python hl_lines="7 12" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="7 12" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 -=== "Python 3.8 Annotated가 없는 경우" +/// tip | 팁 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +가능하다면 `Annotated`가 달린 버전을 권장합니다. - ```Python hl_lines="6 11" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +/// + +```Python hl_lines="6 11" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### 오류 발생시키기 다음 의존성은 기존 의존성과 동일하게 예외를 `raise`를 일으킬 수 있습니다: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8 Annotated가 없는 경우 - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +/// tip | 팁 -=== "Python 3.8 Annotated가 없는 경우" +가능하다면 `Annotated`가 달린 버전을 권장합니다. - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// - ```Python hl_lines="8 13" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +```Python hl_lines="8 13" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// ### 값 반환하기 @@ -109,26 +142,35 @@ 그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 -=== "Python 3.8+" +/// tip | 팁 - ```Python hl_lines="10 15" - {!> ../../../docs_src/dependencies/tutorial006_an.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8 Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="9 14" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` - ```Python hl_lines="9 14" - {!> ../../../docs_src/dependencies/tutorial006.py!} - ``` +//// ## *경로 작동* 모음에 대한 의존성 diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md index 930f6e678..0ad8b55fd 100644 --- a/docs/ko/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,35 @@ 그런 경우에, 애플리케이션의 모든 *경로 작동*에 적용될 것입니다: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 Annotated가 없는 경우" +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial012_an.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.py!} - ``` +//// tab | Python 3.8 Annotated가 없는 경우 + +/// tip | 팁 + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="15" +{!> ../../docs_src/dependencies/tutorial012.py!} +``` + +//// 그리고 [*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}에 대한 아이디어는 여전히 적용되지만 여기에서는 앱에 있는 모든 *경로 작동*에 적용됩니다. diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md index c56dddae3..1aba6e787 100644 --- a/docs/ko/docs/tutorial/dependencies/index.md +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -31,41 +31,57 @@ *경로 작동 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9-12" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.10+ Annotated가 없는 경우 -=== "Python 3.10+ Annotated가 없는 경우" +/// tip | 팁 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +가능하다면 `Annotated`가 달린 버전을 권장합니다. - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// -=== "Python 3.8+ Annotated가 없는 경우" +```Python hl_lines="6-7" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +//// - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | 팁 + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="8-11" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// 이게 다입니다. @@ -85,90 +101,125 @@ 그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다. -!!! 정보 - FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. +/// info | 정보 + +FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. - 옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다. +옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다. - `Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank}를 확실하게 하세요. +`Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요. + +/// ### `Depends` 불러오기 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.10+ Annotated가 없는 경우 - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +/// tip | 팁 -=== "Python 3.8+" +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="1" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.8+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | 팁 - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8+ Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### "의존자"에 의존성 명시하기 *경로 작동 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 18" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="15 20" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="16 21" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ Annotated가 없는 경우" +//// tab | Python 3.10+ Annotated가 없는 경우 - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +/// tip | 팁 - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +가능하다면 `Annotated`가 달린 버전을 권장합니다. -=== "Python 3.8+ Annotated가 없는 경우" +/// - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. +```Python hl_lines="11 16" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ Annotated가 없는 경우 + +/// tip | 팁 + +가능하다면 `Annotated`가 달린 버전을 권장합니다. + +/// + +```Python hl_lines="15 20" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// 비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다. @@ -180,8 +231,11 @@ 그리고 그 함수는 *경로 작동 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다. -!!! tip "팁" - 여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다. +/// tip | 팁 + +여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다. + +/// 새로운 요청이 도착할 때마다, **FastAPI**는 다음을 처리합니다: @@ -202,10 +256,13 @@ common_parameters --> read_users 이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 작동*을 위해 이에 대한 호출을 처리합니다. -!!! check "확인" - 특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다. +/// check | 확인 + +특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다. + +단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다. - 단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다. +/// ## `Annotated`인 의존성 공유하기 @@ -219,28 +276,37 @@ commons: Annotated[dict, Depends(common_parameters)] 하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12 16 21" +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` + +//// - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14 18 23" +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` + +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15 19 24" +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +/// tip | 팁 -!!! tip "팁" - 이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다. +이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다. - 하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎 +하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎 + +/// 이 의존성은 계속해서 예상한대로 작동할 것이며, **제일 좋은 부분**은 **타입 정보가 보존된다는 것입니다**. 즉 여러분의 편집기가 **자동 완성**, **인라인 에러** 등을 계속해서 제공할 수 있다는 것입니다. `mypy`같은 다른 도구도 마찬가지입니다. @@ -256,8 +322,11 @@ commons: Annotated[dict, Depends(common_parameters)] 아무 문제 없습니다. **FastAPI**는 무엇을 할지 알고 있습니다. -!!! note "참고" - 잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다. +/// note | 참고 + +잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다. + +/// ## OpenAPI와 통합 diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md index 8b5fdb8b7..52277f258 100644 --- a/docs/ko/docs/tutorial/encoder.md +++ b/docs/ko/docs/tutorial/encoder.md @@ -21,7 +21,7 @@ JSON 호환 가능 데이터만 수신하는 `fake_db` 데이터베이스가 존 Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 반환합니다: ```Python hl_lines="5 22" -{!../../../docs_src/encoder/tutorial001.py!} +{!../../docs_src/encoder/tutorial001.py!} ``` 이 예시는 Pydantic 모델을 `dict`로, `datetime` 형식을 `str`로 변환합니다. @@ -30,5 +30,8 @@ Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 길이가 긴 문자열 형태의 JSON 형식(문자열)의 데이터가 들어있는 상황에서는 `str`로 반환하지 않습니다. JSON과 모두 호환되는 값과 하위 값이 있는 Python 표준 데이터 구조 (예: `dict`)를 반환합니다. -!!! note "참고" - 실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다. +/// note | 참고 + +실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다. + +/// diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md new file mode 100644 index 000000000..8baaa64fc --- /dev/null +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -0,0 +1,162 @@ +# 추가 데이터 자료형 + +지금까지 일반적인 데이터 자료형을 사용했습니다. 예를 들면 다음과 같습니다: + +* `int` +* `float` +* `str` +* `bool` + +하지만 더 복잡한 데이터 자료형 또한 사용할 수 있습니다. + +그리고 지금까지와 같은 기능들을 여전히 사용할 수 있습니다. + +* 훌륭한 편집기 지원. +* 들어오는 요청의 데이터 변환. +* 응답 데이터의 데이터 변환. +* 데이터 검증. +* 자동 어노테이션과 문서화. + +## 다른 데이터 자료형 + +아래의 추가적인 데이터 자료형을 사용할 수 있습니다: + +* `UUID`: + * 표준 "범용 고유 식별자"로, 많은 데이터베이스와 시스템에서 ID로 사용됩니다. + * 요청과 응답에서 `str`로 표현됩니다. +* `datetime.datetime`: + * 파이썬의 `datetime.datetime`. + * 요청과 응답에서 `2008-09-15T15:53:00+05:00`와 같은 ISO 8601 형식의 `str`로 표현됩니다. +* `datetime.date`: + * 파이썬의 `datetime.date`. + * 요청과 응답에서 `2008-09-15`와 같은 ISO 8601 형식의 `str`로 표현됩니다. +* `datetime.time`: + * 파이썬의 `datetime.time`. + * 요청과 응답에서 `14:23:55.003`와 같은 ISO 8601 형식의 `str`로 표현됩니다. +* `datetime.timedelta`: + * 파이썬의 `datetime.timedelta`. + * 요청과 응답에서 전체 초(seconds)의 `float`로 표현됩니다. + * Pydantic은 "ISO 8601 시차 인코딩"으로 표현하는 것 또한 허용합니다. 더 많은 정보는 이 문서에서 확인하십시오.. +* `frozenset`: + * 요청과 응답에서 `set`와 동일하게 취급됩니다: + * 요청 시, 리스트를 읽어 중복을 제거하고 `set`로 변환합니다. + * 응답 시, `set`는 `list`로 변환됩니다. + * 생성된 스키마는 (JSON 스키마의 `uniqueItems`를 이용해) `set`의 값이 고유함을 명시합니다. +* `bytes`: + * 표준 파이썬의 `bytes`. + * 요청과 응답에서 `str`로 취급됩니다. + * 생성된 스키마는 이것이 `binary` "형식"의 `str`임을 명시합니다. +* `Decimal`: + * 표준 파이썬의 `Decimal`. + * 요청과 응답에서 `float`와 동일하게 다뤄집니다. +* 여기에서 모든 유효한 pydantic 데이터 자료형을 확인할 수 있습니다: Pydantic 데이터 자료형. + +## 예시 + +위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다. + +//// tab | Python 3.10+ + +```Python hl_lines="1 3 12-16" +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="1 3 12-16" +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 3 13-17" +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// + +함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오: + +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="17-18" +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index e3b42bce7..4a689b74a 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ 가장 단순한 FastAPI 파일은 다음과 같이 보일 것입니다: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 위 코드를 `main.py`에 복사합니다. @@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note "참고" - `uvicorn main:app` 명령은 다음을 의미합니다: +/// note | 참고 - * `main`: 파일 `main.py` (파이썬 "모듈"). - * `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트. - * `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용. +`uvicorn main:app` 명령은 다음을 의미합니다: + +* `main`: 파일 `main.py` (파이썬 "모듈"). +* `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트. +* `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용. + +/// 출력되는 줄들 중에는 아래와 같은 내용이 있습니다: @@ -131,20 +134,23 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 1 단계: `FastAPI` 임포트 ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. -!!! note "기술 세부사항" - `FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. +/// note | 기술 세부사항 + +`FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. - `FastAPI`로 Starlette의 모든 기능을 사용할 수 있습니다. +`FastAPI`로 Starlette의 모든 기능을 사용할 수 있습니다. + +/// ### 2 단계: `FastAPI` "인스턴스" 생성 ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 여기에서 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다. @@ -166,7 +172,7 @@ $ uvicorn main:app --reload 아래처럼 앱을 만든다면: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` 이를 `main.py` 파일에 넣고, `uvicorn`을 아래처럼 호출해야 합니다: @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "정보" - "경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다. +/// info | 정보 + +"경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다. + +/// API를 설계할 때 "경로"는 "관심사"와 "리소스"를 분리하기 위한 주요한 방법입니다. @@ -242,7 +251,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 #### *경로 작동 데코레이터* 정의 ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")`은 **FastAPI**에게 바로 아래에 있는 함수가 다음으로 이동하는 요청을 처리한다는 것을 알려줍니다. @@ -250,16 +259,19 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * 경로 `/` * get 작동 사용 -!!! info "`@decorator` 정보" - 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. +/// info | `@decorator` 정보 - 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다. +이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. - "데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다. +마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다. - 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다. +"데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다. - 이것이 "**경로 작동 데코레이터**"입니다. +우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다. + +이것이 "**경로 작동 데코레이터**"입니다. + +/// 다른 작동도 사용할 수 있습니다: @@ -274,14 +286,17 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * `@app.patch()` * `@app.trace()` -!!! tip "팁" - 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다. +/// tip | 팁 + +각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다. - **FastAPI**는 특정 의미를 강제하지 않습니다. +**FastAPI**는 특정 의미를 강제하지 않습니다. - 여기서 정보는 지침서일뿐 강제사항이 아닙니다. +여기서 정보는 지침서일뿐 강제사항이 아닙니다. - 예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다. +예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다. + +/// ### 4 단계: **경로 작동 함수** 정의 @@ -292,7 +307,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 이것은 파이썬 함수입니다. @@ -306,16 +321,19 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa `async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "참고" - 차이점을 모르겠다면 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}을 확인하세요. +/// note | 참고 + +차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요. + +/// ### 5 단계: 콘텐츠 반환 ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다. diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md index 484554e97..972f52a33 100644 --- a/docs/ko/docs/tutorial/header-params.md +++ b/docs/ko/docs/tutorial/header-params.md @@ -7,7 +7,7 @@ 먼저 `Header`를 임포트합니다: ```Python hl_lines="3" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` ## `Header` 매개변수 선언 @@ -17,16 +17,22 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` -!!! note "기술 세부사항" - `Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. +/// note | 기술 세부사항 - `Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요. +`Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. -!!! info "정보" - 헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. +`Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요. + +/// + +/// info | 정보 + +헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. + +/// ## 자동 변환 @@ -45,11 +51,14 @@ 만약 언더스코어를 하이픈으로 자동 변환을 비활성화해야 할 어떤 이유가 있다면, `Header`의 `convert_underscores` 매개변수를 `False`로 설정하십시오: ```Python hl_lines="10" -{!../../../docs_src/header_params/tutorial002.py!} +{!../../docs_src/header_params/tutorial002.py!} ``` -!!! warning "경고" - `convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오. +/// warning | 경고 + +`convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오. + +/// ## 중복 헤더 @@ -62,7 +71,7 @@ 예를 들어, 두 번 이상 나타날 수 있는 `X-Token`헤더를 선언하려면, 다음과 같이 작성합니다: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial003.py!} +{!../../docs_src/header_params/tutorial003.py!} ``` 다음과 같은 두 개의 HTTP 헤더를 전송하여 해당 *경로* 와 통신할 경우: diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md index 94d6dfb92..9f5328992 100644 --- a/docs/ko/docs/tutorial/index.md +++ b/docs/ko/docs/tutorial/index.md @@ -30,7 +30,7 @@ $ uvicorn main:app --reload 코드를 작성하거나 복사, 편집할 때, 로컬 환경에서 실행하는 것을 **강력히 권장**합니다. -로컬 편집기에서 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 비로소 경험할 수 있습니다. +로컬 편집기에서 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 이점을 비로소 경험할 수 있습니다. --- @@ -53,22 +53,25 @@ $ pip install "fastapi[all]" ...이는 코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 또한 포함하고 있습니다. -!!! note "참고" - 부분적으로 설치할 수도 있습니다. +/// note | 참고 - 애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다: +부분적으로 설치할 수도 있습니다. - ``` - pip install fastapi - ``` +애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다: - 추가로 서버 역할을 하는 `uvicorn`을 설치합니다: +``` +pip install fastapi +``` + +추가로 서버 역할을 하는 `uvicorn`을 설치합니다: + +``` +pip install uvicorn +``` - ``` - pip install uvicorn - ``` +사용하려는 각 선택적인 의존성에 대해서도 동일합니다. - 사용하려는 각 선택적인 의존성에 대해서도 동일합니다. +/// ## 고급 사용자 안내서 diff --git a/docs/ko/docs/tutorial/metadata.md b/docs/ko/docs/tutorial/metadata.md new file mode 100644 index 000000000..87531152c --- /dev/null +++ b/docs/ko/docs/tutorial/metadata.md @@ -0,0 +1,131 @@ + +# 메타데이터 및 문서화 URL + +**FastAPI** 응용 프로그램에서 다양한 메타데이터 구성을 사용자 맞춤 설정할 수 있습니다. + +## API에 대한 메타데이터 + +OpenAPI 명세 및 자동화된 API 문서 UI에 사용되는 다음 필드를 설정할 수 있습니다: + +| 매개변수 | 타입 | 설명 | +|----------|------|-------| +| `title` | `str` | API의 제목입니다. | +| `summary` | `str` | API에 대한 짧은 요약입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능 | +| `description` | `str` | API에 대한 짧은 설명입니다. 마크다운을 사용할 수 있습니다. | +| `version` | `string` | API의 버전입니다. OpenAPI의 버전이 아닌, 여러분의 애플리케이션의 버전을 나타냅니다. 예: `2.5.0` | +| `terms_of_service` | `str` | API 이용 약관의 URL입니다. 제공하는 경우 URL 형식이어야 합니다. | +| `contact` | `dict` | 노출된 API에 대한 연락처 정보입니다. 여러 필드를 포함할 수 있습니다.
contact 필드
매개변수타입설명
namestr연락처 인물/조직의 식별명입니다.
urlstr연락처 정보가 담긴 URL입니다. URL 형식이어야 합니다.
emailstr연락처 인물/조직의 이메일 주소입니다. 이메일 주소 형식이어야 합니다.
| +| `license_info` | `dict` | 노출된 API의 라이선스 정보입니다. 여러 필드를 포함할 수 있습니다.
license_info 필드
매개변수타입설명
namestr필수 (license_info가 설정된 경우). API에 사용된 라이선스 이름입니다.
identifierstrAPI에 대한 SPDX 라이선스 표현입니다. identifier 필드는 url 필드와 상호 배타적입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능
urlstrAPI에 사용된 라이선스의 URL입니다. URL 형식이어야 합니다.
| + +다음과 같이 설정할 수 있습니다: + +```Python hl_lines="3-16 19-32" +{!../../docs_src/metadata/tutorial001.py!} +``` + +/// tip + +`description` 필드에 마크다운을 사용할 수 있으며, 출력에서 렌더링됩니다. + +/// + +이 구성을 사용하면 문서 자동화(로 생성된) API 문서는 다음과 같이 보입니다: + + + +## 라이선스 식별자 + +OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `identifier`를 URL 대신 설정할 수 있습니다. + +예: + +```Python hl_lines="31" +{!../../docs_src/metadata/tutorial001_1.py!} +``` + +## 태그에 대한 메타데이터 + +`openapi_tags` 매개변수를 사용하여 경로 작동을 그룹화하는 데 사용되는 태그에 추가 메타데이터를 추가할 수 있습니다. + +리스트는 각 태그에 대해 하나의 딕셔너리를 포함해야 합니다. + +각 딕셔너리에는 다음이 포함될 수 있습니다: + +* `name` (**필수**): `tags` 매개변수에서 *경로 작동*과 `APIRouter`에 사용된 태그 이름과 동일한 `str`입니다. +* `description`: 태그에 대한 간단한 설명을 담은 `str`입니다. 마크다운을 사용할 수 있으며 문서 UI에 표시됩니다. +* `externalDocs`: 외부 문서를 설명하는 `dict`이며: + * `description`: 외부 문서에 대한 간단한 설명을 담은 `str`입니다. + * `url` (**필수**): 외부 문서의 URL을 담은 `str`입니다. + +### 태그에 대한 메타데이터 생성 + +`users` 및 `items`에 대한 태그 예시와 함께 메타데이터를 생성하고 이를 `openapi_tags` 매개변수로 전달해 보겠습니다: + +```Python hl_lines="3-16 18" +{!../../docs_src/metadata/tutorial004.py!} +``` + +설명 안에 마크다운을 사용할 수 있습니다. 예를 들어 "login"은 굵게(**login**) 표시되고, "fancy"는 기울임꼴(_fancy_)로 표시됩니다. + +/// tip + +사용 중인 모든 태그에 메타데이터를 추가할 필요는 없습니다. + +/// + +### 태그 사용 + +`tags` 매개변수를 *경로 작동* 및 `APIRouter`와 함께 사용하여 태그에 할당할 수 있습니다: + +```Python hl_lines="21 26" +{!../../docs_src/metadata/tutorial004.py!} +``` + +/// info + +태그에 대한 자세한 내용은 [경로 작동 구성](path-operation-configuration.md#tags){.internal-link target=_blank}에서 읽어보세요. + +/// + +### 문서 확인 + +이제 문서를 확인하면 모든 추가 메타데이터가 표시됩니다: + + + +### 태그 순서 + +각 태그 메타데이터 딕셔너리의 순서는 문서 UI에 표시되는 순서를 정의합니다. + +예를 들어, 알파벳 순서상 `users`는 `items` 뒤에 오지만, 우리는 `users` 메타데이터를 리스트의 첫 번째 딕셔너리로 추가했기 때문에 먼저 표시됩니다. + +## OpenAPI URL + +OpenAPI 구조는 기본적으로 `/openapi.json`에서 제공됩니다. + +`openapi_url` 매개변수를 통해 이를 설정할 수 있습니다. + +예를 들어, 이를 `/api/v1/openapi.json`에 제공하도록 설정하려면: + +```Python hl_lines="3" +{!../../docs_src/metadata/tutorial002.py!} +``` + +OpenAPI 구조를 완전히 비활성화하려면 `openapi_url=None`으로 설정할 수 있으며, 이를 사용하여 문서화 사용자 인터페이스도 비활성화됩니다. + +## 문서화 URL + +포함된 두 가지 문서화 사용자 인터페이스를 설정할 수 있습니다: + +* **Swagger UI**: `/docs`에서 제공됩니다. + * `docs_url` 매개변수로 URL을 설정할 수 있습니다. + * `docs_url=None`으로 설정하여 비활성화할 수 있습니다. +* **ReDoc**: `/redoc`에서 제공됩니다. + * `redoc_url` 매개변수로 URL을 설정할 수 있습니다. + * `redoc_url=None`으로 설정하여 비활성화할 수 있습니다. + +예를 들어, Swagger UI를 `/documentation`에서 제공하고 ReDoc을 비활성화하려면: + +```Python hl_lines="3" +{!../../docs_src/metadata/tutorial003.py!} +``` diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md index f35b446a6..0547066f1 100644 --- a/docs/ko/docs/tutorial/middleware.md +++ b/docs/ko/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * **응답** 또는 다른 필요한 코드를 실행시키는 동작을 할 수 있습니다. * **응답**를 반환합니다. -!!! note "기술 세부사항" - 만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다. +/// note | 기술 세부사항 - 만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다. +만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다. + +만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다. + +/// ## 미들웨어 만들기 @@ -29,18 +32,24 @@ * `response`를 반환하기 전에 추가로 `response`를 수정할 수 있습니다. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` -!!! tip "팁" - 사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다. +/// tip | 팁 + +사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다. + +그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 Starlette CORS 문서에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다. + +/// + +/// note | 기술적 세부사항 - 그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 Starlette CORS 문서에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다. +`from starlette.requests import request`를 사용할 수도 있습니다. -!!! note "기술적 세부사항" - `from starlette.requests import request`를 사용할 수도 있습니다. +**FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다. - **FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다. +/// ### `response`의 전과 후 @@ -51,7 +60,7 @@ 예를 들어, 요청을 수행하고 응답을 생성하는데 까지 걸린 시간 값을 가지고 있는 `X-Process-Time` 같은 사용자 정의 헤더를 추가할 수 있습니다. ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## 다른 미들웨어 diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md index 411c43493..75a9c71ce 100644 --- a/docs/ko/docs/tutorial/path-operation-configuration.md +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ *경로 작동 데코레이터*를 설정하기 위해서 전달할수 있는 몇 가지 매개변수가 있습니다. -!!! warning "경고" - 아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오. +/// warning | 경고 + +아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오. + +/// ## 응답 상태 코드 @@ -14,22 +17,25 @@ 하지만 각 코드의 의미를 모른다면, `status`에 있는 단축 상수들을 사용할수 있습니다: ```Python hl_lines="3 17" -{!../../../docs_src/path_operation_configuration/tutorial001.py!} +{!../../docs_src/path_operation_configuration/tutorial001.py!} ``` 각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. -!!! note "기술적 세부사항" - 다음과 같이 임포트하셔도 좋습니다. `from starlette import status`. +/// note | 기술적 세부사항 + +다음과 같이 임포트하셔도 좋습니다. `from starlette import status`. + +**FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다. - **FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다. +/// ## 태그 (보통 단일 `str`인) `str`로 구성된 `list`와 함께 매개변수 `tags`를 전달하여, `경로 작동`에 태그를 추가할 수 있습니다: ```Python hl_lines="17 22 27" -{!../../../docs_src/path_operation_configuration/tutorial002.py!} +{!../../docs_src/path_operation_configuration/tutorial002.py!} ``` 전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다: @@ -41,7 +47,7 @@ `summary`와 `description`을 추가할 수 있습니다: ```Python hl_lines="20-21" -{!../../../docs_src/path_operation_configuration/tutorial003.py!} +{!../../docs_src/path_operation_configuration/tutorial003.py!} ``` ## 독스트링으로 만든 기술 @@ -51,7 +57,7 @@ 마크다운 문법으로 독스트링을 작성할 수 있습니다, 작성된 마크다운 형식의 독스트링은 (마크다운의 들여쓰기를 고려하여) 올바르게 화면에 출력됩니다. ```Python hl_lines="19-27" -{!../../../docs_src/path_operation_configuration/tutorial004.py!} +{!../../docs_src/path_operation_configuration/tutorial004.py!} ``` 이는 대화형 문서에서 사용됩니다: @@ -63,16 +69,22 @@ `response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다: ```Python hl_lines="21" -{!../../../docs_src/path_operation_configuration/tutorial005.py!} +{!../../docs_src/path_operation_configuration/tutorial005.py!} ``` -!!! info "정보" - `response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다. +/// info | 정보 + +`response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다. + +/// + +/// check | 확인 + +OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다. -!!! check "확인" - OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다. +따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다. - 따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다. +/// @@ -81,7 +93,7 @@ 단일 *경로 작동*을 없애지 않고 지원중단을 해야한다면, `deprecated` 매개변수를 전달하면 됩니다. ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` 대화형 문서에 지원중단이라고 표시됩니다. diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md index cadf543fc..736f2dc1d 100644 --- a/docs/ko/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md @@ -7,7 +7,7 @@ 먼저 `fastapi`에서 `Path`를 임포트합니다: ```Python hl_lines="3" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` ## 메타데이터 선언 @@ -17,15 +17,18 @@ 예를 들어, `title` 메타데이터 값을 경로 매개변수 `item_id`에 선언하려면 다음과 같이 입력할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` -!!! note "참고" - 경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다. +/// note | 참고 - 즉, `...`로 선언해서 필수임을 나타내는게 좋습니다. +경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다. - 그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다. +즉, `...`로 선언해서 필수임을 나타내는게 좋습니다. + +그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다. + +/// ## 필요한 경우 매개변수 정렬하기 @@ -44,7 +47,7 @@ 따라서 함수를 다음과 같이 선언 할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## 필요한 경우 매개변수 정렬하기, 트릭 @@ -56,7 +59,7 @@ 파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 kwargs로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## 숫자 검증: 크거나 같음 @@ -66,7 +69,7 @@ 여기서 `ge=1`인 경우, `item_id`는 `1`보다 "크거나(`g`reater) 같은(`e`qual)" 정수형 숫자여야 합니다. ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## 숫자 검증: 크거나 같음 및 작거나 같음 @@ -77,7 +80,7 @@ * `le`: 작거나 같은(`l`ess than or `e`qual) ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## 숫자 검증: 부동소수, 크거나 및 작거나 @@ -91,7 +94,7 @@ lt 역시 마찬가지입니다. ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## 요약 @@ -105,18 +108,24 @@ * `lt`: 작거나(`l`ess `t`han) * `le`: 작거나 같은(`l`ess than or `e`qual) -!!! info "정보" - `Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다. +/// info | 정보 + +`Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다. + +그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다. + +/// + +/// note | 기술 세부사항 - 그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다. +`fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다. -!!! note "기술 세부사항" - `fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다. +호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다. - 호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다. +즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다. - 즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다. +편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다. - 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다. +이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다. - 이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다. +/// diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index a75c3cc8c..21808e2ca 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ 파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` 경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다. @@ -19,13 +19,16 @@ 파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` 위의 예시에서, `item_id`는 `int`로 선언되었습니다. -!!! check "확인" - 이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다. +/// check | 확인 + +이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다. + +/// ## 데이터 변환 @@ -35,10 +38,13 @@ {"item_id":3} ``` -!!! check "확인" - 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다. +/// check | 확인 + +함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다. + +즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다. - 즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다. +/// ## 데이터 검증 @@ -63,12 +69,15 @@ `int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2 -!!! check "확인" - 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. +/// check | 확인 - 오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다. +즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. - 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다. +오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다. + +이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다. + +/// ## 문서화 @@ -76,10 +85,13 @@ -!!! check "확인" - 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다. +/// check | 확인 + +그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다. + +경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다. - 경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다. +/// ## 표준 기반의 이점, 대체 문서 @@ -110,7 +122,7 @@ *경로 작동*은 순차적으로 실행되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` 그렇지 않으면 `/users/{user_id}`는 `/users/me` 요청 또한 매개변수 `user_id`의 값이 `"me"`인 것으로 "생각하게" 됩니다. @@ -128,21 +140,27 @@ 가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! info "정보" - 열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다. +/// info | 정보 -!!! tip "팁" - 혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다. +열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다. + +/// + +/// tip | 팁 + +혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다. + +/// ### *경로 매개변수* 선언 생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수*를 만듭니다: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### 문서 확인 @@ -160,7 +178,7 @@ 열거형 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### *열거형 값* 가져오기 @@ -168,11 +186,14 @@ `model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "팁" - `ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다. +/// tip | 팁 + +`ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다. + +/// #### *열거형 멤버* 반환 @@ -181,7 +202,7 @@ 클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` 클라이언트는 아래의 JSON 응답을 얻습니다: @@ -222,13 +243,16 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으 따라서 다음과 같이 사용할 수 있습니다: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "팁" - 매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다. +/// tip | 팁 + +매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다. + +이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다. - 이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md index 2e6396ccc..71f884e83 100644 --- a/docs/ko/docs/tutorial/query-params-str-validations.md +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -5,15 +5,18 @@ 이 응용 프로그램을 예로 들어보겠습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} +{!../../docs_src/query_params_str_validations/tutorial001.py!} ``` 쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. -!!! note "참고" - FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다. +/// note | 참고 - `Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다. +FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다. + +`Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다. + +/// ## 추가 검증 @@ -24,7 +27,7 @@ 이를 위해 먼저 `fastapi`에서 `Query`를 임포트합니다: ```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` ## 기본값으로 `Query` 사용 @@ -32,7 +35,7 @@ 이제 `Query`를 매개변수의 기본값으로 사용하여 `max_length` 매개변수를 50으로 설정합니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` 기본값 `None`을 `Query(None)`으로 바꿔야 하므로, `Query`의 첫 번째 매개변수는 기본값을 정의하는 것과 같은 목적으로 사용됩니다. @@ -51,22 +54,25 @@ q: Optional[str] = None 하지만 명시적으로 쿼리 매개변수를 선언합니다. -!!! info "정보" - FastAPI는 다음 부분에 관심이 있습니다: +/// info | 정보 - ```Python - = None - ``` +FastAPI는 다음 부분에 관심이 있습니다: - 또는: +```Python += None +``` - ```Python - = Query(None) - ``` +또는: - 그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다. +```Python += Query(None) +``` + +그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다. - `Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다. +`Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다. + +/// 또한 `Query`로 더 많은 매개변수를 전달할 수 있습니다. 지금의 경우 문자열에 적용되는 `max_length` 매개변수입니다: @@ -81,7 +87,7 @@ q: str = Query(None, max_length=50) 매개변수 `min_length` 또한 추가할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} +{!../../docs_src/query_params_str_validations/tutorial003.py!} ``` ## 정규식 추가 @@ -89,7 +95,7 @@ q: str = Query(None, max_length=50) 매개변수와 일치해야 하는 정규표현식을 정의할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` 이 특정 정규표현식은 전달 받은 매개변수 값을 검사합니다: @@ -109,11 +115,14 @@ q: str = Query(None, max_length=50) `min_length`가 `3`이고, 기본값이 `"fixedquery"`인 쿼리 매개변수 `q`를 선언해봅시다: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "참고" - 기본값을 갖는 것만으로 매개변수는 선택적이 됩니다. +/// note | 참고 + +기본값을 갖는 것만으로 매개변수는 선택적이 됩니다. + +/// ## 필수로 만들기 @@ -138,11 +147,14 @@ q: Optional[str] = Query(None, min_length=3) 그래서 `Query`를 필수값으로 만들어야 할 때면, 첫 번째 인자로 `...`를 사용할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info "정보" - 이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다. +/// info | 정보 + +이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다. + +/// 이렇게 하면 **FastAPI**가 이 매개변수는 필수임을 알 수 있습니다. @@ -153,7 +165,7 @@ q: Optional[str] = Query(None, min_length=3) 예를 들어, URL에서 여러번 나오는 `q` 쿼리 매개변수를 선언하려면 다음과 같이 작성할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` 아래와 같은 URL을 사용합니다: @@ -175,8 +187,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "팁" - 위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다. +/// tip | 팁 + +위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다. + +/// 대화형 API 문서는 여러 값을 허용하도록 수정 됩니다: @@ -187,7 +202,7 @@ http://localhost:8000/items/?q=foo&q=bar 그리고 제공된 값이 없으면 기본 `list` 값을 정의할 수도 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` 아래로 이동한다면: @@ -212,13 +227,16 @@ http://localhost:8000/items/ `List[str]` 대신 `list`를 직접 사용할 수도 있습니다: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note "참고" - 이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다. +/// note | 참고 - 예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다. +이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다. + +예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다. + +/// ## 더 많은 메타데이터 선언 @@ -226,21 +244,24 @@ http://localhost:8000/items/ 해당 정보는 생성된 OpenAPI에 포함되고 문서 사용자 인터페이스 및 외부 도구에서 사용됩니다. -!!! note "참고" - 도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다. +/// note | 참고 + +도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다. + +일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다. - 일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다. +/// `title`을 추가할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` 그리고 `description`도 추가할 수 있습니다: ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## 별칭 매개변수 @@ -262,7 +283,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 이럴 경우 `alias`를 선언할 수 있으며, 해당 별칭은 매개변수 값을 찾는 데 사용됩니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## 매개변수 사용하지 않게 하기 @@ -274,7 +295,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 그렇다면 `deprecated=True` 매개변수를 `Query`로 전달합니다: ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` 문서가 아래와 같이 보일겁니다: diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index 8c7f9167b..7fa3e8c53 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ 경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` 쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다. @@ -64,25 +64,31 @@ http://127.0.0.1:8000/items/?skip=20 같은 방법으로 기본값을 `None`으로 설정하여 선택적 매개변수를 선언할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} +{!../../docs_src/query_params/tutorial002.py!} ``` 이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다. -!!! check "확인" - **FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다. +/// check | 확인 -!!! note "참고" - FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. +**FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다. - `Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다. +/// + +/// note | 참고 + +FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. + +`Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다. + +/// ## 쿼리 매개변수 형변환 `bool` 형으로 선언할 수도 있고, 아래처럼 변환됩니다: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} +{!../../docs_src/query_params/tutorial003.py!} ``` 이 경우, 아래로 이동하면: @@ -127,7 +133,7 @@ http://127.0.0.1:8000/items/foo?short=yes 매개변수들은 이름으로 감지됩니다: ```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} +{!../../docs_src/query_params/tutorial004.py!} ``` ## 필수 쿼리 매개변수 @@ -139,7 +145,7 @@ http://127.0.0.1:8000/items/foo?short=yes 그러나 쿼리 매개변수를 필수로 만들려면 단순히 기본값을 선언하지 않으면 됩니다: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` 여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다. @@ -185,7 +191,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 그리고 물론, 일부 매개변수는 필수로, 다른 일부는 기본값을, 또 다른 일부는 선택적으로 선언할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} +{!../../docs_src/query_params/tutorial006.py!} ``` 위 예시에서는 3가지 쿼리 매개변수가 있습니다: @@ -194,5 +200,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, 기본값이 `0`인 `int`. * `limit`, 선택적인 `int`. -!!! tip "팁" - [경로 매개변수](path-params.md#predefined-values){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. +/// tip | 팁 + +[경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. + +/// diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index 468c46283..ca0f43978 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -2,19 +2,22 @@ `File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다. -!!! info "정보" - 업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다. +/// info | 정보 - 예시) `pip install python-multipart`. +업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다. - 업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다. +예시) `pip install python-multipart`. + +업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다. + +/// ## `File` 임포트 `fastapi` 에서 `File` 과 `UploadFile` 을 임포트 합니다: ```Python hl_lines="1" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` ## `File` 매개변수 정의 @@ -22,16 +25,22 @@ `Body` 및 `Form` 과 동일한 방식으로 파일의 매개변수를 생성합니다: ```Python hl_lines="7" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` -!!! info "정보" - `File` 은 `Form` 으로부터 직접 상속된 클래스입니다. +/// info | 정보 + +`File` 은 `Form` 으로부터 직접 상속된 클래스입니다. + +하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다. + +/// - 하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다. +/// tip | 팁 -!!! tip "팁" - File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다. +File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다. + +/// 파일들은 "폼 데이터"의 형태로 업로드 됩니다. @@ -46,7 +55,7 @@ `File` 매개변수를 `UploadFile` 타입으로 정의합니다: ```Python hl_lines="12" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` `UploadFile` 을 사용하는 것은 `bytes` 과 비교해 다음과 같은 장점이 있습니다: @@ -89,11 +98,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 기술적 세부사항" - `async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다. +/// note | "`async` 기술적 세부사항" + +`async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다. + +/// + +/// note | Starlette 기술적 세부사항 -!!! note "Starlette 기술적 세부사항" - **FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다. +**FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다. + +/// ## "폼 데이터"란 @@ -101,17 +116,23 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 **FastAPI**는 JSON 대신 올바른 위치에서 데이터를 읽을 수 있도록 합니다. -!!! note "기술적 세부사항" - 폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다. +/// note | 기술적 세부사항 + +폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다. + +하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다. + +인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,. + +/// - 하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다. +/// warning | 경고 - 인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,. +다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. -!!! warning "경고" - 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. +이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. - 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. +/// ## 다중 파일 업로드 @@ -122,22 +143,28 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다: ```Python hl_lines="10 15" -{!../../../docs_src/request_files/tutorial002.py!} +{!../../docs_src/request_files/tutorial002.py!} ``` 선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다. -!!! note "참고" - 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276#3641을 참고하세요. +/// note | 참고 + +2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276#3641을 참고하세요. + +그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다. + +따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다. + +/// - 그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다. +/// note | 기술적 세부사항 - 따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다. +`from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다. -!!! note "기술적 세부사항" - `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다. +**FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다. - **FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index bd5f41918..75bca9f15 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -2,15 +2,18 @@ `File` 과 `Form` 을 사용하여 파일과 폼을 함께 정의할 수 있습니다. -!!! info "정보" - 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다. +/// info | 정보 - 예 ) `pip install python-multipart`. +파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다. + +예 ) `pip install python-multipart`. + +/// ## `File` 및 `Form` 업로드 ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## `File` 및 `Form` 매개변수 정의 @@ -18,17 +21,20 @@ `Body` 및 `Query`와 동일한 방식으로 파일과 폼의 매개변수를 생성합니다: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` 파일과 폼 필드는 폼 데이터 형식으로 업로드되어 파일과 폼 필드로 전달됩니다. 어떤 파일들은 `bytes`로, 또 어떤 파일들은 `UploadFile`로 선언할 수 있습니다. -!!! warning "경고" - 다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. +/// warning | 경고 + +다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. + +이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. - 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md index feff88a42..6ba9654d6 100644 --- a/docs/ko/docs/tutorial/response-model.md +++ b/docs/ko/docs/tutorial/response-model.md @@ -9,11 +9,14 @@ * 기타. ```Python hl_lines="17" -{!../../../docs_src/response_model/tutorial001.py!} +{!../../docs_src/response_model/tutorial001.py!} ``` -!!! note "참고" - `response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다. +/// note | 참고 + +`response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다. + +/// Pydantic 모델 어트리뷰트를 선언한 것과 동일한 타입을 수신하므로 Pydantic 모델이 될 수 있지만, `List[Item]`과 같이 Pydantic 모델들의 `list`일 수도 있습니다. @@ -28,21 +31,24 @@ FastAPI는 이 `response_model`를 사용하여: * 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다. -!!! note "기술 세부사항" - 응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다 +/// note | 기술 세부사항 + +응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다 + +/// ## 동일한 입력 데이터 반환 여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다: ```Python hl_lines="9 11" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` 그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다: ```Python hl_lines="17-18" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` 이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다. @@ -51,27 +57,30 @@ FastAPI는 이 `response_model`를 사용하여: 그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다. -!!! danger "위험" - 절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오. +/// danger | 위험 + +절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오. + +/// ## 출력 모델 추가 대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다: ```Python hl_lines="9 11 16" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` 여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` ...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다: ```Python hl_lines="22" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` 따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다. @@ -91,7 +100,7 @@ FastAPI는 이 `response_model`를 사용하여: 응답 모델은 아래와 같이 기본값을 가질 수 있습니다: ```Python hl_lines="11 13-14" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` * `description: Optional[str] = None`은 기본값으로 `None`을 갖습니다. @@ -107,7 +116,7 @@ FastAPI는 이 `response_model`를 사용하여: *경로 작동 데코레이터* 매개변수를 `response_model_exclude_unset=True`로 설정 할 수 있습니다: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` 이러한 기본값은 응답에 포함되지 않고 실제로 설정된 값만 포함됩니다. @@ -121,16 +130,22 @@ FastAPI는 이 `response_model`를 사용하여: } ``` -!!! info "정보" - FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다. +/// info | 정보 + +FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다. + +/// -!!! info "정보" - 아래 또한 사용할 수 있습니다: +/// info | 정보 - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +아래 또한 사용할 수 있습니다: - Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다. +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다. + +/// #### 기본값이 있는 필드를 갖는 값의 데이터 @@ -166,10 +181,13 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: 따라서 JSON 스키마에 포함됩니다. -!!! tip "팁" - `None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다. +/// tip | 팁 + +`None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다. + +리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다. - 리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다. +/// ### `response_model_include` 및 `response_model_exclude` @@ -179,28 +197,34 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제거하려는 경우 빠른 지름길로 사용할 수 있습니다. -!!! tip "팁" - 하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다. +/// tip | 팁 - 이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다. +하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다. - 비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다. +이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다. + +비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다. + +/// ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial005.py!} +{!../../docs_src/response_model/tutorial005.py!} ``` -!!! tip "팁" - 문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다. +/// tip | 팁 + +문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다. + +이는 `set(["name", "description"])`과 동일합니다. - 이는 `set(["name", "description"])`과 동일합니다. +/// #### `set` 대신 `list` 사용하기 `list` 또는 `tuple` 대신 `set`을 사용하는 법을 잊었더라도, FastAPI는 `set`으로 변환하고 정상적으로 작동합니다: ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial006.py!} +{!../../docs_src/response_model/tutorial006.py!} ``` ## 요약 diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index f92c057be..8e3a16645 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -9,16 +9,22 @@ * 기타 ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "참고" - `status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다. +/// note | 참고 + +`status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다. + +/// `status_code` 매개변수는 HTTP 상태 코드를 숫자로 입력받습니다. -!!! info "정보" - `status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다. +/// info | 정보 + +`status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다. + +/// `status_code` 매개변수는: @@ -27,15 +33,21 @@ -!!! note "참고" - 어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고). +/// note | 참고 + +어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고). + +이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다. - 이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다. +/// ## HTTP 상태 코드에 대하여 -!!! note "참고" - 만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오. +/// note | 참고 + +만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오. + +/// HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다. @@ -43,26 +55,29 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 요약하자면: -* `**1xx**` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다. -* `**2xx**` 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다. +* `1xx` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다. +* **`2xx`** 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다. * `200` 은 디폴트 상태 코드로, 모든 것이 "성공적임"을 의미합니다. * 다른 예로는 `201` "생성됨"이 있습니다. 일반적으로 데이터베이스에 새로운 레코드를 생성한 후 사용합니다. * 단, `204` "내용 없음"은 특별한 경우입니다. 이것은 클라이언트에게 반환할 내용이 없는 경우 사용합니다. 따라서 응답은 본문을 가질 수 없습니다. -* `**3xx**` 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다. -* `**4xx**` 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다. +* **`3xx`** 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다. +* **`4xx`** 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다. * 일례로 `404` 는 "찾을 수 없음" 응답을 위해 사용합니다. * 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다. -* `**5xx**` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. +* `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. + +/// tip | 팁 -!!! tip "팁" - 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오. +각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오. + +/// ## 이름을 기억하는 쉬운 방법 상기 예시 참고: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` 은 "생성됨"를 의미하는 상태 코드입니다. @@ -72,17 +87,20 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 `fastapi.status` 의 편의 변수를 사용할 수 있습니다. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` 이것은 단순히 작업을 편리하게 하기 위한 것으로, HTTP 상태 코드와 동일한 번호를 갖고있지만, 이를 사용하면 편집기의 자동완성 기능을 사용할 수 있습니다: -!!! note "기술적 세부사항" - `from starlette import status` 역시 사용할 수 있습니다. +/// note | 기술적 세부사항 + +`from starlette import status` 역시 사용할 수 있습니다. + +**FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. - **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. +/// ## 기본값 변경 diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md index 4e319e075..77e94db72 100644 --- a/docs/ko/docs/tutorial/schema-extra-example.md +++ b/docs/ko/docs/tutorial/schema-extra-example.md @@ -8,71 +8,59 @@ 생성된 JSON 스키마에 추가될 Pydantic 모델을 위한 `examples`을 선언할 수 있습니다. -=== "Python 3.10+ Pydantic v2" +//// tab | Pydantic v2 - ```Python hl_lines="13-24" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} -=== "Python 3.10+ Pydantic v1" +//// - ```Python hl_lines="13-23" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} - ``` +//// tab | Pydantic v1 -=== "Python 3.8+ Pydantic v2" +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} - ```Python hl_lines="15-26" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// -=== "Python 3.8+ Pydantic v1" +추가 정보는 있는 그대로 해당 모델의 **JSON 스키마** 결과에 추가되고, API 문서에서 사용합니다. - ```Python hl_lines="15-25" - {!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} - ``` +//// tab | Pydantic v2 -추가 정보는 있는 그대로 해당 모델의 **JSON 스키마** 결과에 추가되고, API 문서에서 사용합니다. +Pydantic 버전 2에서 Pydantic 공식 문서: Model Config에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다. -=== "Pydantic v2" +`"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. - Pydantic 버전 2에서 Pydantic 공식 문서: Model Config에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다. +//// - `"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. +//// tab | Pydantic v1 -=== "Pydantic v1" +Pydantic v1에서 Pydantic 공식 문서: Schema customization에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다. - Pydantic v1에서 Pydantic 공식 문서: Schema customization에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다. +`schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. - `schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. +//// -!!! tip "팁" - JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다. +/// tip | 팁 - 예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다. +JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다. -!!! info "정보" - (FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다. +예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다. - 그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓 +/// - 이 문서 끝에 더 많은 읽을거리가 있습니다. +/// info | 정보 -## `Field` 추가 인자 +(FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다. -Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 선언할 수 있습니다: +그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓 + +이 문서 끝에 더 많은 읽을거리가 있습니다. -=== "Python 3.10+" +/// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +## `Field` 추가 인자 -=== "Python 3.8+" +Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 선언할 수 있습니다: - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} ## JSON Schema에서의 `examples` - OpenAPI @@ -92,41 +80,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 여기, `Body()`에 예상되는 예제 데이터 하나를 포함한 `examples`를 넘겼습니다: -=== "Python 3.10+" - - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="22-29" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="23-30" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` - -=== "Python 3.10+ Annotated가 없는 경우" - - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. - - ```Python hl_lines="18-25" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` - -=== "Python 3.8+ Annotated가 없는 경우" - - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. - - ```Python hl_lines="20-27" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} ### 문서 UI 예시 @@ -138,41 +92,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 물론 여러 `examples`를 넘길 수 있습니다: -=== "Python 3.10+" - - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="23-38" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="24-39" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` - -=== "Python 3.10+ Annotated가 없는 경우" - - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. - - ```Python hl_lines="19-34" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` - -=== "Python 3.8+ Annotated가 없는 경우" - - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. - - ```Python hl_lines="21-36" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} 이와 같이 하면 이 예제는 그 본문 데이터를 위한 내부 **JSON 스키마**의 일부가 될 것입니다. @@ -213,41 +133,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 이를 다음과 같이 사용할 수 있습니다: -=== "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+ Annotated가 없는 경우" - - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. - - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} - ``` - -=== "Python 3.8+ Annotated가 없는 경우" - - !!! tip "팁" - 가능하다면 `Annotated`가 달린 버전을 권장합니다. - - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial005.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} ### 문서 UI에서의 OpenAPI 예시 @@ -257,17 +143,23 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 ## 기술적 세부 사항 -!!! tip "팁" - 이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다. +/// tip | 팁 + +이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다. + +세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다. - 세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다. +간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓 - 간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓 +/// -!!! warning "경고" - 표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다. +/// warning | 경고 - 만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다. +표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다. + +만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다. + +/// OpenAPI 3.1.0 전에 OpenAPI는 오래된 **JSON 스키마**의 수정된 버전을 사용했습니다. @@ -285,8 +177,11 @@ OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분 * `File()` * `Form()` -!!! info "정보" - 이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다. +/// info | 정보 + +이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다. + +/// ### JSON 스키마의 `examples` 필드 @@ -298,10 +193,13 @@ OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분 JSON 스키마의 새로운 `examples` 필드는 예제 속 **단순한 `list`**이며, (위에서 상술한 것처럼) OpenAPI의 다른 곳에 존재하는 dict으로 된 추가적인 메타데이터가 아닙니다. -!!! info "정보" - 더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉). +/// info | 정보 + +더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉). + +이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다. - 이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다. +/// ### Pydantic과 FastAPI `examples` diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md index 5bc2cee7a..cf550735a 100644 --- a/docs/ko/docs/tutorial/security/get-current-user.md +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -3,7 +3,7 @@ 이전 장에서 (의존성 주입 시스템을 기반으로 한)보안 시스템은 *경로 작동 함수*에서 `str`로 `token`을 제공했습니다: ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` 그러나 아직도 유용하지 않습니다. @@ -16,17 +16,21 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다른 곳에서 사용할 수 있습니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="5 12-16" +{!> ../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="3 10-14" +{!> ../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## `get_current_user` 의존성 생성하기 @@ -38,63 +42,81 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 이전에 *경로 작동*에서 직접 수행했던 것과 동일하게 새 종속성 `get_current_user`는 하위 종속성 `oauth2_scheme`에서 `str`로 `token`을 수신합니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="25" +{!> ../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="23" +{!> ../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 유저 가져오기 `get_current_user`는 토큰을 `str`로 취하고 Pydantic `User` 모델을 반환하는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="19-22 26-27" +{!> ../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="17-20 24-25" +{!> ../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 현재 유저 주입하기 이제 *경로 작동*에서 `get_current_user`와 동일한 `Depends`를 사용할 수 있습니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +```Python hl_lines="31" +{!> ../../docs_src/security/tutorial002.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="29" +{!> ../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다. 이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다. -!!! 팁 - 요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다. +/// tip | 팁 + +요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다. + +여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다. - 여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다. +/// -!!! 확인 - 이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다. +/// check | 확인 - 해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다. +이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다. + +해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다. + +/// ## 다른 모델 @@ -128,17 +150,21 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 그리고 이 수천 개의 *경로 작동*은 모두 3줄 정도로 줄일 수 있습니다. -=== "파이썬 3.7 이상" +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="30-32" +{!> ../../docs_src/security/tutorial002.py!} +``` + +//// - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +//// tab | 파이썬 3.10 이상 -=== "파이썬 3.10 이상" +```Python hl_lines="28-30" +{!> ../../docs_src/security/tutorial002_py310.py!} +``` - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +//// ## 요약 diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..fd18c1d47 --- /dev/null +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,359 @@ +# 패스워드와 Bearer를 이용한 간단한 OAuth2 + +이제 이전 장에서 빌드하고 누락된 부분을 추가하여 완전한 보안 흐름을 갖도록 하겠습니다. + +## `username`와 `password` 얻기 + +**FastAPI** 보안 유틸리티를 사용하여 `username` 및 `password`를 가져올 것입니다. + +OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 때 클라이언트/유저가 `username` 및 `password` 필드를 폼 데이터로 보내야 함을 지정합니다. + +그리고 사양에는 필드의 이름을 그렇게 지정해야 한다고 나와 있습니다. 따라서 `user-name` 또는 `email`은 작동하지 않습니다. + +하지만 걱정하지 않아도 됩니다. 프런트엔드에서 최종 사용자에게 원하는 대로 표시할 수 있습니다. + +그리고 데이터베이스 모델은 원하는 다른 이름을 사용할 수 있습니다. + +그러나 로그인 *경로 작동*의 경우 사양과 호환되도록 이러한 이름을 사용해야 합니다(예를 들어 통합 API 문서 시스템을 사용할 수 있어야 합니다). + +사양에는 또한 `username`과 `password`가 폼 데이터로 전송되어야 한다고 명시되어 있습니다(따라서 여기에는 JSON이 없습니다). + +### `scope` + +사양에는 클라이언트가 다른 폼 필드 "`scope`"를 보낼 수 있다고 나와 있습니다. + +폼 필드 이름은 `scope`(단수형)이지만 실제로는 공백으로 구분된 "범위"가 있는 긴 문자열입니다. + +각 "범위"는 공백이 없는 문자열입니다. + +일반적으로 특정 보안 권한을 선언하는 데 사용됩니다. 다음을 봅시다: + +* `users:read` 또는 `users:write`는 일반적인 예시입니다. +* `instagram_basic`은 페이스북/인스타그램에서 사용합니다. +* `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다. + +/// 정보 + +OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다. + +`:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다. + +이러한 세부 사항은 구현에 따라 다릅니다. + +OAuth2의 경우 문자열일 뿐입니다. + +/// + +## `username`과 `password`를 가져오는 코드 + +이제 **FastAPI**에서 제공하는 유틸리티를 사용하여 이를 처리해 보겠습니다. + +### `OAuth2PasswordRequestForm` + +먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다. + +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="4 76" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="2 74" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +`OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다: + +* `username`. +* `password`. +* `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다. +* `grant_type`(선택적으로 사용). + +/// 팁 + +OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다. + +사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다. + +/// + +* `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다). +* `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다). + +/// 정보 + +`OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다. + +`OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다. + +그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다. + +그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다. + +/// + +### 폼 데이터 사용하기 + +/// 팁 + +종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다. + +이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다. + +/// + +이제 폼 필드의 `username`을 사용하여 (가짜) 데이터베이스에서 유저 데이터를 가져옵니다. + +해당 사용자가 없으면 "잘못된 사용자 이름 또는 패스워드"라는 오류가 반환됩니다. + +오류의 경우 `HTTPException` 예외를 사용합니다: + +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="3 77-79" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="1 75-77" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +### 패스워드 확인하기 + +이 시점에서 데이터베이스의 사용자 데이터 형식을 확인했지만 암호를 확인하지 않았습니다. + +먼저 데이터를 Pydantic `UserInDB` 모델에 넣겠습니다. + +일반 텍스트 암호를 저장하면 안 되니 (가짜) 암호 해싱 시스템을 사용합니다. + +두 패스워드가 일치하지 않으면 동일한 오류가 반환됩니다. + +#### 패스워드 해싱 + +"해싱"은 일부 콘텐츠(이 경우 패스워드)를 횡설수설하는 것처럼 보이는 일련의 바이트(문자열)로 변환하는 것을 의미합니다. + +정확히 동일한 콘텐츠(정확히 동일한 패스워드)를 전달할 때마다 정확히 동일한 횡설수설이 발생합니다. + +그러나 횡설수설에서 암호로 다시 변환할 수는 없습니다. + +##### 패스워드 해싱을 사용해야 하는 이유 + +데이터베이스가 유출된 경우 해커는 사용자의 일반 텍스트 암호가 아니라 해시만 갖게 됩니다. + +따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다). + +//// tab | P파이썬 3.7 이상 + +```Python hl_lines="80-83" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="78-81" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +#### `**user_dict`에 대해 + +`UserInDB(**user_dict)`는 다음을 의미한다: + +*`user_dict`의 키와 값을 다음과 같은 키-값 인수로 직접 전달합니다:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// 정보 + +`**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다. + +/// + +## 토큰 반환하기 + +`token` 엔드포인트의 응답은 JSON 객체여야 합니다. + +`token_type`이 있어야 합니다. 여기서는 "Bearer" 토큰을 사용하므로 토큰 유형은 "`bearer`"여야 합니다. + +그리고 액세스 토큰을 포함하는 문자열과 함께 `access_token`이 있어야 합니다. + +이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다. + +/// 팁 + +다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다. + +하지만 지금은 필요한 세부 정보에 집중하겠습니다. + +/// + +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="85" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="83" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +/// 팁 + +사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다. + +이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다. + +사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다. + +나머지는 **FastAPI**가 처리합니다. + +/// + +## 의존성 업데이트하기 + +이제 의존성을 업데이트를 할 겁니다. + +이 사용자가 활성화되어 있는 *경우에만* `current_user`를 가져올 겁니다. + +따라서 `get_current_user`를 의존성으로 사용하는 추가 종속성 `get_current_active_user`를 만듭니다. + +이러한 의존성 모두, 사용자가 존재하지 않거나 비활성인 경우 HTTP 오류를 반환합니다. + +따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다: + +//// tab | 파이썬 3.7 이상 + +```Python hl_lines="58-66 69-72 90" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +//// tab | 파이썬 3.10 이상 + +```Python hl_lines="55-64 67-70 88" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +/// 정보 + +여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다. + +모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다. + +베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다. + +실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다. + +그러나 여기에서는 사양을 준수하도록 제공됩니다. + +또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다. + +그것이 표준의 이점입니다 ... + +/// + +## 확인하기 + +대화형 문서 열기: http://127.0.0.1:8000/docs. + +### 인증하기 + +"Authorize" 버튼을 눌러봅시다. + +자격 증명을 사용합니다. + +유저명: `johndoe` + +패스워드: `secret` + + + +시스템에서 인증하면 다음과 같이 표시됩니다: + + + +### 자신의 유저 데이터 가져오기 + +이제 `/users/me` 경로에 `GET` 작업을 진행합시다. + +다음과 같은 사용자 데이터를 얻을 수 있습니다: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +잠금 아이콘을 클릭하고 로그아웃한 다음 동일한 작업을 다시 시도하면 다음과 같은 HTTP 401 오류가 발생합니다. + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### 비활성된 유저 + +이제 비활성된 사용자로 시도하고, 인증해봅시다: + +유저명: `alice` + +패스워드: `secret2` + +그리고 `/users/me` 경로와 함께 `GET` 작업을 사용해 봅시다. + +다음과 같은 "Inactive user" 오류가 발생합니다: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## 요약 + +이제 API에 대한 `username` 및 `password`를 기반으로 완전한 보안 시스템을 구현할 수 있는 도구가 있습니다. + +이러한 도구를 사용하여 보안 시스템을 모든 데이터베이스 및 모든 사용자 또는 데이터 모델과 호환되도록 만들 수 있습니다. + +유일한 오점은 아직 실제로 "안전"하지 않다는 것입니다. + +다음 장에서는 안전한 패스워드 해싱 라이브러리와 JWT 토큰을 사용하는 방법을 살펴보겠습니다. diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md index fe1aa4e5e..af785f206 100644 --- a/docs/ko/docs/tutorial/static-files.md +++ b/docs/ko/docs/tutorial/static-files.md @@ -8,13 +8,16 @@ * 특정 경로에 `StaticFiles()` 인스턴스를 "마운트" 합니다. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` -!!! note "기술적 세부사항" - `from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다. +/// note | 기술적 세부사항 - **FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다. +`from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다. + +**FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다. + +/// ### "마운팅" 이란 diff --git a/docs/missing-translation.md b/docs/missing-translation.md index 32b6016f9..c2882e90e 100644 --- a/docs/missing-translation.md +++ b/docs/missing-translation.md @@ -1,4 +1,7 @@ -!!! warning - The current page still doesn't have a translation for this language. +/// warning - But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}. +The current page still doesn't have a translation for this language. + +But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}. + +/// diff --git a/docs/nl/docs/environment-variables.md b/docs/nl/docs/environment-variables.md new file mode 100644 index 000000000..f6b3d285b --- /dev/null +++ b/docs/nl/docs/environment-variables.md @@ -0,0 +1,298 @@ +# Omgevingsvariabelen + +/// tip + +Als je al weet wat "omgevingsvariabelen" zijn en hoe je ze kunt gebruiken, kun je deze stap gerust overslaan. + +/// + +Een omgevingsvariabele (ook bekend als "**env var**") is een variabele die **buiten** de Python-code leeft, in het **besturingssysteem** en die door je Python-code (of door andere programma's) kan worden gelezen. + +Omgevingsvariabelen kunnen nuttig zijn voor het bijhouden van applicatie **instellingen**, als onderdeel van de **installatie** van Python, enz. + +## Omgevingsvariabelen maken en gebruiken + +Je kunt omgevingsvariabelen **maken** en gebruiken in de **shell (terminal)**, zonder dat je Python nodig hebt: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Je zou een omgevingsvariabele MY_NAME kunnen maken met +$ export MY_NAME="Wade Wilson" + +// Dan zou je deze met andere programma's kunnen gebruiken, zoals +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Maak een omgevingsvariabel MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Gebruik het met andere programma's, zoals +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Omgevingsvariabelen uitlezen in Python + +Je kunt omgevingsvariabelen **buiten** Python aanmaken, in de terminal (of met een andere methode) en ze vervolgens **in Python uitlezen**. + +Je kunt bijvoorbeeld een bestand `main.py` hebben met: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +Het tweede argument van `os.getenv()` is de standaardwaarde die wordt geretourneerd. + +Als je dit niet meegeeft, is de standaardwaarde `None`. In dit geval gebruiken we standaard `"World"`. + +/// + +Dan zou je dat Python-programma kunnen aanroepen: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Hier stellen we de omgevingsvariabelen nog niet in +$ python main.py + +// Omdat we de omgevingsvariabelen niet hebben ingesteld, krijgen we de standaardwaarde + +Hello World from Python + +// Maar als we eerst een omgevingsvariabele aanmaken +$ export MY_NAME="Wade Wilson" + +// en het programma dan opnieuw aanroepen +$ python main.py + +// kan het de omgevingsvariabele nu wel uitlezen + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Hier stellen we de omgevingsvariabelen nog niet in +$ python main.py + +// Omdat we de omgevingsvariabelen niet hebben ingesteld, krijgen we de standaardwaarde + +Hello World from Python + +// Maar als we eerst een omgevingsvariabele aanmaken +$ $Env:MY_NAME = "Wade Wilson" + +// en het programma dan opnieuw aanroepen +$ python main.py + +// kan het de omgevingsvariabele nu wel uitlezen + +Hello Wade Wilson from Python +``` + +
+ +//// + +Omdat omgevingsvariabelen buiten de code kunnen worden ingesteld, maar wel door de code kunnen worden gelezen en niet hoeven te worden opgeslagen (gecommit naar `git`) met de rest van de bestanden, worden ze vaak gebruikt voor configuraties of **instellingen**. + +Je kunt ook een omgevingsvariabele maken die alleen voor een **specifieke programma-aanroep** beschikbaar is, die alleen voor dat programma beschikbaar is en alleen voor de duur van dat programma. + +Om dat te doen, maak je het vlak voor het programma zelf aan, op dezelfde regel: + +
+ +```console +// Maak een omgevingsvariabele MY_NAME in de regel voor deze programma-aanroep +$ MY_NAME="Wade Wilson" python main.py + +// Nu kan het de omgevingsvariabele lezen + +Hello Wade Wilson from Python + +// De omgevingsvariabelen bestaan daarna niet meer +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +Je kunt er meer over lezen op The Twelve-Factor App: Config. + +/// + +## Types en Validatie + +Deze omgevingsvariabelen kunnen alleen **tekstuele gegevens** verwerken, omdat ze extern zijn aan Python, compatibel moeten zijn met andere programma's en de rest van het systeem (zelfs met verschillende besturingssystemen, zoals Linux, Windows en macOS). + +Dat betekent dat **elke waarde** die in Python uit een omgevingsvariabele wordt gelezen **een `str` zal zijn** en dat elke conversie naar een ander type of elke validatie in de code moet worden uitgevoerd. + +Meer informatie over het gebruik van omgevingsvariabelen voor het verwerken van **applicatie instellingen** vind je in de [Geavanceerde gebruikershandleiding - Instellingen en Omgevingsvariabelen](./advanced/settings.md){.internal-link target=_blank}. + +## `PATH` Omgevingsvariabele + +Er is een **speciale** omgevingsvariabele met de naam **`PATH`**, die door de besturingssystemen (Linux, macOS, Windows) wordt gebruikt om programma's te vinden die uitgevoerd kunnen worden. + +De waarde van de variabele `PATH` is een lange string die bestaat uit mappen die gescheiden worden door een dubbele punt `:` op Linux en macOS en door een puntkomma `;` op Windows. + +De omgevingsvariabele `PATH` zou er bijvoorbeeld zo uit kunnen zien: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Dit betekent dat het systeem naar programma's zoekt in de mappen: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Dit betekent dat het systeem naar programma's zoekt in de mappen: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Wanneer je een **opdracht** in de terminal typt, **zoekt** het besturingssysteem naar het programma in **elk van de mappen** die vermeld staan in de omgevingsvariabele `PATH`. + +Wanneer je bijvoorbeeld `python` in de terminal typt, zoekt het besturingssysteem naar een programma met de naam `python` in de **eerste map** in die lijst. + +Zodra het gevonden wordt, zal het dat programma **gebruiken**. Anders blijft het in de **andere mappen** zoeken. + +### Python installeren en `PATH` bijwerken + +Wanneer je Python installeert, word je mogelijk gevraagd of je de omgevingsvariabele `PATH` wilt bijwerken. + +//// tab | Linux, macOS + +Stel dat je Python installeert en het komt terecht in de map `/opt/custompython/bin`. + +Als je kiest om de `PATH` omgevingsvariabele bij te werken, zal het installatieprogramma `/opt/custompython/bin` toevoegen aan de `PATH` omgevingsvariabele. + +Dit zou er zo uit kunnen zien: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Op deze manier zal het systeem, wanneer je `python` in de terminal typt, het Python-programma in `/opt/custompython/bin` (de laatste map) vinden en dat gebruiken. + +//// + +//// tab | Windows + +Stel dat je Python installeert en het komt terecht in de map `C:\opt\custompython\bin`. + +Als je kiest om de `PATH` omgevingsvariabele bij te werken, zal het installatieprogramma `C:\opt\custompython\bin` toevoegen aan de `PATH` omgevingsvariabele. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Op deze manier zal het systeem, wanneer je `python` in de terminal typt, het Python-programma in `C:\opt\custompython\bin` (de laatste map) vinden en dat gebruiken. + +//// + +Dus als je typt: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +Zal het systeem het `python`-programma in `/opt/custompython/bin` **vinden** en uitvoeren. + +Het zou ongeveer hetzelfde zijn als het typen van: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +Zal het systeem het `python`-programma in `C:\opt\custompython\bin\python` **vinden** en uitvoeren. + +Het zou ongeveer hetzelfde zijn als het typen van: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +Deze informatie is handig wanneer je meer wilt weten over [virtuele omgevingen](virtual-environments.md){.internal-link target=_blank}. + +## Conclusion + +Hiermee heb je basiskennis van wat **omgevingsvariabelen** zijn en hoe je ze in Python kunt gebruiken. + +Je kunt er ook meer over lezen op de Wikipedia over omgevingsvariabelen. + +In veel gevallen is het niet direct duidelijk hoe omgevingsvariabelen nuttig zijn en hoe je ze moet toepassen. Maar ze blijven in veel verschillende scenario's opduiken als je aan het ontwikkelen bent, dus het is goed om er meer over te weten. + +Je hebt deze informatie bijvoorbeeld nodig in de volgende sectie, over [Virtuele Omgevingen](virtual-environments.md). diff --git a/docs/nl/docs/features.md b/docs/nl/docs/features.md new file mode 100644 index 000000000..848b155ec --- /dev/null +++ b/docs/nl/docs/features.md @@ -0,0 +1,201 @@ +# Functionaliteit + +## FastAPI functionaliteit + +**FastAPI** biedt je het volgende: + +### Gebaseerd op open standaarden + +* OpenAPI voor het maken van API's, inclusief declaraties van padbewerkingen, parameters, request bodies, beveiliging, enz. +* Automatische datamodel documentatie met JSON Schema (aangezien OpenAPI zelf is gebaseerd op JSON Schema). +* Ontworpen op basis van deze standaarden, na zorgvuldig onderzoek. In plaats van achteraf deze laag er bovenop te bouwen. +* Dit maakt het ook mogelijk om automatisch **clientcode te genereren** in verschillende programmeertalen. + +### Automatische documentatie + +Interactieve API-documentatie en verkenning van webgebruikersinterfaces. Aangezien dit framework is gebaseerd op OpenAPI, zijn er meerdere documentatie opties mogelijk, waarvan er standaard 2 zijn inbegrepen. + +* Swagger UI, met interactieve interface, maakt het mogelijk je API rechtstreeks vanuit de browser aan te roepen en te testen. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Alternatieve API-documentatie met ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Gewoon Moderne Python + +Het is allemaal gebaseerd op standaard **Python type** declaraties (dankzij Pydantic). Je hoeft dus geen nieuwe syntax te leren. Het is gewoon standaard moderne Python. + +Als je een opfriscursus van 2 minuten nodig hebt over het gebruik van Python types (zelfs als je FastAPI niet gebruikt), bekijk dan deze korte tutorial: [Python Types](python-types.md){.internal-link target=_blank}. + +Je schrijft gewoon standaard Python met types: + +```Python +from datetime import date + +from pydantic import BaseModel + +# Declareer een variabele als een str +# en krijg editorondersteuning in de functie +def main(user_id: str): + return user_id + + +# Een Pydantic model +class User(BaseModel): + id: int + name: str + joined: date +``` + +Vervolgens kan je het op deze manier gebruiken: + +```Python +my_user: User = User(id=3, name="John Doe", joined="2018-07-19") + +second_user_data = { + "id": 4, + "name": "Mary", + "joined": "2018-11-30", +} + +my_second_user: User = User(**second_user_data) +``` + +/// info + +`**second_user_data` betekent: + +Geef de sleutels (keys) en waarden (values) van de `second_user_data` dict direct door als sleutel-waarden argumenten, gelijk aan: `User(id=4, name=“Mary”, joined=“2018-11-30”)` + +/// + +### Editor-ondersteuning + +Het gehele framework is ontworpen om eenvoudig en intuïtief te zijn in gebruik. Alle beslissingen zijn getest op meerdere code-editors nog voordat het daadwerkelijke ontwikkelen begon, om zo de beste ontwikkelervaring te garanderen. + +Uit enquêtes onder Python ontwikkelaars blijkt maar al te duidelijk dat "(automatische) code aanvulling" een van de meest gebruikte functionaliteiten is. + +Het hele **FastAPI** framework is daarop gebaseerd. Automatische code aanvulling werkt overal. + +Je hoeft zelden terug te vallen op de documentatie. + +Zo kan je editor je helpen: + +* in Visual Studio Code: + +![editor ondersteuning](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* in PyCharm: + +![editor ondersteuning](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +Je krijgt autocomletion die je voorheen misschien zelfs voor onmogelijk had gehouden. Zoals bijvoorbeeld de `price` key in een JSON body (die genest had kunnen zijn) die afkomstig is van een request. + +Je hoeft niet langer de verkeerde keys in te typen, op en neer te gaan tussen de documentatie, of heen en weer te scrollen om te checken of je `username` of toch `user_name` had gebruikt. + +### Kort + +Dit framework heeft voor alles verstandige **standaardinstellingen**, met overal optionele configuraties. Alle parameters kunnen worden verfijnd zodat het past bij wat je nodig hebt, om zo de API te kunnen definiëren die jij nodig hebt. + +Maar standaard werkt alles **“gewoon”**. + +### Validatie + +* Validatie voor de meeste (of misschien wel alle?) Python **datatypes**, inclusief: + * JSON objecten (`dict`). + * JSON array (`list`) die itemtypes definiëren. + * String (`str`) velden, die min en max lengtes hebben. + * Getallen (`int`, `float`) met min en max waarden, enz. + +* Validatie voor meer exotische typen, zoals: + * URL. + * E-mail. + * UUID. + * ...en anderen. + +Alle validatie wordt uitgevoerd door het beproefde en robuuste **Pydantic**. + +### Beveiliging en authenticatie + +Beveiliging en authenticatie is geïntegreerd. Zonder compromissen te doen naar databases of datamodellen. + +Alle beveiligingsschema's gedefinieerd in OpenAPI, inclusief: + +* HTTP Basic. +* **OAuth2** (ook met **JWT tokens**). Bekijk de tutorial over [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* API keys in: + * Headers. + * Query parameters. + * Cookies, enz. + +Plus alle beveiligingsfuncties van Starlette (inclusief **sessiecookies**). + +Gebouwd als een herbruikbare tool met componenten die makkelijk te integreren zijn in en met je systemen, datastores, relationele en NoSQL databases, enz. + +### Dependency Injection + +FastAPI bevat een uiterst eenvoudig, maar uiterst krachtig Dependency Injection systeem. + +* Zelfs dependencies kunnen dependencies hebben, waardoor een hiërarchie of **“graph” van dependencies** ontstaat. +* Allemaal **automatisch afgehandeld** door het framework. +* Alle dependencies kunnen data nodig hebben van request, de vereiste **padoperaties veranderen** en automatische documentatie verstrekken. +* **Automatische validatie** zelfs voor *padoperatie* parameters gedefinieerd in dependencies. +* Ondersteuning voor complexe gebruikersauthenticatiesystemen, **databaseverbindingen**, enz. +* **Geen compromisen** met databases, gebruikersinterfaces, enz. Maar eenvoudige integratie met ze allemaal. + +### Ongelimiteerde "plug-ins" + +Of anders gezegd, je hebt ze niet nodig, importeer en gebruik de code die je nodig hebt. + +Elke integratie is ontworpen om eenvoudig te gebruiken (met afhankelijkheden), zodat je een “plug-in" kunt maken in 2 regels code, met dezelfde structuur en syntax die wordt gebruikt voor je *padbewerkingen*. + +### Getest + +* 100% van de code is getest. +* 100% type geannoteerde codebase. +* Wordt gebruikt in productietoepassingen. + +## Starlette functies + +**FastAPI** is volledig verenigbaar met (en gebaseerd op) Starlette. + +`FastAPI` is eigenlijk een subklasse van `Starlette`. Dus als je Starlette al kent of gebruikt, zal de meeste functionaliteit op dezelfde manier werken. + +Met **FastAPI** krijg je alle functies van **Starlette** (FastAPI is gewoon Starlette op steroïden): + +* Zeer indrukwekkende prestaties. Het is een van de snelste Python frameworks, vergelijkbaar met **NodeJS** en **Go**. +* **WebSocket** ondersteuning. +* Taken in de achtergrond tijdens het proces. +* Opstart- en afsluit events. +* Test client gebouwd op HTTPX. +* **CORS**, GZip, Statische bestanden, Streaming reacties. +* **Sessie en Cookie** ondersteuning. +* 100% van de code is getest. +* 100% type geannoteerde codebase. + +## Pydantic functionaliteit + +**FastAPI** is volledig verenigbaar met (en gebaseerd op) Pydantic. Dus alle extra Pydantic code die je nog hebt werkt ook. + +Inclusief externe pakketten die ook gebaseerd zijn op Pydantic, zoals ORMs, ODMs voor databases. + +Dit betekent ook dat je in veel gevallen het object dat je van een request krijgt **direct naar je database** kunt sturen, omdat alles automatisch wordt gevalideerd. + +Hetzelfde geldt ook andersom, in veel gevallen kun je dus het object dat je krijgt van de database **direct doorgeven aan de client**. + +Met **FastAPI** krijg je alle functionaliteit van **Pydantic** (omdat FastAPI is gebaseerd op Pydantic voor alle dataverwerking): + +* **Geen brainfucks**: + * Je hoeft geen nieuwe microtaal voor schemadefinities te leren. + * Als je bekend bent Python types, weet je hoe je Pydantic moet gebruiken. +* Werkt goed samen met je **IDE/linter/hersenen**: + * Doordat pydantic's datastructuren enkel instanties zijn van klassen, die je definieert, werkt automatische aanvulling, linting, mypy en je intuïtie allemaal goed met je gevalideerde data. +* Valideer **complexe structuren**: + * Gebruik van hiërarchische Pydantic modellen, Python `typing`'s `List` en `Dict`, enz. + * Met validators kunnen complexe dataschema's duidelijk en eenvoudig worden gedefinieerd, gecontroleerd en gedocumenteerd als JSON Schema. + * Je kunt diep **geneste JSON** objecten laten valideren en annoteren. +* **Uitbreidbaar**: + * Met Pydantic kunnen op maat gemaakte datatypen worden gedefinieerd of je kunt validatie uitbreiden met methoden op een model dat is ingericht met de decorator validator. +* 100% van de code is getest. diff --git a/docs/nl/docs/index.md b/docs/nl/docs/index.md new file mode 100644 index 000000000..d88bb7771 --- /dev/null +++ b/docs/nl/docs/index.md @@ -0,0 +1,494 @@ +# FastAPI + + + +

+ FastAPI +

+

+ FastAPI framework, zeer goede prestaties, eenvoudig te leren, snel te programmeren, klaar voor productie +

+

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**Documentatie**: https://fastapi.tiangolo.com + +**Broncode**: https://github.com/tiangolo/fastapi + +--- + +FastAPI is een modern, snel (zeer goede prestaties), web framework voor het bouwen van API's in Python, gebruikmakend van standaard Python type-hints. + +De belangrijkste kenmerken zijn: + +* **Snel**: Zeer goede prestaties, vergelijkbaar met **NodeJS** en **Go** (dankzij Starlette en Pydantic). [Een van de snelste beschikbare Python frameworks](#prestaties). +* **Snel te programmeren**: Verhoog de snelheid om functionaliteit te ontwikkelen met ongeveer 200% tot 300%. * +* **Minder bugs**: Verminder ongeveer 40% van de door mensen (ontwikkelaars) veroorzaakte fouten. * +* **Intuïtief**: Buitengewoon goede ondersteuning voor editors. Overal automische code aanvulling. Minder tijd kwijt aan debuggen. +* **Eenvoudig**: Ontworpen om gemakkelijk te gebruiken en te leren. Minder tijd nodig om documentatie te lezen. +* **Kort**: Minimaliseer codeduplicatie. Elke parameterdeclaratie ondersteunt meerdere functionaliteiten. Minder bugs. +* **Robust**: Code gereed voor productie. Met automatische interactieve documentatie. +* **Standards-based**: Gebaseerd op (en volledig verenigbaar met) open standaarden voor API's: OpenAPI (voorheen bekend als Swagger) en JSON Schema. + +* schatting op basis van testen met een intern ontwikkelteam en bouwen van productieapplicaties. + +## Sponsors + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Overige sponsoren + +## Meningen + +"_[...] Ik gebruik **FastAPI** heel vaak tegenwoordig. [...] Ik ben van plan om het te gebruiken voor alle **ML-services van mijn team bij Microsoft**. Sommige van deze worden geïntegreerd in het kernproduct van **Windows** en sommige **Office**-producten._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We hebben de **FastAPI** library gebruikt om een **REST** server te maken die bevraagd kan worden om **voorspellingen** te maken. [voor Ludwig]_" + +
Piero Molino, Yaroslav Dudin en Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** is verheugd om een open-source release aan te kondigen van ons **crisismanagement**-orkestratieframework: **Dispatch**! [gebouwd met **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_Ik ben super enthousiast over **FastAPI**. Het is zo leuk!_" + +
Brian Okken - Python Bytes podcast presentator (ref)
+ +--- + +"_Wat je hebt gebouwd ziet er echt super solide en gepolijst uit. In veel opzichten is het wat ik wilde dat **Hug** kon zijn - het is echt inspirerend om iemand dit te zien bouwen._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"Wie geïnteresseerd is in een **modern framework** voor het bouwen van REST API's, bekijkt best eens **FastAPI** [...] Het is snel, gebruiksvriendelijk en gemakkelijk te leren [...]_" + +"_We zijn overgestapt naar **FastAPI** voor onze **API's** [...] Het gaat jou vast ook bevallen [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI oprichters - spaCy ontwikkelaars (ref) - (ref)
+ +--- + +"_Wie een Python API wil bouwen voor productie, kan ik ten stelligste **FastAPI** aanraden. Het is **prachtig ontworpen**, **eenvoudig te gebruiken** en **gemakkelijk schaalbaar**, het is een **cruciale component** geworden in onze strategie om API's centraal te zetten, en het vereenvoudigt automatisering en diensten zoals onze Virtual TAC Engineer._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, de FastAPI van CLIs + + + +Als je een CLI-app bouwt die in de terminal moet worden gebruikt in plaats van een web-API, gebruik dan **Typer**. + +**Typer** is het kleine broertje van FastAPI. En het is bedoeld als de **FastAPI van CLI's**. ️ + +## Vereisten + +FastAPI staat op de schouders van reuzen: + +* Starlette voor de webonderdelen. +* Pydantic voor de datadelen. + +## Installatie + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +**Opmerking**: Zet `"fastapi[standard]"` tussen aanhalingstekens om ervoor te zorgen dat het werkt in alle terminals. + +## Voorbeeld + +### Creëer het + +* Maak het bestand `main.py` aan met daarin: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+Of maak gebruik van async def... + +Als je code gebruik maakt van `async` / `await`, gebruik dan `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Opmerking**: + +Als je het niet weet, kijk dan in het gedeelte _"Heb je haast?"_ over `async` en `await` in de documentatie. + +
+ +### Voer het uit + +Run de server met: + +
+ +```console +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+Over het commando fastapi dev main.py... + +Het commando `fastapi dev` leest het `main.py` bestand, detecteert de **FastAPI** app, en start een server met Uvicorn. + +Standaard zal dit commando `fastapi dev` starten met "auto-reload" geactiveerd voor ontwikkeling op het lokale systeem. + +Je kan hier meer over lezen in de FastAPI CLI documentatie. + +
+ +### Controleer het + +Open je browser op http://127.0.0.1:8000/items/5?q=somequery. + +Je zult een JSON response zien: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Je hebt een API gemaakt die: + +* HTTP verzoeken kan ontvangen op de _paden_ `/` en `/items/{item_id}`. +* Beide _paden_ hebben `GET` operaties (ook bekend als HTTP _methoden_). +* Het _pad_ `/items/{item_id}` heeft een _pad parameter_ `item_id` dat een `int` moet zijn. +* Het _pad_ `/items/{item_id}` heeft een optionele `str` _query parameter_ `q`. + +### Interactieve API documentatie + +Ga naar http://127.0.0.1:8000/docs. + +Je ziet de automatische interactieve API documentatie (verstrekt door Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternatieve API documentatie + +Ga vervolgens naar http://127.0.0.1:8000/redoc. + +Je ziet de automatische interactieve API documentatie (verstrekt door ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Voorbeeld upgrade + +Pas nu het bestand `main.py` aan om de body van een `PUT` request te ontvangen. + +Dankzij Pydantic kunnen we de body declareren met standaard Python types. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +De `fastapi dev` server zou automatisch moeten herladen. + +### Interactieve API documentatie upgrade + +Ga nu naar http://127.0.0.1:8000/docs. + +* De interactieve API-documentatie wordt automatisch bijgewerkt, inclusief de nieuwe body: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Klik op de knop "Try it out", hiermee kan je de parameters invullen en direct met de API interacteren: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Klik vervolgens op de knop "Execute", de gebruikersinterface zal communiceren met jouw API, de parameters verzenden, de resultaten ophalen en deze op het scherm tonen: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternatieve API documentatie upgrade + +Ga vervolgens naar http://127.0.0.1:8000/redoc. + +* De alternatieve documentatie zal ook de nieuwe queryparameter en body weergeven: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Samenvatting + +Samengevat declareer je **eenmalig** de types van parameters, body, etc. als functieparameters. + +Dat doe je met standaard moderne Python types. + +Je hoeft geen nieuwe syntax te leren, de methods of klassen van een specifieke bibliotheek, etc. + +Gewoon standaard **Python**. + +Bijvoorbeeld, voor een `int`: + +```Python +item_id: int +``` + +of voor een complexer `Item` model: + +```Python +item: Item +``` + +...en met die ene verklaring krijg je: + +* Editor ondersteuning, inclusief: + * Code aanvulling. + * Type validatie. +* Validatie van data: + * Automatische en duidelijke foutboodschappen wanneer de data ongeldig is. + * Validatie zelfs voor diep geneste JSON objecten. +* Conversie van invoergegevens: afkomstig van het netwerk naar Python-data en -types. Zoals: + * JSON. + * Pad parameters. + * Query parameters. + * Cookies. + * Headers. + * Formulieren. + * Bestanden. +* Conversie van uitvoergegevens: converstie van Python-data en -types naar netwerkgegevens (zoals JSON): + * Converteer Python types (`str`, `int`, `float`, `bool`, `list`, etc). + * `datetime` objecten. + * `UUID` objecten. + * Database modellen. + * ...en nog veel meer. +* Automatische interactieve API-documentatie, inclusief 2 alternatieve gebruikersinterfaces: + * Swagger UI. + * ReDoc. + +--- + +Terugkomend op het vorige code voorbeeld, **FastAPI** zal: + +* Valideren dat er een `item_id` bestaat in het pad voor `GET` en `PUT` verzoeken. +* Valideren dat het `item_id` van het type `int` is voor `GET` en `PUT` verzoeken. + * Wanneer dat niet het geval is, krijgt de cliënt een nuttige, duidelijke foutmelding. +* Controleren of er een optionele query parameter is met de naam `q` (zoals in `http://127.0.0.1:8000/items/foo?q=somequery`) voor `GET` verzoeken. + * Aangezien de `q` parameter werd gedeclareerd met `= None`, is deze optioneel. + * Zonder de `None` declaratie zou deze verplicht zijn (net als bij de body in het geval met `PUT`). +* Voor `PUT` verzoeken naar `/items/{item_id}`, lees de body als JSON: + * Controleer of het een verplicht attribuut `naam` heeft en dat dat een `str` is. + * Controleer of het een verplicht attribuut `price` heeft en dat dat een`float` is. + * Controleer of het een optioneel attribuut `is_offer` heeft, dat een `bool` is wanneer het aanwezig is. + * Dit alles werkt ook voor diep geneste JSON objecten. +* Converteer automatisch van en naar JSON. +* Documenteer alles met OpenAPI, dat gebruikt kan worden door: + * Interactieve documentatiesystemen. + * Automatische client code generatie systemen, voor vele talen. +* Biedt 2 interactieve documentatie-webinterfaces aan. + +--- + +Dit was nog maar een snel overzicht, maar je zou nu toch al een idee moeten hebben over hoe het allemaal werkt. + +Probeer deze regel te veranderen: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...van: + +```Python + ... "item_name": item.name ... +``` + +...naar: + +```Python + ... "item_price": item.price ... +``` + +...en zie hoe je editor de attributen automatisch invult en hun types herkent: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Voor een vollediger voorbeeld met meer mogelijkheden, zie de Tutorial - Gebruikershandleiding. + +**Spoiler alert**: de tutorial - gebruikershandleiding bevat: + +* Declaratie van **parameters** op andere plaatsen zoals: **headers**, **cookies**, **formuliervelden** en **bestanden**. +* Hoe stel je **validatie restricties** in zoals `maximum_length` of een `regex`. +* Een zeer krachtig en eenvoudig te gebruiken **Dependency Injection** systeem. +* Beveiliging en authenticatie, inclusief ondersteuning voor **OAuth2** met **JWT-tokens** en **HTTP Basic** auth. +* Meer geavanceerde (maar even eenvoudige) technieken voor het declareren van **diep geneste JSON modellen** (dankzij Pydantic). +* **GraphQL** integratie met Strawberry en andere packages. +* Veel extra functies (dankzij Starlette) zoals: + * **WebSockets** + * uiterst gemakkelijke tests gebaseerd op HTTPX en `pytest` + * **CORS** + * **Cookie Sessions** + * ...en meer. + +## Prestaties + +Onafhankelijke TechEmpower benchmarks tonen **FastAPI** applicaties draaiend onder Uvicorn aan als een van de snelste Python frameworks beschikbaar, alleen onder Starlette en Uvicorn zelf (intern gebruikt door FastAPI). (*) + +Zie de sectie Benchmarks om hier meer over te lezen. + +## Afhankelijkheden + +FastAPI maakt gebruik van Pydantic en Starlette. + +### `standard` Afhankelijkheden + +Wanneer je FastAPI installeert met `pip install "fastapi[standard]"`, worden de volgende `standard` optionele afhankelijkheden geïnstalleerd: + +Gebruikt door Pydantic: + +* email_validator - voor email validatie. + +Gebruikt door Starlette: + +* httpx - Vereist indien je de `TestClient` wil gebruiken. +* jinja2 - Vereist als je de standaard templateconfiguratie wil gebruiken. +* python-multipart - Vereist indien je "parsen" van formulieren wil ondersteunen met `requests.form()`. + +Gebruikt door FastAPI / Starlette: + +* uvicorn - voor de server die jouw applicatie laadt en bedient. +* `fastapi-cli` - om het `fastapi` commando te voorzien. + +### Zonder `standard` Afhankelijkheden + +Indien je de optionele `standard` afhankelijkheden niet wenst te installeren, kan je installeren met `pip install fastapi` in plaats van `pip install "fastapi[standard]"`. + +### Bijkomende Optionele Afhankelijkheden + +Er zijn nog een aantal bijkomende afhankelijkheden die je eventueel kan installeren. + +Bijkomende optionele afhankelijkheden voor Pydantic: + +* pydantic-settings - voor het beheren van settings. +* pydantic-extra-types - voor extra data types die gebruikt kunnen worden met Pydantic. + +Bijkomende optionele afhankelijkheden voor FastAPI: + +* orjson - Vereist indien je `ORJSONResponse` wil gebruiken. +* ujson - Vereist indien je `UJSONResponse` wil gebruiken. + +## Licentie + +Dit project is gelicenseerd onder de voorwaarden van de MIT licentie. diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md new file mode 100644 index 000000000..00052037c --- /dev/null +++ b/docs/nl/docs/python-types.md @@ -0,0 +1,597 @@ +# Introductie tot Python Types + +Python biedt ondersteuning voor optionele "type hints" (ook wel "type annotaties" genoemd). + +Deze **"type hints"** of annotaties zijn een speciale syntax waarmee het type van een variabele kan worden gedeclareerd. + +Door types voor je variabelen te declareren, kunnen editors en hulpmiddelen je beter ondersteunen. + +Dit is slechts een **korte tutorial/opfrisser** over Python type hints. Het behandelt enkel het minimum dat nodig is om ze te gebruiken met **FastAPI**... en dat is relatief weinig. + +**FastAPI** is helemaal gebaseerd op deze type hints, ze geven veel voordelen. + +Maar zelfs als je **FastAPI** nooit gebruikt, heb je er baat bij om er iets over te leren. + +/// note + +Als je een Python expert bent en alles al weet over type hints, sla dan dit hoofdstuk over. + +/// + +## Motivatie + +Laten we beginnen met een eenvoudig voorbeeld: + +```Python +{!../../docs_src/python_types/tutorial001.py!} +``` + +Het aanroepen van dit programma leidt tot het volgende resultaat: + +``` +John Doe +``` + +De functie voert het volgende uit: + +* Neem een `first_name` en een `last_name` +* Converteer de eerste letter van elk naar een hoofdletter met `title()`. +`` +* Voeg samen met een spatie in het midden. + +```Python hl_lines="2" +{!../../docs_src/python_types/tutorial001.py!} +``` + +### Bewerk het + +Dit is een heel eenvoudig programma. + +Maar stel je nu voor dat je het vanaf nul zou moeten maken. + +Op een gegeven moment zou je aan de definitie van de functie zijn begonnen, je had de parameters klaar... + +Maar dan moet je “die methode die de eerste letter naar hoofdletters converteert” aanroepen. + +Was het `upper`? Was het `uppercase`? `first_uppercase`? `capitalize`? + +Dan roep je de hulp in van je oude programmeursvriend, (automatische) code aanvulling in je editor. + +Je typt de eerste parameter van de functie, `first_name`, dan een punt (`.`) en drukt dan op `Ctrl+Spatie` om de aanvulling te activeren. + +Maar helaas krijg je niets bruikbaars: + + + +### Types toevoegen + +Laten we een enkele regel uit de vorige versie aanpassen. + +We zullen precies dit fragment, de parameters van de functie, wijzigen van: + +```Python + first_name, last_name +``` + +naar: + +```Python + first_name: str, last_name: str +``` + +Dat is alles. + +Dat zijn de "type hints": + +```Python hl_lines="1" +{!../../docs_src/python_types/tutorial002.py!} +``` + +Dit is niet hetzelfde als het declareren van standaardwaarden zoals bij: + +```Python + first_name="john", last_name="doe" +``` + +Het is iets anders. + +We gebruiken dubbele punten (`:`), geen gelijkheidstekens (`=`). + +Het toevoegen van type hints verandert normaal gesproken niet wat er gebeurt in je programma t.o.v. wat er zonder type hints zou gebeuren. + +Maar stel je voor dat je weer bezig bent met het maken van een functie, maar deze keer met type hints. + +Op hetzelfde moment probeer je de automatische aanvulling te activeren met `Ctrl+Spatie` en je ziet: + + + +Nu kun je de opties bekijken en er doorheen scrollen totdat je de optie vindt die “een belletje doet rinkelen”: + + + +### Meer motivatie + +Bekijk deze functie, deze heeft al type hints: + +```Python hl_lines="1" +{!../../docs_src/python_types/tutorial003.py!} +``` + +Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling, maar ook controles op fouten: + + + +Nu weet je hoe je het moet oplossen, converteer `age` naar een string met `str(age)`: + +```Python hl_lines="2" +{!../../docs_src/python_types/tutorial004.py!} +``` + +## Types declareren + +Je hebt net de belangrijkste plek om type hints te declareren gezien. Namelijk als functieparameters. + +Dit is ook de belangrijkste plek waar je ze gebruikt met **FastAPI**. + +### Eenvoudige types + +Je kunt alle standaard Python types declareren, niet alleen `str`. + +Je kunt bijvoorbeeld het volgende gebruiken: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../docs_src/python_types/tutorial005.py!} +``` + +### Generieke types met typeparameters + +Er zijn enkele datastructuren die andere waarden kunnen bevatten, zoals `dict`, `list`, `set` en `tuple` en waar ook de interne waarden hun eigen type kunnen hebben. + +Deze types die interne types hebben worden “**generieke**” types genoemd. Het is mogelijk om ze te declareren, zelfs met hun interne types. + +Om deze types en de interne types te declareren, kun je de standaard Python module `typing` gebruiken. Deze module is speciaal gemaakt om deze type hints te ondersteunen. + +#### Nieuwere versies van Python + +De syntax met `typing` is **verenigbaar** met alle versies, van Python 3.6 tot aan de nieuwste, inclusief Python 3.9, Python 3.10, enz. + +Naarmate Python zich ontwikkelt, worden **nieuwere versies**, met verbeterde ondersteuning voor deze type annotaties, beschikbaar. In veel gevallen hoef je niet eens de `typing` module te importeren en te gebruiken om de type annotaties te declareren. + +Als je een recentere versie van Python kunt kiezen voor je project, kun je profiteren van die extra eenvoud. + +In alle documentatie staan voorbeelden die compatibel zijn met elke versie van Python (als er een verschil is). + +Bijvoorbeeld “**Python 3.6+**” betekent dat het compatibel is met Python 3.6 of hoger (inclusief 3.7, 3.8, 3.9, 3.10, etc). En “**Python 3.9+**” betekent dat het compatibel is met Python 3.9 of hoger (inclusief 3.10, etc). + +Als je de **laatste versies van Python** kunt gebruiken, gebruik dan de voorbeelden voor de laatste versie, die hebben de **beste en eenvoudigste syntax**, bijvoorbeeld “**Python 3.10+**”. + +#### List + +Laten we bijvoorbeeld een variabele definiëren als een `list` van `str`. + +//// tab | Python 3.9+ + +Declareer de variabele met dezelfde dubbele punt (`:`) syntax. + +Als type, vul `list` in. + +Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes: + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +Van `typing`, importeer `List` (met een hoofdletter `L`): + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +Declareer de variabele met dezelfde dubbele punt (`:`) syntax. + +Zet als type de `List` die je hebt geïmporteerd uit `typing`. + +Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes: + +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +//// + +/// info + +De interne types tussen vierkante haakjes worden “typeparameters” genoemd. + +In dit geval is `str` de typeparameter die wordt doorgegeven aan `List` (of `list` in Python 3.9 en hoger). + +/// + +Dat betekent: “de variabele `items` is een `list`, en elk van de items in deze list is een `str`”. + +/// tip + +Als je Python 3.9 of hoger gebruikt, hoef je `List` niet te importeren uit `typing`, je kunt in plaats daarvan hetzelfde reguliere `list` type gebruiken. + +/// + +Door dat te doen, kan je editor ondersteuning bieden, zelfs tijdens het verwerken van items uit de list: + + + +Zonder types is dat bijna onmogelijk om te bereiken. + +Merk op dat de variabele `item` een van de elementen is in de lijst `items`. + +Toch weet de editor dat het een `str` is, en biedt daar vervolgens ondersteuning voor aan. + +#### Tuple en Set + +Je kunt hetzelfde doen om `tuple`s en `set`s te declareren: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` + +//// + +Dit betekent: + +* De variabele `items_t` is een `tuple` met 3 items, een `int`, nog een `int`, en een `str`. +* De variabele `items_s` is een `set`, en elk van de items is van het type `bytes`. + +#### Dict + +Om een `dict` te definiëren, geef je 2 typeparameters door, gescheiden door komma's. + +De eerste typeparameter is voor de sleutels (keys) van de `dict`. + +De tweede typeparameter is voor de waarden (values) van het `dict`: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// + +Dit betekent: + +* De variabele `prices` is een `dict`: + * De sleutels van dit `dict` zijn van het type `str` (bijvoorbeeld de naam van elk item). + * De waarden van dit `dict` zijn van het type `float` (bijvoorbeeld de prijs van elk item). + +#### Union + +Je kunt een variable declareren die van **verschillende types** kan zijn, bijvoorbeeld een `int` of een `str`. + +In Python 3.6 en hoger (inclusief Python 3.10) kun je het `Union`-type van `typing` gebruiken en de mogelijke types die je wilt accepteren, tussen de vierkante haakjes zetten. + +In Python 3.10 is er ook een **nieuwe syntax** waarin je de mogelijke types kunt scheiden door een verticale balk (`|`). + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +In beide gevallen betekent dit dat `item` een `int` of een `str` kan zijn. + +#### Mogelijk `None` + +Je kunt declareren dat een waarde een type kan hebben, zoals `str`, maar dat het ook `None` kan zijn. + +In Python 3.6 en hoger (inclusief Python 3.10) kun je het declareren door `Optional` te importeren en te gebruiken vanuit de `typing`-module. + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009.py!} +``` + +Door `Optional[str]` te gebruiken in plaats van alleen `str`, kan de editor je helpen fouten te detecteren waarbij je ervan uit zou kunnen gaan dat een waarde altijd een `str` is, terwijl het in werkelijkheid ook `None` zou kunnen zijn. + +`Optional[EenType]` is eigenlijk een snelkoppeling voor `Union[EenType, None]`, ze zijn equivalent. + +Dit betekent ook dat je in Python 3.10 `EenType | None` kunt gebruiken: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### Gebruik van `Union` of `Optional` + +Als je een Python versie lager dan 3.10 gebruikt, is dit een tip vanuit mijn **subjectieve** standpunt: + +* 🚨 Vermijd het gebruik van `Optional[EenType]`. +* Gebruik in plaats daarvan **`Union[EenType, None]`** ✨. + +Beide zijn gelijkwaardig en onderliggend zijn ze hetzelfde, maar ik zou `Union` aanraden in plaats van `Optional` omdat het woord “**optional**” lijkt te impliceren dat de waarde optioneel is, en het eigenlijk betekent “het kan `None` zijn”, zelfs als het niet optioneel is en nog steeds vereist is. + +Ik denk dat `Union[SomeType, None]` explicieter is over wat het betekent. + +Het gaat alleen om de woorden en naamgeving. Maar die naamgeving kan invloed hebben op hoe jij en je teamgenoten over de code denken. + +Laten we als voorbeeld deze functie nemen: + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009c.py!} +``` + +De parameter `name` is gedefinieerd als `Optional[str]`, maar is **niet optioneel**, je kunt de functie niet aanroepen zonder de parameter: + +```Python +say_hi() # Oh, nee, dit geeft een foutmelding! 😱 +``` + +De `name` parameter is **nog steeds vereist** (niet *optioneel*) omdat het geen standaardwaarde heeft. Toch accepteert `name` `None` als waarde: + +```Python +say_hi(name=None) # Dit werkt, None is geldig 🎉 +``` + +Het goede nieuws is dat als je eenmaal Python 3.10 gebruikt, je je daar geen zorgen meer over hoeft te maken, omdat je dan gewoon `|` kunt gebruiken om unions van types te definiëren: + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009c_py310.py!} +``` + +Dan hoef je je geen zorgen te maken over namen als `Optional` en `Union`. 😎 + +#### Generieke typen + +De types die typeparameters in vierkante haakjes gebruiken, worden **Generieke types** of **Generics** genoemd, bijvoorbeeld: + +//// tab | Python 3.10+ + +Je kunt dezelfde ingebouwde types gebruiken als generics (met vierkante haakjes en types erin): + +* `list` +* `tuple` +* `set` +* `dict` + +Hetzelfde als bij Python 3.8, uit de `typing`-module: + +* `Union` +* `Optional` (hetzelfde als bij Python 3.8) +* ...en anderen. + +In Python 3.10 kun je , als alternatief voor de generieke `Union` en `Optional`, de verticale lijn (`|`) gebruiken om unions van typen te voorzien, dat is veel beter en eenvoudiger. + +//// + +//// tab | Python 3.9+ + +Je kunt dezelfde ingebouwde types gebruiken als generieke types (met vierkante haakjes en types erin): + +* `list` +* `tuple` +* `set` +* `dict` + +En hetzelfde als met Python 3.8, vanuit de `typing`-module: + +* `Union` +* `Optional` +* ...en anderen. + +//// + +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...en anderen. + +//// + +### Klassen als types + +Je kunt een klasse ook declareren als het type van een variabele. + +Stel dat je een klasse `Person` hebt, met een naam: + +```Python hl_lines="1-3" +{!../../docs_src/python_types/tutorial010.py!} +``` + +Vervolgens kun je een variabele van het type `Persoon` declareren: + +```Python hl_lines="6" +{!../../docs_src/python_types/tutorial010.py!} +``` + +Dan krijg je ook nog eens volledige editorondersteuning: + + + +Merk op dat dit betekent dat "`one_person` een **instantie** is van de klasse `Person`". + +Dit betekent niet dat `one_person` de **klasse** is met de naam `Person`. + +## Pydantic modellen + +Pydantic is een Python-pakket voor het uitvoeren van datavalidatie. + +Je declareert de "vorm" van de data als klassen met attributen. + +Elk attribuut heeft een type. + +Vervolgens maak je een instantie van die klasse met een aantal waarden en het valideert de waarden, converteert ze naar het juiste type (als dat het geval is) en geeft je een object met alle data terug. + +Daarnaast krijg je volledige editorondersteuning met dat resulterende object. + +Een voorbeeld uit de officiële Pydantic-documentatie: + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info + +Om meer te leren over Pydantic, bekijk de documentatie. + +/// + +**FastAPI** is volledig gebaseerd op Pydantic. + +Je zult veel meer van dit alles in de praktijk zien in de [Tutorial - Gebruikershandleiding](tutorial/index.md){.internal-link target=_blank}. + +/// tip + +Pydantic heeft een speciaal gedrag wanneer je `Optional` of `Union[EenType, None]` gebruikt zonder een standaardwaarde, je kunt er meer over lezen in de Pydantic-documentatie over Verplichte optionele velden. + +/// + +## Type Hints met Metadata Annotaties + +Python heeft ook een functie waarmee je **extra metadata** in deze type hints kunt toevoegen met behulp van `Annotated`. + +//// tab | Python 3.9+ + +In Python 3.9 is `Annotated` onderdeel van de standaardpakket, dus je kunt het importeren vanuit `typing`. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +In versies lager dan Python 3.9 importeer je `Annotated` vanuit `typing_extensions`. + +Het wordt al geïnstalleerd met **FastAPI**. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` + +//// + +Python zelf doet niets met deze `Annotated` en voor editors en andere hulpmiddelen is het type nog steeds een `str`. + +Maar je kunt deze ruimte in `Annotated` gebruiken om **FastAPI** te voorzien van extra metadata over hoe je wilt dat je applicatie zich gedraagt. + +Het belangrijkste om te onthouden is dat **de eerste *typeparameter*** die je doorgeeft aan `Annotated` het **werkelijke type** is. De rest is gewoon metadata voor andere hulpmiddelen. + +Voor nu hoef je alleen te weten dat `Annotated` bestaat en dat het standaard Python is. 😎 + +Later zul je zien hoe **krachtig** het kan zijn. + +/// tip + +Het feit dat dit **standaard Python** is, betekent dat je nog steeds de **best mogelijke ontwikkelaarservaring** krijgt in je editor, met de hulpmiddelen die je gebruikt om je code te analyseren en te refactoren, enz. ✨ + +Daarnaast betekent het ook dat je code zeer verenigbaar zal zijn met veel andere Python-hulpmiddelen en -pakketten. 🚀 + +/// + +## Type hints in **FastAPI** + +**FastAPI** maakt gebruik van type hints om verschillende dingen te doen. + +Met **FastAPI** declareer je parameters met type hints en krijg je: + +* **Editor ondersteuning**. +* **Type checks**. + +...en **FastAPI** gebruikt dezelfde declaraties om: + +* **Vereisten te definïeren **: van request pad parameters, query parameters, headers, bodies, dependencies, enz. +* **Data te converteren**: van de request naar het vereiste type. +* **Data te valideren**: afkomstig van elke request: + * **Automatische foutmeldingen** te genereren die naar de client worden geretourneerd wanneer de data ongeldig is. +* De API met OpenAPI te **documenteren**: + * die vervolgens wordt gebruikt door de automatische interactieve documentatie gebruikersinterfaces. + +Dit klinkt misschien allemaal abstract. Maak je geen zorgen. Je ziet dit allemaal in actie in de [Tutorial - Gebruikershandleiding](tutorial/index.md){.internal-link target=_blank}. + +Het belangrijkste is dat door standaard Python types te gebruiken, op één plek (in plaats van meer klassen, decorators, enz. toe te voegen), **FastAPI** een groot deel van het werk voor je doet. + +/// info + +Als je de hele tutorial al hebt doorgenomen en terug bent gekomen om meer te weten te komen over types, is een goede bron het "cheat sheet" van `mypy`. + +/// diff --git a/docs/nl/mkdocs.yml b/docs/nl/mkdocs.yml new file mode 100644 index 000000000..de18856f4 --- /dev/null +++ b/docs/nl/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/pl/docs/features.md b/docs/pl/docs/features.md index a6435977c..80d3bdece 100644 --- a/docs/pl/docs/features.md +++ b/docs/pl/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` oznacza: +/// info - Przekaż klucze i wartości słownika `second_user_data` bezpośrednio jako argumenty klucz-wartość, co jest równoznaczne z: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` oznacza: + +Przekaż klucze i wartości słownika `second_user_data` bezpośrednio jako argumenty klucz-wartość, co jest równoznaczne z: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Wsparcie edytora diff --git a/docs/pl/docs/help-fastapi.md b/docs/pl/docs/help-fastapi.md index 54c172664..3ea328dc2 100644 --- a/docs/pl/docs/help-fastapi.md +++ b/docs/pl/docs/help-fastapi.md @@ -26,13 +26,13 @@ Możesz zapisać się do rzadkiego [newslettera o **FastAPI i jego przyjaciołac ## Dodaj gwiazdkę **FastAPI** na GitHubie -Możesz "dodać gwiazdkę" FastAPI na GitHubie (klikając przycisk gwiazdki w prawym górnym rogu): https://github.com/tiangolo/fastapi. ⭐️ +Możesz "dodać gwiazdkę" FastAPI na GitHubie (klikając przycisk gwiazdki w prawym górnym rogu): https://github.com/fastapi/fastapi. ⭐️ Dodając gwiazdkę, inni użytkownicy będą mogli łatwiej znaleźć projekt i zobaczyć, że był już przydatny dla innych. ## Obserwuj repozytorium GitHub w poszukiwaniu nowych wydań -Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/tiangolo/fastapi. 👀 +Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/fastapi/fastapi. 👀 Wybierz opcję "Tylko wydania". @@ -59,7 +59,7 @@ Możesz: ## Napisz tweeta o **FastAPI** -Napisz tweeta o **FastAPI** i powiedz czemu Ci się podoba. 🎉 +Napisz tweeta o **FastAPI** i powiedz czemu Ci się podoba. 🎉 Uwielbiam czytać w jaki sposób **FastAPI** jest używane, co Ci się w nim podobało, w jakim projekcie/firmie go używasz itp. @@ -73,12 +73,12 @@ Uwielbiam czytać w jaki sposób **FastAPI** jest używane, co Ci się w nim pod Możesz spróbować pomóc innym, odpowiadając w: -* Dyskusjach na GitHubie -* Problemach na GitHubie +* Dyskusjach na GitHubie +* Problemach na GitHubie W wielu przypadkach możesz już znać odpowiedź na te pytania. 🤓 -Jeśli pomożesz wielu ludziom, możesz zostać oficjalnym [Ekspertem FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. 🎉 +Jeśli pomożesz wielu ludziom, możesz zostać oficjalnym [Ekspertem FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. 🎉 Pamiętaj tylko o najważniejszym: bądź życzliwy. Ludzie przychodzą sfrustrowani i w wielu przypadkach nie zadają pytań w najlepszy sposób, ale mimo to postaraj się być dla nich jak najbardziej życzliwy. 🤗 @@ -125,7 +125,7 @@ Jeśli odpowiedzą, jest duża szansa, że rozwiązałeś ich problem, gratulacj ## Obserwuj repozytorium na GitHubie -Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/tiangolo/fastapi. 👀 +Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/fastapi/fastapi. 👀 Jeśli wybierzesz "Obserwuj" zamiast "Tylko wydania", otrzymasz powiadomienia, gdy ktoś utworzy nowy problem lub pytanie. Możesz również określić, że chcesz być powiadamiany tylko o nowych problemach, dyskusjach, PR-ach itp. @@ -133,7 +133,7 @@ Następnie możesz spróbować pomóc rozwiązać te problemy. ## Zadawaj pytania -Możesz utworzyć nowe pytanie w repozytorium na GitHubie, na przykład aby: +Możesz utworzyć nowe pytanie w repozytorium na GitHubie, na przykład aby: * Zadać **pytanie** lub zapytać o **problem**. * Zaproponować nową **funkcję**. @@ -170,12 +170,15 @@ A jeśli istnieje jakaś konkretna potrzeba dotycząca stylu lub spójności, sa * Następnie dodaj **komentarz** z informacją o tym, że sprawdziłeś kod, dzięki temu będę miał pewność, że faktycznie go sprawdziłeś. -!!! info - Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń. +/// info - Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅 +Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń. - Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓 +Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅 + +Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓 + +/// * Jeśli PR można uprościć w jakiś sposób, możesz o to poprosić, ale nie ma potrzeby być zbyt wybrednym, może być wiele subiektywnych punktów widzenia (a ja też będę miał swój 🙈), więc lepiej żebyś skupił się na kluczowych rzeczach. @@ -196,7 +199,7 @@ A jeśli istnieje jakaś konkretna potrzeba dotycząca stylu lub spójności, sa Możesz [wnieść wkład](contributing.md){.internal-link target=_blank} do kodu źródłowego za pomocą Pull Requestu, na przykład: * Naprawić literówkę, którą znalazłeś w dokumentacji. -* Podzielić się artykułem, filmem lub podcastem, który stworzyłeś lub znalazłeś na temat FastAPI, edytując ten plik. +* Podzielić się artykułem, filmem lub podcastem, który stworzyłeś lub znalazłeś na temat FastAPI, edytując ten plik. * Upewnij się, że dodajesz swój link na początku odpowiedniej sekcji. * Pomóc w [tłumaczeniu dokumentacji](contributing.md#translations){.internal-link target=_blank} na Twój język. * Możesz również pomóc w weryfikacji tłumaczeń stworzonych przez innych. @@ -215,8 +218,8 @@ Jest wiele pracy do zrobienia, a w większości przypadków **TY** możesz to zr Główne zadania, które możesz wykonać teraz to: -* [Pomóc innym z pytaniami na GitHubie](#help-others-with-questions-in-github){.internal-link target=_blank} (zobacz sekcję powyżej). -* [Oceniać Pull Requesty](#review-pull-requests){.internal-link target=_blank} (zobacz sekcję powyżej). +* [Pomóc innym z pytaniami na GitHubie](#pomagaj-innym-odpowiadajac-na-ich-pytania-na-githubie){.internal-link target=_blank} (zobacz sekcję powyżej). +* [Oceniać Pull Requesty](#przegladaj-pull-requesty){.internal-link target=_blank} (zobacz sekcję powyżej). Te dwie czynności **zajmują najwięcej czasu**. To główna praca związana z utrzymaniem FastAPI. @@ -226,10 +229,13 @@ Jeśli możesz mi w tym pomóc, **pomożesz mi utrzymać FastAPI** i zapewnisz Dołącz do 👥 serwera czatu na Discordzie 👥 i spędzaj czas z innymi w społeczności FastAPI. -!!! wskazówka - Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. +/// tip | Wskazówka + +Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + +Używaj czatu tylko do innych ogólnych rozmów. - Używaj czatu tylko do innych ogólnych rozmów. +/// ### Nie zadawaj pytań na czacie @@ -237,7 +243,7 @@ Miej na uwadze, że ponieważ czaty pozwalają na bardziej "swobodną rozmowę", Na GitHubie szablon poprowadzi Cię do napisania odpowiedniego pytania, dzięki czemu łatwiej uzyskasz dobrą odpowiedź, a nawet rozwiążesz problem samodzielnie, zanim zapytasz. Ponadto na GitHubie mogę się upewnić, że zawsze odpowiadam na wszystko, nawet jeśli zajmuje to trochę czasu. Osobiście nie mogę tego zrobić z systemami czatu. 😅 -Rozmów w systemach czatu nie można tak łatwo przeszukiwać, jak na GitHubie, więc pytania i odpowiedzi mogą zaginąć w rozmowie. A tylko te na GitHubie liczą się do zostania [Ekspertem FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, więc najprawdopodobniej otrzymasz więcej uwagi na GitHubie. +Rozmów w systemach czatu nie można tak łatwo przeszukiwać, jak na GitHubie, więc pytania i odpowiedzi mogą zaginąć w rozmowie. A tylko te na GitHubie liczą się do zostania [Ekspertem FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}, więc najprawdopodobniej otrzymasz więcej uwagi na GitHubie. Z drugiej strony w systemach czatu są tysiące użytkowników, więc jest duża szansa, że znajdziesz tam kogoś do rozmowy, prawie w każdej chwili. 😄 diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index ab33bfb9c..9a96c6553 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ FastAPI to szybki, prosty w nauce i gotowy do użycia w produkcji framework

- - Test + + Test - - Coverage + + Coverage Package version @@ -20,11 +26,11 @@ **Dokumentacja**: https://fastapi.tiangolo.com -**Kod żródłowy**: https://github.com/tiangolo/fastapi +**Kod żródłowy**: https://github.com/fastapi/fastapi --- -FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona 3.8+ bazujący na standardowym typowaniu Pythona. +FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona bazujący na standardowym typowaniu Pythona. Kluczowe cechy: @@ -60,7 +66,7 @@ Kluczowe cechy: "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -84,7 +90,7 @@ Kluczowe cechy: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -106,8 +112,6 @@ Jeżeli tworzysz aplikacje CLI< ## Wymagania -Python 3.8+ - FastAPI oparty jest na: * Starlette dla części webowej. @@ -125,7 +129,7 @@ $ pip install fastapi -Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np. Uvicorn lub Hypercorn. +Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np. Uvicorn lub Hypercorn.
@@ -321,7 +325,7 @@ Robisz to tak samo jak ze standardowymi typami w Pythonie. Nie musisz sie uczyć żadnej nowej składni, metod lub klas ze specyficznych bibliotek itp. -Po prostu standardowy **Python 3.8+**. +Po prostu standardowy **Python**. Na przykład, dla danych typu `int`: @@ -435,7 +439,7 @@ Aby dowiedzieć się o tym więcej, zobacz sekcję email_validator - dla walidacji adresów email. +* email-validator - dla walidacji adresów email. Używane przez Starlette: @@ -446,12 +450,12 @@ Używane przez Starlette: * itsdangerous - Wymagany dla wsparcia `SessionMiddleware`. * pyyaml - Wymagane dla wsparcia `SchemaGenerator` z Starlette (z FastAPI prawdopodobnie tego nie potrzebujesz). * graphene - Wymagane dla wsparcia `GraphQLApp`. -* ujson - Wymagane jeżeli chcesz korzystać z `UJSONResponse`. Używane przez FastAPI / Starlette: * uvicorn - jako serwer, który ładuje i obsługuje Twoją aplikację. * orjson - Wymagane jeżeli chcesz używać `ORJSONResponse`. +* ujson - Wymagane jeżeli chcesz korzystać z `UJSONResponse`. Możesz zainstalować wszystkie te aplikacje przy pomocy `pip install fastapi[all]`. diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md index 9406d703d..8fa4c75ad 100644 --- a/docs/pl/docs/tutorial/first-steps.md +++ b/docs/pl/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Najprostszy plik FastAPI może wyglądać tak: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Skopiuj to do pliku `main.py`. @@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note - Polecenie `uvicorn main:app` odnosi się do: +/// note + +Polecenie `uvicorn main:app` odnosi się do: + +* `main`: plik `main.py` ("moduł" Python). +* `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`. +* `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania. - * `main`: plik `main.py` ("moduł" Python). - * `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`. - * `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania. +/// Na wyjściu znajduje się linia z czymś w rodzaju: @@ -130,23 +131,21 @@ Możesz go również użyć do automatycznego generowania kodu dla klientów, kt ### Krok 1: zaimportuj `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API. -!!! note "Szczegóły techniczne" - `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`. +/// note | Szczegóły techniczne + +`FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`. - Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`. +Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`. +/// ### Krok 2: utwórz instancję `FastAPI` -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{*../../docs_src/first_steps/tutorial001.py hl[3] *} Zmienna `app` będzie tutaj "instancją" klasy `FastAPI`. @@ -166,9 +165,7 @@ $ uvicorn main:app --reload Jeśli stworzysz swoją aplikację, np.: -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} I umieścisz to w pliku `main.py`, to będziesz mógł tak wywołać `uvicorn`: @@ -200,8 +197,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - "Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'. +/// info + +"Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'. + +/// Podczas budowania API, "ścieżka" jest głównym sposobem na oddzielenie "odpowiedzialności" i „zasobów”. @@ -242,25 +242,26 @@ Będziemy je również nazywali "**operacjami**". #### Zdefiniuj *dekorator operacji na ścieżce* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")` mówi **FastAPI** że funkcja poniżej odpowiada za obsługę żądań, które trafiają do: * ścieżki `/` * używając operacji get -!!! info "`@decorator` Info" - Składnia `@something` jest w Pythonie nazywana "dekoratorem". +/// info | `@decorator` Info - Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa). +Składnia `@something` jest w Pythonie nazywana "dekoratorem". - "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi. +Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa). - W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`. +"Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi. - Jest to "**dekorator operacji na ścieżce**". +W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`. + +Jest to "**dekorator operacji na ścieżce**". + +/// Możesz również użyć innej operacji: @@ -275,14 +276,17 @@ Oraz tych bardziej egzotycznych: * `@app.patch()` * `@app.trace()` -!!! tip - Możesz dowolnie używać każdej operacji (metody HTTP). +/// tip + +Możesz dowolnie używać każdej operacji (metody HTTP). - **FastAPI** nie narzuca żadnego konkretnego znaczenia. +**FastAPI** nie narzuca żadnego konkretnego znaczenia. - Informacje tutaj są przedstawione jako wskazówka, a nie wymóg. +Informacje tutaj są przedstawione jako wskazówka, a nie wymóg. - Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`. +Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`. + +/// ### Krok 4: zdefiniuj **funkcję obsługującą ścieżkę** @@ -292,9 +296,7 @@ To jest nasza "**funkcja obsługująca ścieżkę**": * **operacja**: to `get`. * **funkcja**: to funkcja poniżej "dekoratora" (poniżej `@app.get("/")`). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Jest to funkcja Python. @@ -306,18 +308,17 @@ W tym przypadku jest to funkcja "asynchroniczna". Możesz również zdefiniować to jako normalną funkcję zamiast `async def`: -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note -!!! note - Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](/async/#in-a-hurry){.internal-link target=_blank}. +Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Krok 5: zwróć zawartość -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Możesz zwrócić `dict`, `list`, pojedynczą wartość jako `str`, `int`, itp. diff --git a/docs/pl/docs/tutorial/index.md b/docs/pl/docs/tutorial/index.md index f8c5c6022..66f7c6d62 100644 --- a/docs/pl/docs/tutorial/index.md +++ b/docs/pl/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...wliczając w to `uvicorn`, który będzie służył jako serwer wykonujacy Twój kod. -!!! note - Możesz również wykonać instalację "krok po kroku". +/// note - Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym: +Możesz również wykonać instalację "krok po kroku". - ``` - pip install fastapi - ``` +Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym: - Zainstaluj też `uvicorn`, który będzie służył jako serwer: +``` +pip install fastapi +``` + +Zainstaluj też `uvicorn`, który będzie służył jako serwer: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć. - Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć. +/// ## Zaawansowany poradnik diff --git a/docs/pt/docs/about/index.md b/docs/pt/docs/about/index.md new file mode 100644 index 000000000..1f42e8831 --- /dev/null +++ b/docs/pt/docs/about/index.md @@ -0,0 +1,3 @@ +# Sobre + +Sobre o FastAPI, seus padrões, inspirações e muito mais. 🤓 diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md new file mode 100644 index 000000000..58e75ad93 --- /dev/null +++ b/docs/pt/docs/advanced/additional-responses.md @@ -0,0 +1,255 @@ +# Retornos Adicionais no OpenAPI + +/// warning | Aviso + +Este é um tema bem avançado. + +Se você está começando com o **FastAPI**, provavelmente você não precisa disso. + +/// + +Você pode declarar retornos adicionais, com códigos de status adicionais, media types, descrições, etc. + +Essas respostas adicionais serão incluídas no esquema do OpenAPI, e também aparecerão na documentação da API. + +Porém para as respostas adicionais, você deve garantir que está retornando um `Response` como por exemplo o `JSONResponse` diretamente, junto com o código de status e o conteúdo. + +## Retorno Adicional com `model` + +Você pode fornecer o parâmetro `responses` aos seus *decoradores de caminho*. + +Este parâmetro recebe um `dict`, as chaves são os códigos de status para cada retorno, como por exemplo `200`, e os valores são um outro `dict` com a informação de cada um deles. + +Cada um desses `dict` de retorno pode ter uma chave `model`, contendo um modelo do Pydantic, assim como o `response_model`. + +O **FastAPI** pegará este modelo, gerará o esquema JSON dele e incluirá no local correto do OpenAPI. + +Por exemplo, para declarar um outro retorno com o status code `404` e um modelo do Pydantic chamado `Message`, você pode escrever: + +```Python hl_lines="18 22" +{!../../docs_src/additional_responses/tutorial001.py!} +``` + +/// note | Nota + +Lembre-se que você deve retornar o `JSONResponse` diretamente. + +/// + +/// info | Informação + +A chave `model` não é parte do OpenAPI. + +O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto. + +O local correto é: + +* Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém: + * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo:: + * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto. + * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc. + +/// + +O retorno gerado no OpenAI para esta *operação de caminho* será: + +```JSON hl_lines="3-12" +{ + "responses": { + "404": { + "description": "Additional Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } +} +``` + +Os esquemas são referenciados em outro local dentro do esquema OpenAPI: + +```JSON hl_lines="4-16" +{ + "components": { + "schemas": { + "Message": { + "title": "Message", + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "title": "Message", + "type": "string" + } + } + }, + "Item": { + "title": "Item", + "required": [ + "id", + "value" + ], + "type": "object", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + } + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + } + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + } + } + } + } +} +``` + +## Media types adicionais para o retorno principal + +Você pode utilizar o mesmo parâmetro `responses` para adicionar diferentes media types para o mesmo retorno principal. + +Por exemplo, você pode adicionar um media type adicional de `image/png`, declarando que a sua *operação de caminho* pode retornar um objeto JSON (com o media type `application/json`) ou uma imagem PNG: + +```Python hl_lines="19-24 28" +{!../../docs_src/additional_responses/tutorial002.py!} +``` + +/// note | Nota + +Note que você deve retornar a imagem utilizando um `FileResponse` diretamente. + +/// + +/// info | Informação + +A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`). + +Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado. + +/// + +## Combinando informações + +Você também pode combinar informações de diferentes lugares, incluindo os parâmetros `response_model`, `status_code`, e `responses`. + +Você pode declarar um `response_model`, utilizando o código de status padrão `200` (ou um customizado caso você precise), e depois adicionar informações adicionais para esse mesmo retorno em `responses`, diretamente no esquema OpenAPI. + +O **FastAPI** manterá as informações adicionais do `responses`, e combinará com o esquema JSON do seu modelo. + +Por exemplo, você pode declarar um retorno com o código de status `404` que utiliza um modelo do Pydantic que possui um `description` customizado. + +E um retorno com o código de status `200` que utiliza o seu `response_model`, porém inclui um `example` customizado: + +```Python hl_lines="20-31" +{!../../docs_src/additional_responses/tutorial003.py!} +``` + +Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API: + + + +## Combinar retornos predefinidos e personalizados + +Você pode querer possuir alguns retornos predefinidos que são aplicados para diversas *operações de caminho*, porém você deseja combinar com retornos personalizados que são necessários para cada *operação de caminho*. + +Para estes casos, você pode utilizar a técnica do Python de "desempacotamento" de um `dict` utilizando `**dict_to_unpack`: + +```Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +Aqui, o `new_dict` terá todos os pares de chave-valor do `old_dict` mais o novo par de chave-valor: + +```Python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` + +Você pode utilizar essa técnica para reutilizar alguns retornos predefinidos nas suas *operações de caminho* e combiná-las com personalizações adicionais. + +Por exemplo: + +```Python hl_lines="13-17 26" +{!../../docs_src/additional_responses/tutorial004.py!} +``` + +## Mais informações sobre retornos OpenAPI + +Para verificar exatamente o que você pode incluir nos retornos, você pode conferir estas seções na especificação do OpenAPI: + +* Objeto de Retorno OpenAPI, inclui o `Response Object`. +* Objeto de Retorno OpenAPI, você pode incluir qualquer coisa dele diretamente em cada retorno dentro do seu parâmetro `responses`. Incluindo `description`, `headers`, `content` (dentro dele que você declara diferentes media types e esquemas JSON), e `links`. diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md new file mode 100644 index 000000000..5fe970d2a --- /dev/null +++ b/docs/pt/docs/advanced/additional-status-codes.md @@ -0,0 +1,91 @@ +# Códigos de status adicionais + +Por padrão, o **FastAPI** retornará as respostas utilizando o `JSONResponse`, adicionando o conteúdo do retorno da sua *operação de caminho* dentro do `JSONResponse`. + +Ele usará o código de status padrão ou o que você definir na sua *operação de caminho*. + +## Códigos de status adicionais + +Caso você queira retornar códigos de status adicionais além do código principal, você pode fazer isso retornando um `Response` diretamente, como por exemplo um `JSONResponse`, e definir os códigos de status adicionais diretamente. + +Por exemplo, vamos dizer que você deseja ter uma *operação de caminho* que permita atualizar itens, e retornar um código de status HTTP 200 "OK" quando for bem sucedido. + +Mas você também deseja aceitar novos itens. E quando os itens não existiam, ele os cria, e retorna o código de status HTTP 201 "Created. + +Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja: + +//// tab | Python 3.10+ + +```Python hl_lines="4 25" +{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 25" +{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 26" +{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Faça uso da versão `Annotated` quando possível. + +/// + +```Python hl_lines="2 23" +{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Faça uso da versão `Annotated` quando possível. + +/// + +```Python hl_lines="4 25" +{!> ../../docs_src/additional_status_codes/tutorial001.py!} +``` + +//// + +/// warning | Aviso + +Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente. + +Ele não será serializado com um modelo, etc. + +Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`). + +/// + +/// note | Detalhes técnicos + +Você também pode utilizar `from starlette.responses import JSONResponse`. + +O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`. + +/// + +## OpenAPI e documentação da API + +Se você retorna códigos de status adicionais e retornos diretamente, eles não serão incluídos no esquema do OpenAPI (a documentação da API), porque o FastAPI não tem como saber de antemão o que será retornado. + +Mas você pode documentar isso no seu código, utilizando: [Retornos Adicionais](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md new file mode 100644 index 000000000..52fe121f9 --- /dev/null +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -0,0 +1,177 @@ +# Dependências avançadas + +## Dependências parametrizadas + +Todas as dependências que vimos até agora são funções ou classes fixas. + +Mas podem ocorrer casos onde você deseja ser capaz de definir parâmetros na dependência, sem ter a necessidade de declarar diversas funções ou classes. + +Vamos imaginar que queremos ter uma dependência que verifica se o parâmetro de consulta `q` possui um valor fixo. + +Porém nós queremos poder parametrizar o conteúdo fixo. + +## Uma instância "chamável" + +Em Python existe uma maneira de fazer com que uma instância de uma classe seja um "chamável". + +Não propriamente a classe (que já é um chamável), mas a instância desta classe. + +Para fazer isso, nós declaramos o método `__call__`: + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente. + +## Parametrizar a instância + +E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência: + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código. + +## Crie uma instância + +Nós poderíamos criar uma instância desta classe com: + +//// tab | Python 3.9+ + +```Python hl_lines="18" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`. + +## Utilize a instância como dependência + +Então, nós podemos utilizar este `checker` em um `Depends(checker)`, no lugar de `Depends(FixedContentQueryChecker)`, porque a dependência é a instância, `checker`, e não a própria classe. + +E quando a dependência for resolvida, o **FastAPI** chamará este `checker` como: + +```Python +checker(q="somequery") +``` + +...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`: + +//// tab | Python 3.9+ + +```Python hl_lines="22" +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../docs_src/dependencies/tutorial011_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="20" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +/// tip | Dica + +Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda. + +Estes exemplos são intencionalmente simples, porém mostram como tudo funciona. + +Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira. + +Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos. + +/// diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md new file mode 100644 index 000000000..8fae97298 --- /dev/null +++ b/docs/pt/docs/advanced/async-tests.md @@ -0,0 +1,107 @@ +# Testes Assíncronos + +Você já viu como testar as suas aplicações **FastAPI** utilizando o `TestClient` que é fornecido. Até agora, você viu apenas como escrever testes síncronos, sem utilizar funções `async`. + +Ser capaz de utilizar funções assíncronas em seus testes pode ser útil, por exemplo, quando você está realizando uma consulta em seu banco de dados de maneira assíncrona. Imagine que você deseja testar realizando requisições para a sua aplicação FastAPI e depois verificar que a sua aplicação inseriu corretamente as informações no banco de dados, ao utilizar uma biblioteca assíncrona para banco de dados. + +Vamos ver como nós podemos fazer isso funcionar. + +## pytest.mark.anyio + +Se quisermos chamar funções assíncronas em nossos testes, as nossas funções de teste precisam ser assíncronas. O AnyIO oferece um plugin bem legal para isso, que nos permite especificar que algumas das nossas funções de teste precisam ser chamadas de forma assíncrona. + +## HTTPX + +Mesmo que a sua aplicação **FastAPI** utilize funções normais com `def` no lugar de `async def`, ela ainda é uma aplicação `async` por baixo dos panos. + +O `TestClient` faz algumas mágicas para invocar a aplicação FastAPI assíncrona em suas funções `def` normais, utilizando o pytest padrão. Porém a mágica não acontece mais quando nós estamos utilizando dentro de funções assíncronas. Ao executar os nossos testes de forma assíncrona, nós não podemos mais utilizar o `TestClient` dentro das nossas funções de teste. + +O `TestClient` é baseado no HTTPX, e felizmente nós podemos utilizá-lo diretamente para testar a API. + +## Exemplo + +Para um exemplos simples, vamos considerar uma estrutura de arquivos semelhante ao descrito em [Bigger Applications](../tutorial/bigger-applications.md){.internal-link target=_blank} e [Testing](../tutorial/testing.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +O arquivo `main.py` teria: + +```Python +{!../../docs_src/async_tests/main.py!} +``` + +O arquivo `test_main.py` teria os testes para para o arquivo `main.py`, ele poderia ficar assim: + +```Python +{!../../docs_src/async_tests/test_main.py!} +``` + +## Executá-lo + +Você pode executar os seus testes normalmente via: + +
+ +```console +$ pytest + +---> 100% +``` + +
+ +## Em Detalhes + +O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste deve ser invocada de maneira assíncrona: + +```Python hl_lines="7" +{!../../docs_src/async_tests/test_main.py!} +``` + +/// tip | Dica + +Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente. + +/// + +Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. + +```Python hl_lines="9-12" +{!../../docs_src/async_tests/test_main.py!} +``` + +Isso é equivalente a: + +```Python +response = client.get('/') +``` + +...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`. + +/// tip | Dica + +Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona. + +/// + +/// warning | Aviso + +Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do florimondmanca/asgi-lifespan. + +/// + +## Outras Chamadas de Funções Assíncronas + +Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código. + +/// tip | Dica + +Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o MotorClient do MongoDB) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`. + +/// diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md new file mode 100644 index 000000000..6837c9542 --- /dev/null +++ b/docs/pt/docs/advanced/behind-a-proxy.md @@ -0,0 +1,361 @@ +# Atrás de um Proxy + +Em algumas situações, você pode precisar usar um servidor **proxy** como Traefik ou Nginx com uma configuração que adiciona um prefixo de caminho extra que não é visto pela sua aplicação. + +Nesses casos, você pode usar `root_path` para configurar sua aplicação. + +O `root_path` é um mecanismo fornecido pela especificação ASGI (que o FastAPI utiliza, através do Starlette). + +O `root_path` é usado para lidar com esses casos específicos. + +E também é usado internamente ao montar sub-aplicações. + +## Proxy com um prefixo de caminho removido + +Ter um proxy com um prefixo de caminho removido, nesse caso, significa que você poderia declarar um caminho em `/app` no seu código, mas então, você adiciona uma camada no topo (o proxy) que colocaria sua aplicação **FastAPI** sob um caminho como `/api/v1`. + +Nesse caso, o caminho original `/app` seria servido em `/api/v1/app`. + +Embora todo o seu código esteja escrito assumindo que existe apenas `/app`. + +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *} + +E o proxy estaria **"removendo"** o **prefixo do caminho** dinamicamente antes de transmitir a solicitação para o servidor da aplicação (provavelmente Uvicorn via CLI do FastAPI), mantendo sua aplicação convencida de que está sendo servida em `/app`, para que você não precise atualizar todo o seu código para incluir o prefixo `/api/v1`. + +Até aqui, tudo funcionaria normalmente. + +Mas então, quando você abre a interface de documentação integrada (o frontend), ele esperaria obter o OpenAPI schema em `/openapi.json`, em vez de `/api/v1/openapi.json`. + +Então, o frontend (que roda no navegador) tentaria acessar `/openapi.json` e não conseguiria obter o OpenAPI schema. + +Como temos um proxy com um prefixo de caminho de `/api/v1` para nossa aplicação, o frontend precisa buscar o OpenAPI schema em `/api/v1/openapi.json`. + +```mermaid +graph LR + +browser("Browser") +proxy["Proxy on http://0.0.0.0:9999/api/v1/app"] +server["Server on http://127.0.0.1:8000/app"] + +browser --> proxy +proxy --> server +``` + +/// tip | Dica + +O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor. + +/// + +A interface de documentação também precisaria do OpenAPI schema para declarar que API `server` está localizado em `/api/v1` (atrás do proxy). Por exemplo: + +```JSON hl_lines="4-8" +{ + "openapi": "3.1.0", + // Mais coisas aqui + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + // Mais coisas aqui + } +} +``` + +Neste exemplo, o "Proxy" poderia ser algo como **Traefik**. E o servidor seria algo como CLI do FastAPI com **Uvicorn**, executando sua aplicação FastAPI. + +### Fornecendo o `root_path` + +Para conseguir isso, você pode usar a opção de linha de comando `--root-path` assim: + +
+ +```console +$ fastapi run main.py --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Se você usar Hypercorn, ele também tem a opção `--root-path`. + +/// note | Detalhes Técnicos + +A especificação ASGI define um `root_path` para esse caso de uso. + +E a opção de linha de comando `--root-path` fornece esse `root_path`. + +/// + +### Verificando o `root_path` atual + +Você pode obter o `root_path` atual usado pela sua aplicação para cada solicitação, ele faz parte do dicionário `scope` (que faz parte da especificação ASGI). + +Aqui estamos incluindo ele na mensagem apenas para fins de demonstração. + +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} + +Então, se você iniciar o Uvicorn com: + +
+ +```console +$ fastapi run main.py --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +A resposta seria algo como: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +### Configurando o `root_path` na aplicação FastAPI + +Alternativamente, se você não tiver uma maneira de fornecer uma opção de linha de comando como `--root-path` ou equivalente, você pode definir o parâmetro `--root-path` ao criar sua aplicação FastAPI: + +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} + +Passar o `root_path`h para `FastAPI` seria o equivalente a passar a opção de linha de comando `--root-path` para Uvicorn ou Hypercorn. + +### Sobre `root_path` + +Tenha em mente que o servidor (Uvicorn) não usará esse `root_path` para nada além de passá-lo para a aplicação. + +Mas se você acessar com seu navegador http://127.0.0.1:8000/app você verá a resposta normal: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +Portanto, ele não esperará ser acessado em `http://127.0.0.1:8000/api/v1/app`. + +O Uvicorn esperará que o proxy acesse o Uvicorn em `http://127.0.0.1:8000/app`, e então seria responsabilidade do proxy adicionar o prefixo extra `/api/v1` no topo. + +## Sobre proxies com um prefixo de caminho removido + +Tenha em mente que um proxy com prefixo de caminho removido é apenas uma das maneiras de configurá-lo. + +Provavelmente, em muitos casos, o padrão será que o proxy não tenha um prefixo de caminho removido. + +Em um caso como esse (sem um prefixo de caminho removido), o proxy escutaria em algo como `https://myawesomeapp.com`, e então se o navegador acessar `https://myawesomeapp.com/api/v1/app` e seu servidor (por exemplo, Uvicorn) escutar em `http://127.0.0.1:8000` o proxy (sem um prefixo de caminho removido) acessaria o Uvicorn no mesmo caminho: `http://127.0.0.1:8000/api/v1/app`. + +## Testando localmente com Traefik + +Você pode facilmente executar o experimento localmente com um prefixo de caminho removido usando Traefik. + +Faça o download do Traefik., Ele é um único binário e você pode extrair o arquivo compactado e executá-lo diretamente do terminal. + +Então, crie um arquivo `traefik.toml` com: + +```TOML hl_lines="3" +[entryPoints] + [entryPoints.http] + address = ":9999" + +[providers] + [providers.file] + filename = "routes.toml" +``` + +Isso diz ao Traefik para escutar na porta 9999 e usar outro arquivo `routes.toml`. + +/// tip | Dica + +Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`). + +/// + +Agora crie esse outro arquivo `routes.toml`: + +```TOML hl_lines="5 12 20" +[http] + [http.middlewares] + + [http.middlewares.api-stripprefix.stripPrefix] + prefixes = ["/api/v1"] + + [http.routers] + + [http.routers.app-http] + entryPoints = ["http"] + service = "app" + rule = "PathPrefix(`/api/v1`)" + middlewares = ["api-stripprefix"] + + [http.services] + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.app.loadBalancer.servers]] + url = "http://127.0.0.1:8000" +``` + +Esse arquivo configura o Traefik para usar o prefixo de caminho `/api/v1`. + +E então ele redirecionará suas solicitações para seu Uvicorn rodando em `http://127.0.0.1:8000`. + +Agora inicie o Traefik: + +
+ +```console +$ ./traefik --configFile=traefik.toml + +INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml +``` + +
+ +E agora inicie sua aplicação, usando a opção `--root-path`: + +
+ +```console +$ fastapi run main.py --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Verifique as respostas + +Agora, se você for ao URL com a porta para o Uvicorn: http://127.0.0.1:8000/app, você verá a resposta normal: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +/// tip | Dica + +Perceba que, mesmo acessando em `http://127.0.0.1:8000/app`, ele mostra o `root_path` de `/api/v1`, retirado da opção `--root-path`. + +/// + +E agora abra o URL com a porta para o Traefik, incluindo o prefixo de caminho: http://127.0.0.1:9999/api/v1/app. + +Obtemos a mesma resposta: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +mas desta vez no URL com o prefixo de caminho fornecido pelo proxy: `/api/v1`. + +Claro, a ideia aqui é que todos acessariam a aplicação através do proxy, então a versão com o prefixo de caminho `/api/v1` é a "correta". + +E a versão sem o prefixo de caminho (`http://127.0.0.1:8000/app`), fornecida diretamente pelo Uvicorn, seria exclusivamente para o _proxy_ (Traefik) acessá-la. + +Isso demonstra como o Proxy (Traefik) usa o prefixo de caminho e como o servidor (Uvicorn) usa o `root_path` da opção `--root-path`. + +### Verifique a interface de documentação + +Mas aqui está a parte divertida. ✨ + +A maneira "oficial" de acessar a aplicação seria através do proxy com o prefixo de caminho que definimos. Então, como esperaríamos, se você tentar a interface de documentação servida diretamente pelo Uvicorn, sem o prefixo de caminho no URL, ela não funcionará, porque espera ser acessada através do proxy. + +Você pode verificar em http://127.0.0.1:8000/docs: + + + +Mas se acessarmos a interface de documentação no URL "oficial" usando o proxy com a porta `9999`, em `/api/v1/docs`, ela funciona corretamente! 🎉 + +Você pode verificar em http://127.0.0.1:9999/api/v1/docs: + + + +Exatamente como queríamos. ✔️ + +Isso porque o FastAPI usa esse `root_path` para criar o `server` padrão no OpenAPI com o URL fornecido pelo `root_path`. + +## Servidores adicionais + +/// warning | Aviso + +Este é um caso de uso mais avançado. Sinta-se à vontade para pular. + +/// + +Por padrão, o **FastAPI** criará um `server` no OpenAPI schema com o URL para o `root_path`. + +Mas você também pode fornecer outros `servers` alternativos, por exemplo, se quiser que a *mesma* interface de documentação interaja com ambientes de staging e produção. + +Se você passar uma lista personalizada de `servers` e houver um `root_path` (porque sua API está atrás de um proxy), o **FastAPI** inserirá um "server" com esse `root_path` no início da lista. + +Por exemplo: + +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} + +Gerará um OpenAPI schema como: + +```JSON hl_lines="5-7" +{ + "openapi": "3.1.0", + // Mais coisas aqui + "servers": [ + { + "url": "/api/v1" + }, + { + "url": "https://stag.example.com", + "description": "Staging environment" + }, + { + "url": "https://prod.example.com", + "description": "Production environment" + } + ], + "paths": { + // Mais coisas aqui + } +} +``` + +/// tip | Dica + +Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`. + +/// + +Na interface de documentação em http://127.0.0.1:9999/api/v1/docs parecerá: + + + +/// tip | Dica + +A interface de documentação interagirá com o servidor que você selecionar. + +/// + +### Desabilitar servidor automático de `root_path` + +Se você não quiser que o **FastAPI** inclua um servidor automático usando o `root_path`, você pode usar o parâmetro `root_path_in_servers=False`: + +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} + +e então ele não será incluído no OpenAPI schema. + +## Montando uma sub-aplicação + +Se você precisar montar uma sub-aplicação (como descrito em [Sub Aplicações - Montagens](sub-applications.md){.internal-link target=_blank}) enquanto também usa um proxy com `root_path`, você pode fazer isso normalmente, como esperaria. + +O FastAPI usará internamente o `root_path` de forma inteligente, então tudo funcionará. ✨ diff --git a/docs/pt/docs/advanced/benchmarks.md b/docs/pt/docs/advanced/benchmarks.md new file mode 100644 index 000000000..72ef1e444 --- /dev/null +++ b/docs/pt/docs/advanced/benchmarks.md @@ -0,0 +1,34 @@ +# Benchmarks + +Benchmarks independentes da TechEmpower mostram que aplicações **FastAPI** rodando com o Uvicorn como um dos frameworks Python mais rápidos disponíveis, ficando atrás apenas do Starlette e Uvicorn (utilizado internamente pelo FastAPI). + +Porém, ao verificar benchmarks e comparações você deve prestar atenção ao seguinte: + +## Benchmarks e velocidade + +Quando você verifica os benchmarks, é comum ver diversas ferramentas de diferentes tipos comparados como se fossem equivalentes. + +Especificamente, para ver o Uvicorn, Starlette e FastAPI comparados entre si (entre diversas outras ferramentas). + +Quanto mais simples o problema resolvido pela ferramenta, melhor será a performance. E a maioria das análises não testa funcionalidades adicionais que são oferecidas pela ferramenta. + +A hierarquia é: + +* **Uvicorn**: um servidor ASGI + * **Starlette**: (utiliza Uvicorn) um microframework web + * **FastAPI**: (utiliza Starlette) um microframework para APIs com diversas funcionalidades adicionais para a construção de APIs, com validação de dados, etc. + +* **Uvicorn**: + * Terá a melhor performance, pois não possui muito código além do próprio servidor. + * Você não escreveria uma aplicação utilizando o Uvicorn diretamente. Isso significaria que o seu código teria que incluir pelo menos todo o código fornecido pelo Starlette (ou o **FastAPI**). E caso você fizesse isso, a sua aplicação final teria a mesma sobrecarga que teria se utilizasse um framework, minimizando o código e os bugs. + * Se você está comparando o Uvicorn, compare com os servidores de aplicação Daphne, Hypercorn, uWSGI, etc. +* **Starlette**: + * Terá o melhor desempenho, depois do Uvicorn. Na verdade, o Starlette utiliza o Uvicorn para rodar. Portanto, ele pode ficar mais "devagar" que o Uvicorn apenas por ter que executar mais código. + * Mas ele fornece as ferramentas para construir aplicações web simples, com roteamento baseado em caminhos, etc. + * Se você está comparando o Starlette, compare-o com o Sanic, Flask, Django, etc. Frameworks web (ou microframeworks). +* **FastAPI**: + * Da mesma forma que o Starlette utiliza o Uvicorn e não consegue ser mais rápido que ele, o **FastAPI** utiliza o Starlette, portanto, ele não consegue ser mais rápido que ele. + * O FastAPI provê mais funcionalidades em cima do Starlette. Funcionalidades que você quase sempre precisará quando estiver construindo APIs, como validação de dados e serialização. E ao utilizá-lo, você obtém documentação automática sem custo nenhum (a documentação automática sequer adiciona sobrecarga nas aplicações rodando, pois ela é gerada na inicialização). + * Caso você não utilize o FastAPI e faz uso do Starlette diretamente (ou outra ferramenta, como o Sanic, Flask, Responder, etc) você mesmo teria que implementar toda a validação de dados e serialização. Então, a sua aplicação final ainda teria a mesma sobrecarga caso estivesse usando o FastAPI. E em muitos casos, validação de dados e serialização é a maior parte do código escrito em aplicações. + * Então, ao utilizar o FastAPI, você está economizando tempo de programação, evitando bugs, linhas de código, e provavelmente terá a mesma performance (ou até melhor) do que teria caso você não o utilizasse (já que você teria que implementar tudo no seu código). + * Se você está comparando o FastAPI, compare-o com frameworks de aplicações web (ou conjunto de ferramentas) que oferecem validação de dados, serialização e documentação, como por exemplo o Flask-apispec, NestJS, Molten, etc. Frameworks que possuem validação integrada de dados, serialização e documentação. diff --git a/docs/pt/docs/advanced/custom-response.md b/docs/pt/docs/advanced/custom-response.md new file mode 100644 index 000000000..5f673d7ce --- /dev/null +++ b/docs/pt/docs/advanced/custom-response.md @@ -0,0 +1,344 @@ +# Resposta Personalizada - HTML, Stream, File e outras + +Por padrão, o **FastAPI** irá retornar respostas utilizando `JSONResponse`. + +Mas você pode sobrescrever esse comportamento utilizando `Response` diretamente, como visto em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}. + +Mas se você retornar uma `Response` diretamente (ou qualquer subclasse, como `JSONResponse`), os dados não serão convertidos automaticamente (mesmo que você declare um `response_model`), e a documentação não será gerada automaticamente (por exemplo, incluindo o "media type", no cabeçalho HTTP `Content-Type` como parte do esquema OpenAPI gerado). + +Mas você também pode declarar a `Response` que você deseja utilizar (e.g. qualquer subclasse de `Response`), em um *decorador de operação de rota* utilizando o parâmetro `response_class`. + +Os conteúdos que você retorna em sua *função de operador de rota* serão colocados dentro dessa `Response`. + +E se a `Response` tiver um media type JSON (`application/json`), como é o caso com `JSONResponse` e `UJSONResponse`, os dados que você retornar serão automaticamente convertidos (e filtrados) com qualquer `response_model` do Pydantic que for declarado em sua *função de operador de rota*. + +/// note | Nota + +Se você utilizar uma classe de Resposta sem media type, o FastAPI esperará que sua resposta não tenha conteúdo, então ele não irá documentar o formato da resposta na documentação OpenAPI gerada. + +/// + +## Utilizando `ORJSONResponse` + +Por exemplo, se você precisa bastante de performance, você pode instalar e utilizar o `orjson` e definir a resposta para ser uma `ORJSONResponse`. + +Importe a classe, ou subclasse, de `Response` que você deseja utilizar e declare ela no *decorador de operação de rota*. + +Para respostas grandes, retornar uma `Response` diretamente é muito mais rápido que retornar um dicionário. + +Isso ocorre por que, por padrão, o FastAPI irá verificar cada item dentro do dicionário e garantir que ele seja serializável para JSON, utilizando o mesmo[Codificador Compatível com JSON](../tutorial/encoder.md){.internal-link target=_blank} explicado no tutorial. Isso permite que você retorne **objetos abstratos**, como modelos do banco de dados, por exemplo. + +Mas se você tem certeza que o conteúdo que você está retornando é **serializável com JSON**, você pode passá-lo diretamente para a classe de resposta e evitar o trabalho extra que o FastAPI teria ao passar o conteúdo pelo `jsonable_encoder` antes de passar para a classe de resposta. + +```Python hl_lines="2 7" +{!../../docs_src/custom_response/tutorial001b.py!} +``` + +/// info | Informação + +O parâmetro `response_class` também será usado para definir o "media type" da resposta. + +Neste caso, o cabeçalho HTTP `Content-Type` irá ser definido como `application/json`. + +E será documentado como tal no OpenAPI. + +/// + +/// tip | Dica + +A `ORJSONResponse` está disponível apenas no FastAPI, e não no Starlette. + +/// + +## Resposta HTML + +Para retornar uma resposta com HTML diretamente do **FastAPI**, utilize `HTMLResponse`. + +* Importe `HTMLResponse` +* Passe `HTMLResponse` como o parâmetro de `response_class` do seu *decorador de operação de rota*. + +```Python hl_lines="2 7" +{!../../docs_src/custom_response/tutorial002.py!} +``` + +/// info | Informação + +O parâmetro `response_class` também será usado para definir o "media type" da resposta. + +Neste caso, o cabeçalho HTTP `Content-Type` será definido como `text/html`. + +E será documentado como tal no OpenAPI. + +/// + +### Retornando uma `Response` + +Como visto em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}, você também pode sobrescrever a resposta diretamente na sua *operação de rota*, ao retornar ela. + +O mesmo exemplo de antes, retornando uma `HTMLResponse`, poderia parecer com: + +```Python hl_lines="2 7 19" +{!../../docs_src/custom_response/tutorial003.py!} +``` + +/// warning | Aviso + +Uma `Response` retornada diretamente em sua *função de operação de rota* não será documentada no OpenAPI (por exemplo, o `Content-Type` não será documentado) e não será visível na documentação interativa automática. + +/// + +/// info | Informação + +Obviamente, o cabeçalho `Content-Type`, o código de status, etc, virão do objeto `Response` que você retornou. + +/// + +### Documentar no OpenAPI e sobrescrever `Response` + +Se você deseja sobrescrever a resposta dentro de uma função, mas ao mesmo tempo documentar o "media type" no OpenAPI, você pode utilizar o parâmetro `response_class` E retornar um objeto `Response`. + +A `response_class` será usada apenas para documentar o OpenAPI da *operação de rota*, mas sua `Response` será usada como foi definida. + +##### Retornando uma `HTMLResponse` diretamente + +Por exemplo, poderia ser algo como: + +```Python hl_lines="7 21 23" +{!../../docs_src/custom_response/tutorial004.py!} +``` + +Neste exemplo, a função `generate_html_response()` já cria e retorna uma `Response` em vez de retornar o HTML em uma `str`. + +Ao retornar o resultado chamando `generate_html_response()`, você já está retornando uma `Response` que irá sobrescrever o comportamento padrão do **FastAPI**. + +Mas se você passasse uma `HTMLResponse` em `response_class` também, o **FastAPI** saberia como documentar isso no OpenAPI e na documentação interativa como um HTML com `text/html`: + + + +## Respostas disponíveis + +Aqui estão algumas dos tipos de resposta disponíveis. + +Lembre-se que você pode utilizar `Response` para retornar qualquer outra coisa, ou até mesmo criar uma subclasse personalizada. + +/// note | Detalhes Técnicos + +Você também pode utilizar `from starlette.responses import HTMLResponse`. + +O **FastAPI** provê a mesma `starlette.responses` como `fastapi.responses` apenas como uma facilidade para você, desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. + +/// + +### `Response` + +A classe principal de respostas, todas as outras respostas herdam dela. + +Você pode retorná-la diretamente. + +Ela aceita os seguintes parâmetros: + +* `content` - Uma sequência de caracteres (`str`) ou `bytes`. +* `status_code` - Um código de status HTTP do tipo `int`. +* `headers` - Um dicionário `dict` de strings. +* `media_type` - Uma `str` informando o media type. E.g. `"text/html"`. + +O FastAPI (Starlette, na verdade) irá incluir o cabeçalho Content-Length automaticamente. Ele também irá incluir o cabeçalho Content-Type, baseado no `media_type` e acrescentando uma codificação para tipos textuais. + +```Python hl_lines="1 18" +{!../../docs_src/response_directly/tutorial002.py!} +``` + +### `HTMLResponse` + +Usa algum texto ou sequência de bytes e retorna uma resposta HTML. Como você leu acima. + +### `PlainTextResponse` + +Usa algum texto ou sequência de bytes para retornar uma resposta de texto não formatado. + +```Python hl_lines="2 7 9" +{!../../docs_src/custom_response/tutorial005.py!} +``` + +### `JSONResponse` + +Pega alguns dados e retorna uma resposta com codificação `application/json`. + +É a resposta padrão utilizada no **FastAPI**, como você leu acima. + +### `ORJSONResponse` + +Uma alternativa mais rápida de resposta JSON utilizando o `orjson`, como você leu acima. + +/// info | Informação + +Essa resposta requer a instalação do pacote `orjson`, com o comando `pip install orjson`, por exemplo. + +/// + +### `UJSONResponse` + +Uma alternativa de resposta JSON utilizando a biblioteca `ujson`. + +/// info | Informação + +Essa resposta requer a instalação do pacote `ujson`, com o comando `pip install ujson`, por exemplo. + +/// + +/// warning | Aviso + +`ujson` é menos cauteloso que a implementação nativa do Python na forma que os casos especiais são tratados + +/// + +```Python hl_lines="2 7" +{!../../docs_src/custom_response/tutorial001.py!} +``` + +/// tip | Dica + +É possível que `ORJSONResponse` seja uma alternativa mais rápida. + +/// + +### `RedirectResponse` + +Retorna um redirecionamento HTTP. Utiliza o código de status 307 (Redirecionamento Temporário) por padrão. + +Você pode retornar uma `RedirectResponse` diretamente: + +```Python hl_lines="2 9" +{!../../docs_src/custom_response/tutorial006.py!} +``` + +--- + +Ou você pode utilizá-la no parâmetro `response_class`: + +```Python hl_lines="2 7 9" +{!../../docs_src/custom_response/tutorial006b.py!} +``` + +Se você fizer isso, então você pode retornar a URL diretamente da sua *função de operação de rota* + +Neste caso, o `status_code` utilizada será o padrão de `RedirectResponse`, que é `307`. + +--- + +Você também pode utilizar o parâmetro `status_code` combinado com o parâmetro `response_class`: + +```Python hl_lines="2 7 9" +{!../../docs_src/custom_response/tutorial006c.py!} +``` + +### `StreamingResponse` + +Recebe uma gerador assíncrono ou um gerador/iterador comum e retorna o corpo da requisição continuamente (stream). + +```Python hl_lines="2 14" +{!../../docs_src/custom_response/tutorial007.py!} +``` + +#### Utilizando `StreamingResponse` com objetos semelhantes a arquivos + +Se você tiver um objeto semelhante a um arquivo (e.g. o objeto retornado por `open()`), você pode criar uma função geradora para iterar sobre esse objeto. + +Dessa forma, você não precisa ler todo o arquivo na memória primeiro, e você pode passar essa função geradora para `StreamingResponse` e retorná-la. + +Isso inclui muitas bibliotecas que interagem com armazenamento em nuvem, processamento de vídeos, entre outras. + +```{ .python .annotate hl_lines="2 10-12 14" } +{!../../docs_src/custom_response/tutorial008.py!} +``` + +1. Essa é a função geradora. É definida como "função geradora" porque contém declarações `yield` nela. +2. Ao utilizar o bloco `with`, nós garantimos que o objeto semelhante a um arquivo é fechado após a função geradora ser finalizada. Isto é, após a resposta terminar de ser enivada. +3. Essa declaração `yield from` informa a função para iterar sobre essa coisa nomeada de `file_like`. E então, para cada parte iterada, fornece essa parte como se viesse dessa função geradora (`iterfile`). + + Então, é uma função geradora que transfere o trabalho de "geração" para alguma outra coisa interna. + + Fazendo dessa forma, podemos colocá-la em um bloco `with`, e assim garantir que o objeto semelhante a um arquivo é fechado quando a função termina. + +/// tip | Dica + +Perceba que aqui estamos utilizando o `open()` da biblioteca padrão que não suporta `async` e `await`, e declaramos a operação de rota com o `def` básico. + +/// + +### `FileResponse` + +Envia um arquivo de forma assíncrona e contínua (stream). +* +Recebe um conjunto de argumentos do construtor diferente dos outros tipos de resposta: + +* `path` - O caminho do arquivo que será transmitido +* `headers` - quaisquer cabeçalhos que serão incluídos, como um dicionário. +* `media_type` - Uma string com o media type. Se não for definida, o media type é inferido a partir do nome ou caminho do arquivo. +* `filename` - Se for definido, é incluído no cabeçalho `Content-Disposition`. + +Respostas de Arquivos incluem o tamanho do arquivo, data da última modificação e ETags apropriados, nos cabeçalhos `Content-Length`, `Last-Modified` e `ETag`, respectivamente. + +```Python hl_lines="2 10" +{!../../docs_src/custom_response/tutorial009.py!} +``` + +Você também pode usar o parâmetro `response_class`: + +```Python hl_lines="2 8 10" +{!../../docs_src/custom_response/tutorial009b.py!} +``` + +Nesse caso, você pode retornar o caminho do arquivo diretamente da sua *função de operação de rota*. + +## Classe de resposta personalizada + +Você pode criar sua própria classe de resposta, herdando de `Response` e usando essa nova classe. + +Por exemplo, vamos supor que você queira utilizar o `orjson`, mas com algumas configurações personalizadas que não estão incluídas na classe `ORJSONResponse`. + +Vamos supor também que você queira retornar um JSON indentado e formatado, então você quer utilizar a opção `orjson.OPT_INDENT_2` do orjson. + +Você poderia criar uma classe `CustomORJSONResponse`. A principal coisa a ser feita é sobrecarregar o método render da classe Response, `Response.render(content)`, que retorna o conteúdo em bytes, para retornar o conteúdo que você deseja: + +```Python hl_lines="9-14 17" +{!../../docs_src/custom_response/tutorial009c.py!} +``` + +Agora em vez de retornar: + +```json +{"message": "Hello World"} +``` + +...essa resposta retornará: + +```json +{ + "message": "Hello World" +} +``` + +Obviamente, você provavelmente vai encontrar maneiras muito melhores de se aproveitar disso do que a formatação de JSON. 😉 + +## Classe de resposta padrão + +Quando você criar uma instância da classe **FastAPI** ou um `APIRouter` você pode especificar qual classe de resposta utilizar por padrão. + +O padrão que define isso é o `default_response_class`. + +No exemplo abaixo, o **FastAPI** irá utilizar `ORJSONResponse` por padrão, em todas as *operações de rota*, em vez de `JSONResponse`. + +```Python hl_lines="2 4" +{!../../docs_src/custom_response/tutorial010.py!} +``` + +/// tip | Dica + +Você ainda pode substituir `response_class` em *operações de rota* como antes. + +/// + +## Documentação adicional + +Você também pode declarar o media type e muitos outros detalhes no OpenAPI utilizando `responses`: [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/advanced/dataclasses.md b/docs/pt/docs/advanced/dataclasses.md new file mode 100644 index 000000000..af603ada7 --- /dev/null +++ b/docs/pt/docs/advanced/dataclasses.md @@ -0,0 +1,101 @@ +# Usando Dataclasses + +FastAPI é construído em cima do **Pydantic**, e eu tenho mostrado como usar modelos Pydantic para declarar requisições e respostas. + +Mas o FastAPI também suporta o uso de `dataclasses` da mesma forma: + +```Python hl_lines="1 7-12 19-20" +{!../../docs_src/dataclasses/tutorial001.py!} +``` + +Isso ainda é suportado graças ao **Pydantic**, pois ele tem suporte interno para `dataclasses`. + +Então, mesmo com o código acima que não usa Pydantic explicitamente, o FastAPI está usando Pydantic para converter essas dataclasses padrão para a versão do Pydantic. + +E claro, ele suporta o mesmo: + +* validação de dados +* serialização de dados +* documentação de dados, etc. + +Isso funciona da mesma forma que com os modelos Pydantic. E na verdade é alcançado da mesma maneira por baixo dos panos, usando Pydantic. + +/// info | Informação + +Lembre-se de que dataclasses não podem fazer tudo o que os modelos Pydantic podem fazer. + +Então, você ainda pode precisar usar modelos Pydantic. + +Mas se você tem um monte de dataclasses por aí, este é um truque legal para usá-las para alimentar uma API web usando FastAPI. 🤓 + +/// + +## Dataclasses em `response_model` + +Você também pode usar `dataclasses` no parâmetro `response_model`: + +```Python hl_lines="1 7-13 19" +{!../../docs_src/dataclasses/tutorial002.py!} +``` + +A dataclass será automaticamente convertida para uma dataclass Pydantic. + +Dessa forma, seu esquema aparecerá na interface de documentação da API: + + + +## Dataclasses em Estruturas de Dados Aninhadas + +Você também pode combinar `dataclasses` com outras anotações de tipo para criar estruturas de dados aninhadas. + +Em alguns casos, você ainda pode ter que usar a versão do Pydantic das `dataclasses`. Por exemplo, se você tiver erros com a documentação da API gerada automaticamente. + +Nesse caso, você pode simplesmente trocar as `dataclasses` padrão por `pydantic.dataclasses`, que é um substituto direto: + +```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } +{!../../docs_src/dataclasses/tutorial003.py!} +``` + +1. Ainda importamos `field` das `dataclasses` padrão. + +2. `pydantic.dataclasses` é um substituto direto para `dataclasses`. + +3. A dataclass `Author` inclui uma lista de dataclasses `Item`. + +4. A dataclass `Author` é usada como o parâmetro `response_model`. + +5. Você pode usar outras anotações de tipo padrão com dataclasses como o corpo da requisição. + + Neste caso, é uma lista de dataclasses `Item`. + +6. Aqui estamos retornando um dicionário que contém `items`, que é uma lista de dataclasses. + + O FastAPI ainda é capaz de serializar os dados para JSON. + +7. Aqui o `response_model` está usando uma anotação de tipo de uma lista de dataclasses `Author`. + + Novamente, você pode combinar `dataclasses` com anotações de tipo padrão. + +8. Note que esta *função de operação de rota* usa `def` regular em vez de `async def`. + + Como sempre, no FastAPI você pode combinar `def` e `async def` conforme necessário. + + Se você precisar de uma atualização sobre quando usar qual, confira a seção _"Com pressa?"_ na documentação sobre [`async` e `await`](../async.md#in-a-hurry){.internal-link target=_blank}. + +9. Esta *função de operação de rota* não está retornando dataclasses (embora pudesse), mas uma lista de dicionários com dados internos. + + O FastAPI usará o parâmetro `response_model` (que inclui dataclasses) para converter a resposta. + +Você pode combinar `dataclasses` com outras anotações de tipo em muitas combinações diferentes para formar estruturas de dados complexas. + +Confira as dicas de anotação no código acima para ver mais detalhes específicos. + +## Saiba Mais + +Você também pode combinar `dataclasses` com outros modelos Pydantic, herdar deles, incluí-los em seus próprios modelos, etc. + +Para saber mais, confira a documentação do Pydantic sobre dataclasses. + +## Versão + +Isso está disponível desde a versão `0.67.0` do FastAPI. 🔖 diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 7f6cb6f5d..783dbfc83 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -32,24 +32,27 @@ Vamos iniciar com um exemplo e ver isso detalhadamente. Nós criamos uma função assíncrona chamada `lifespan()` com `yield` como este: ```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Aqui nós estamos simulando a *inicialização* custosa do carregamento do modelo colocando a (falsa) função de modelo no dicionário com modelos de _machine learning_ antes do `yield`. Este código será executado **antes** da aplicação **começar a receber requisições**, durante a *inicialização*. E então, logo após o `yield`, descarregaremos o modelo. Esse código será executado **após** a aplicação **terminar de lidar com as requisições**, pouco antes do *encerramento*. Isso poderia, por exemplo, liberar recursos como memória ou GPU. -!!! tip "Dica" - O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação. +/// tip | Dica - Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷 +O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação. + +Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷 + +/// ### Função _lifespan_ A primeira coisa a notar, é que estamos definindo uma função assíncrona com `yield`. Isso é muito semelhante à Dependências com `yield`. ```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` A primeira parte da função, antes do `yield`, será executada **antes** da aplicação inicializar. @@ -63,7 +66,7 @@ Se você verificar, a função está decorada com um `@asynccontextmanager`. Que converte a função em algo chamado de "**Gerenciador de Contexto Assíncrono**". ```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Um **gerenciador de contexto** em Python é algo que você pode usar em uma declaração `with`, por exemplo, `open()` pode ser usado como um gerenciador de contexto: @@ -87,15 +90,18 @@ No nosso exemplo de código acima, nós não usamos ele diretamente, mas nós pa O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Contexto Assíncrono**, então nós podemos passar nosso novo gerenciador de contexto assíncrono do `lifespan` para ele. ```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` ## Eventos alternativos (deprecados) -!!! warning "Aviso" - A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima. +/// warning | Aviso + +A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima. - Você provavelmente pode pular essa parte. +Você provavelmente pode pular essa parte. + +/// Existe uma forma alternativa para definir a execução dessa lógica durante *inicialização* e durante *encerramento*. @@ -108,7 +114,7 @@ Essas funções podem ser declaradas com `async def` ou `def` normal. Para adicionar uma função que deve rodar antes da aplicação iniciar, declare-a com o evento `"startup"`: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` Nesse caso, a função de manipulação de evento `startup` irá inicializar os itens do "banco de dados" (só um `dict`) com alguns valores. @@ -122,22 +128,28 @@ E sua aplicação não irá começar a receber requisições até que todos os m Para adicionar uma função que deve ser executada quando a aplicação estiver encerrando, declare ela com o evento `"shutdown"`: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`. -!!! info "Informação" - Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior. +/// info | Informação + +Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior. -!!! tip "Dica" - Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo. +/// - Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco. +/// tip | Dica - Mas `open()` não usa `async` e `await`. +Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo. - Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`. +Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco. + +Mas `open()` não usa `async` e `await`. + +Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`. + +/// ### `startup` e `shutdown` juntos @@ -153,11 +165,14 @@ Só um detalhe técnico para nerds curiosos. 🤓 Por baixo, na especificação técnica ASGI, essa é a parte do Protocolo Lifespan, e define eventos chamados `startup` e `shutdown`. -!!! info "Informação" - Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette. +/// info | Informação + +Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette. + +Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código. - Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código. +/// ## Sub Aplicações -🚨 Tenha em mente que esses eventos de lifespan (de inicialização e desligamento) irão somente ser executados para a aplicação principal, não para [Sub Aplicações - Montagem](./sub-applications.md){.internal-link target=_blank}. +🚨 Tenha em mente que esses eventos de lifespan (de inicialização e desligamento) irão somente ser executados para a aplicação principal, não para [Sub Aplicações - Montagem](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/advanced/index.md b/docs/pt/docs/advanced/index.md index 413d8815f..22ba2bf4a 100644 --- a/docs/pt/docs/advanced/index.md +++ b/docs/pt/docs/advanced/index.md @@ -6,10 +6,13 @@ O [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_bla Na próxima seção você verá outras opções, configurações, e recursos adicionais. -!!! tip "Dica" - As próximas seções **não são necessáriamente "avançadas"** +/// tip | Dica - E é possível que para seu caso de uso, a solução esteja em uma delas. +As próximas seções **não são necessáriamente "avançadas"** + +E é possível que para seu caso de uso, a solução esteja em uma delas. + +/// ## Leia o Tutorial primeiro diff --git a/docs/pt/docs/advanced/middleware.md b/docs/pt/docs/advanced/middleware.md new file mode 100644 index 000000000..8167f7d27 --- /dev/null +++ b/docs/pt/docs/advanced/middleware.md @@ -0,0 +1,96 @@ +# Middleware Avançado + +No tutorial principal você leu como adicionar [Middleware Personalizado](../tutorial/middleware.md){.internal-link target=_blank} à sua aplicação. + +E então você também leu como lidar com [CORS com o `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank}. + +Nesta seção, veremos como usar outros middlewares. + +## Adicionando middlewares ASGI + +Como o **FastAPI** é baseado no Starlette e implementa a especificação ASGI, você pode usar qualquer middleware ASGI. + +O middleware não precisa ser feito para o FastAPI ou Starlette para funcionar, desde que siga a especificação ASGI. + +No geral, os middlewares ASGI são classes que esperam receber um aplicativo ASGI como o primeiro argumento. + +Então, na documentação de middlewares ASGI de terceiros, eles provavelmente dirão para você fazer algo como: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +Mas, o FastAPI (na verdade, o Starlette) fornece uma maneira mais simples de fazer isso que garante que os middlewares internos lidem com erros do servidor e que os manipuladores de exceções personalizados funcionem corretamente. + +Para isso, você usa `app.add_middleware()` (como no exemplo para CORS). + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` recebe uma classe de middleware como o primeiro argumento e quaisquer argumentos adicionais a serem passados para o middleware. + +## Middlewares Integrados + +**FastAPI** inclui vários middlewares para casos de uso comuns, veremos a seguir como usá-los. + +/// note | Detalhes Técnicos + +Para o próximo exemplo, você também poderia usar `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vem diretamente do Starlette. + +/// + +## `HTTPSRedirectMiddleware` + +Garante que todas as requisições devem ser `https` ou `wss`. + +Qualquer requisição para `http` ou `ws` será redirecionada para o esquema seguro. + +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} + +## `TrustedHostMiddleware` + +Garante que todas as requisições recebidas tenham um cabeçalho `Host` corretamente configurado, a fim de proteger contra ataques de cabeçalho de host HTTP. + +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} + +Os seguintes argumentos são suportados: + +* `allowed_hosts` - Uma lista de nomes de domínio que são permitidos como nomes de host. Domínios com coringa, como `*.example.com`, são suportados para corresponder a subdomínios. Para permitir qualquer nome de host, use `allowed_hosts=["*"]` ou omita o middleware. + +Se uma requisição recebida não for validada corretamente, uma resposta `400` será enviada. + +## `GZipMiddleware` + +Gerencia respostas GZip para qualquer requisição que inclua `"gzip"` no cabeçalho `Accept-Encoding`. + +O middleware lidará com respostas padrão e de streaming. + +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} + +Os seguintes argumentos são suportados: + +* `minimum_size` - Não comprima respostas menores que este tamanho mínimo em bytes. O padrão é `500`. +* `compresslevel` - Usado durante a compressão GZip. É um inteiro variando de 1 a 9. O padrão é `9`. Um valor menor resulta em uma compressão mais rápida, mas em arquivos maiores, enquanto um valor maior resulta em uma compressão mais lenta, mas em arquivos menores. + +## Outros middlewares + +Há muitos outros middlewares ASGI. + +Por exemplo: + +* Uvicorn's `ProxyHeadersMiddleware` +* MessagePack + +Para checar outros middlewares disponíveis, confira Documentação de Middlewares do Starlette e a Lista Incrível do ASGI. diff --git a/docs/pt/docs/advanced/openapi-callbacks.md b/docs/pt/docs/advanced/openapi-callbacks.md new file mode 100644 index 000000000..c66ababa0 --- /dev/null +++ b/docs/pt/docs/advanced/openapi-callbacks.md @@ -0,0 +1,194 @@ +# Callbacks na OpenAPI + +Você poderia criar uma API com uma *operação de rota* que poderia acionar uma solicitação a uma *API externa* criada por outra pessoa (provavelmente o mesmo desenvolvedor que estaria *usando* sua API). + +O processo que acontece quando seu aplicativo de API chama a *API externa* é chamado de "callback". Porque o software que o desenvolvedor externo escreveu envia uma solicitação para sua API e então sua API *chama de volta*, enviando uma solicitação para uma *API externa* (que provavelmente foi criada pelo mesmo desenvolvedor). + +Nesse caso, você poderia querer documentar como essa API externa *deveria* ser. Que *operação de rota* ela deveria ter, que corpo ela deveria esperar, que resposta ela deveria retornar, etc. + +## Um aplicativo com callbacks + +Vamos ver tudo isso com um exemplo. + +Imagine que você tem um aplicativo que permite criar faturas. + +Essas faturas terão um `id`, `title` (opcional), `customer` e `total`. + +O usuário da sua API (um desenvolvedor externo) criará uma fatura em sua API com uma solicitação POST. + +Então sua API irá (vamos imaginar): + +* Enviar uma solicitação de pagamento para o desenvolvedor externo. +* Coletar o dinheiro. +* Enviar a notificação de volta para o usuário da API (o desenvolvedor externo). +* Isso será feito enviando uma solicitação POST (de *sua API*) para alguma *API externa* fornecida por esse desenvolvedor externo (este é o "callback"). + +## O aplicativo **FastAPI** normal + +Vamos primeiro ver como o aplicativo da API normal se pareceria antes de adicionar o callback. + +Ele terá uma *operação de rota* que receberá um corpo `Invoice`, e um parâmetro de consulta `callback_url` que conterá a URL para o callback. + +Essa parte é bastante normal, a maior parte do código provavelmente já é familiar para você: + +```Python hl_lines="9-13 36-53" +{!../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +/// tip | Dica + +O parâmetro de consulta `callback_url` usa um tipo Pydantic Url. + +/// + +A única coisa nova é o argumento `callbacks=invoices_callback_router.routes` no decorador da *operação de rota*. Veremos o que é isso a seguir. + +## Documentando o callback + +O código real do callback dependerá muito do seu próprio aplicativo de API. + +E provavelmente variará muito de um aplicativo para o outro. + +Poderia ser apenas uma ou duas linhas de código, como: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +Mas possivelmente a parte mais importante do callback é garantir que o usuário da sua API (o desenvolvedor externo) implemente a *API externa* corretamente, de acordo com os dados que *sua API* vai enviar no corpo da solicitação do callback, etc. + +Então, o que faremos a seguir é adicionar o código para documentar como essa *API externa* deve ser para receber o callback de *sua API*. + +A documentação aparecerá na interface do Swagger em `/docs` em sua API, e permitirá que os desenvolvedores externos saibam como construir a *API externa*. + +Esse exemplo não implementa o callback em si (que poderia ser apenas uma linha de código), apenas a parte da documentação. + +/// tip | Dica + +O callback real é apenas uma solicitação HTTP. + +Quando implementando o callback por você mesmo, você pode usar algo como HTTPX ou Requisições. + +/// + +## Escrevendo o código de documentação do callback + +Esse código não será executado em seu aplicativo, nós só precisamos dele para *documentar* como essa *API externa* deveria ser. + +Mas, você já sabe como criar facilmente documentação automática para uma API com o **FastAPI**. + +Então vamos usar esse mesmo conhecimento para documentar como a *API externa* deveria ser... criando as *operações de rota* que a *API externa* deveria implementar (as que sua API irá chamar). + +/// tip | Dica + +Quando escrever o código para documentar um callback, pode ser útil imaginar que você é aquele *desenvolvedor externo*. E que você está atualmente implementando a *API externa*, não *sua API*. + +Adotar temporariamente esse ponto de vista (do *desenvolvedor externo*) pode ajudar a sentir que é mais óbvio onde colocar os parâmetros, o modelo Pydantic para o corpo, para a resposta, etc. para essa *API externa*. + +/// + +### Criar um `APIRouter` para o callback + +Primeiramente crie um novo `APIRouter` que conterá um ou mais callbacks. + +```Python hl_lines="3 25" +{!../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +### Crie a *operação de rota* do callback + +Para criar a *operação de rota* do callback, use o mesmo `APIRouter` que você criou acima. + +Ele deve parecer exatamente como uma *operação de rota* normal do FastAPI: + +* Ele provavelmente deveria ter uma declaração do corpo que deveria receber, por exemplo. `body: InvoiceEvent`. +* E também deveria ter uma declaração de um código de status de resposta, por exemplo. `response_model=InvoiceEventReceived`. + +```Python hl_lines="16-18 21-22 28-32" +{!../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +Há 2 diferenças principais de uma *operação de rota* normal: + +* Ela não necessita ter nenhum código real, porque seu aplicativo nunca chamará esse código. Ele é usado apenas para documentar a *API externa*. Então, a função poderia ter apenas `pass`. +* A *rota* pode conter uma expressão OpenAPI 3 (veja mais abaixo) onde pode usar variáveis com parâmetros e partes da solicitação original enviada para *sua API*. + +### A expressão do caminho do callback + +A *rota* do callback pode ter uma expressão OpenAPI 3 que pode conter partes da solicitação original enviada para *sua API*. + +Nesse caso, é a `str`: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +Então, se o usuário da sua API (o desenvolvedor externo) enviar uma solicitação para *sua API* para: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +com um corpo JSON de: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +então *sua API* processará a fatura e, em algum momento posterior, enviará uma solicitação de callback para o `callback_url` (a *API externa*): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +com um corpo JSON contendo algo como: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +e esperaria uma resposta daquela *API externa* com um corpo JSON como: + +```JSON +{ + "ok": true +} +``` + +/// tip | Dica + +Perceba como a URL de callback usada contém a URL recebida como um parâmetro de consulta em `callback_url` (`https://www.external.org/events`) e também o `id` da fatura de dentro do corpo JSON (`2expen51ve`). + +/// + +### Adicionar o roteador de callback + +Nesse ponto você tem a(s) *operação de rota de callback* necessária(s) (a(s) que o *desenvolvedor externo* deveria implementar na *API externa*) no roteador de callback que você criou acima. + +Agora use o parâmetro `callbacks` no decorador da *operação de rota de sua API* para passar o atributo `.routes` (que é na verdade apenas uma `list` de rotas/*operações de rota*) do roteador de callback que você criou acima: + +```Python hl_lines="35" +{!../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +/// tip | Dica + +Perceba que você não está passando o roteador em si (`invoices_callback_router`) para `callback=`, mas o atributo `.routes`, como em `invoices_callback_router.routes`. + +/// + +### Verifique a documentação + +Agora você pode iniciar seu aplicativo e ir para http://127.0.0.1:8000/docs. + +Você verá sua documentação incluindo uma seção "Callbacks" para sua *operação de rota* que mostra como a *API externa* deveria ser: + + diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md new file mode 100644 index 000000000..344fe6371 --- /dev/null +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -0,0 +1,57 @@ +# Webhooks OpenAPI + +Existem situações onde você deseja informar os **usuários** da sua API que a sua aplicação pode chamar a aplicação *deles* (enviando uma requisição) com alguns dados, normalmente para **notificar** algum tipo de **evento**. + +Isso significa que no lugar do processo normal de seus usuários enviarem requisições para a sua API, é a **sua API** (ou sua aplicação) que poderia **enviar requisições para o sistema deles** (para a API deles, a aplicação deles). + +Isso normalmente é chamado de **webhook**. + +## Etapas dos Webhooks + +Normalmente, o processo é que **você define** em seu código qual é a mensagem que você irá mandar, o **corpo da sua requisição**. + +Você também define de alguma maneira em quais **momentos** a sua aplicação mandará essas requisições ou eventos. + +E os **seus usuários** definem de alguma forma (em algum painel por exemplo) a **URL** que a sua aplicação deve enviar essas requisições. + +Toda a **lógica** sobre como cadastrar as URLs para os webhooks e o código para enviar de fato as requisições cabe a você definir. Você escreve da maneira que você desejar no **seu próprio código**. + +## Documentando webhooks com o FastAPI e OpenAPI + +Com o **FastAPI**, utilizando o OpenAPI, você pode definir os nomes destes webhooks, os tipos das operações HTTP que a sua aplicação pode enviar (e.g. `POST`, `PUT`, etc.) e os **corpos** da requisição que a sua aplicação enviaria. + +Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles. + +/// info | Informação + +Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`. + +/// + +## Uma aplicação com webhooks + +Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado `webhooks`, que você utilizar para defini-los da mesma maneira que você definiria as suas **operações de rotas**, utilizando por exemplo `@app.webhooks.post()`. + +```Python hl_lines="9-13 36-53" +{!../../docs_src/openapi_webhooks/tutorial001.py!} +``` + +Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. + +/// info | Informação + +O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos. + +/// + +Note que utilizando webhooks você não está de fato declarando uma **rota** (como `/items/`), o texto que informa é apenas um **identificador** do webhook (o nome do evento), por exemplo em `@app.webhooks.post("new-subscription")`, o nome do webhook é `new-subscription`. + +Isto porque espera-se que os **seus usuários** definam o verdadeiro **caminho da URL** onde eles desejam receber a requisição do webhook de algum outra maneira. (e.g. um painel). + +### Confira a documentação + +Agora você pode iniciar a sua aplicação e ir até http://127.0.0.1:8000/docs. + +Você verá que a sua documentação possui as *operações de rota* normais e agora também possui alguns **webhooks**: + + diff --git a/docs/pt/docs/advanced/path-operation-advanced-configuration.md b/docs/pt/docs/advanced/path-operation-advanced-configuration.md new file mode 100644 index 000000000..04f5cc9a3 --- /dev/null +++ b/docs/pt/docs/advanced/path-operation-advanced-configuration.md @@ -0,0 +1,212 @@ +# Configuração Avançada da Operação de Rota + +## operationId do OpenAPI + +/// warning | Aviso + +Se você não é um "especialista" no OpenAPI, você provavelmente não precisa disso. + +/// + +Você pode definir o `operationId` do OpenAPI que será utilizado na sua *operação de rota* com o parâmetro `operation_id`. + +Você precisa ter certeza que ele é único para cada operação. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} + +### Utilizando o nome da *função de operação de rota* como o operationId + +Se você quiser utilizar o nome das funções da sua API como `operationId`s, você pode iterar sobre todos esses nomes e sobrescrever o `operationId` em cada *operação de rota* utilizando o `APIRoute.name` dela. + +Você deve fazer isso depois de adicionar todas as suas *operações de rota*. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} + +/// tip | Dica + +Se você chamar `app.openapi()` manualmente, os `operationId`s devem ser atualizados antes dessa chamada. + +/// + +/// warning | Aviso + +Se você fizer isso, você tem que ter certeza de que cada uma das suas *funções de operação de rota* tem um nome único. + +Mesmo que elas estejam em módulos (arquivos Python) diferentes. + +/// + +## Excluir do OpenAPI + +Para excluir uma *operação de rota* do esquema OpenAPI gerado (e por consequência, dos sistemas de documentação automáticos), utilize o parâmetro `include_in_schema` e defina ele como `False`: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} + +## Descrição avançada a partir de docstring + +Você pode limitar as linhas utilizadas a partir de uma docstring de uma *função de operação de rota* para o OpenAPI. + +Adicionar um `\f` (um caractere de escape para alimentação de formulário) faz com que o **FastAPI** restrinja a saída utilizada pelo OpenAPI até esse ponto. + +Ele não será mostrado na documentação, mas outras ferramentas (como o Sphinx) serão capazes de utilizar o resto do texto. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} + +## Respostas Adicionais + +Você provavelmente já viu como declarar o `response_model` e `status_code` para uma *operação de rota*. + +Isso define os metadados sobre a resposta principal da *operação de rota*. + +Você também pode declarar respostas adicionais, com seus modelos, códigos de status, etc. + +Existe um capítulo inteiro da nossa documentação sobre isso, você pode ler em [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. + +## Extras do OpenAPI + +Quando você declara uma *operação de rota* na sua aplicação, o **FastAPI** irá gerar os metadados relevantes da *operação de rota* automaticamente para serem incluídos no esquema do OpenAPI. + +/// note | Nota + +Na especificação do OpenAPI, isso é chamado de um Objeto de Operação. + +/// + +Ele possui toda a informação sobre a *operação de rota* e é usado para gerar a documentação automaticamente. + +Ele inclui os atributos `tags`, `parameters`, `requestBody`, `responses`, etc. + +Esse esquema específico para uma *operação de rota* normalmente é gerado automaticamente pelo **FastAPI**, mas você também pode estender ele. + +/// tip | Dica + +Esse é um ponto de extensão de baixo nível. + +Caso você só precise declarar respostas adicionais, uma forma conveniente de fazer isso é com [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// + +Você pode estender o esquema do OpenAPI para uma *operação de rota* utilizando o parâmetro `openapi_extra`. + +### Extensões do OpenAPI + +Esse parâmetro `openapi_extra` pode ser útil, por exemplo, para declarar [Extensões do OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): + +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} + +Se você abrir os documentos criados automaticamente para a API, sua extensão aparecerá no final da *operação de rota* específica. + + + +E se você olhar o esquema OpenAPI resultante (na rota `/openapi.json` da sua API), você verá que a sua extensão também faz parte da *operação de rota* específica: + +```JSON hl_lines="22" +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + }, + "x-aperture-labs-portal": "blue" + } + } + } +} +``` + +### Esquema de *operação de rota* do OpenAPI personalizado + +O dicionário em `openapi_extra` vai ter todos os seus níveis mesclados dentro do esquema OpenAPI gerado automaticamente para a *operação de rota*. + +Então, você pode adicionar dados extras para o esquema gerado automaticamente. + +Por exemplo, você poderia optar por ler e validar a requisição com seu próprio código, sem utilizar funcionalidades automatizadas do FastAPI com o Pydantic, mas você ainda pode quere definir a requisição no esquema OpenAPI. + +Você pode fazer isso com `openapi_extra`: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36,39:40] *} + +Nesse exemplo, nós não declaramos nenhum modelo do Pydantic. Na verdade, o corpo da requisição não está nem mesmo analisado como JSON, ele é lido diretamente como `bytes` e a função `magic_data_reader()` seria a responsável por analisar ele de alguma forma. + +De toda forma, nós podemos declarar o esquema esperado para o corpo da requisição. + +### Tipo de conteúdo do OpenAPI personalizado + +Utilizando esse mesmo truque, você pode utilizar um modelo Pydantic para definir o esquema JSON que é então incluído na seção do esquema personalizado do OpenAPI na *operação de rota*. + +E você pode fazer isso até mesmo quando os dados da requisição não seguem o formato JSON. + +Por exemplo, nesta aplicação nós não usamos a funcionalidade integrada ao FastAPI de extrair o esquema JSON dos modelos Pydantic nem a validação automática do JSON. Na verdade, estamos declarando o tipo do conteúdo da requisição como YAML, em vez de JSON: + +//// tab | Pydantic v2 + +```Python hl_lines="17-22 24" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="17-22 24" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` + +//// + +/// info | Informação + +Na versão 1 do Pydantic, o método para obter o esquema JSON de um modelo é `Item.schema()`, na versão 2 do Pydantic, o método é `Item.model_json_schema()` + +/// + +Entretanto, mesmo que não utilizemos a funcionalidade integrada por padrão, ainda estamos usando um modelo Pydantic para gerar um esquema JSON manualmente para os dados que queremos receber no formato YAML. + +Então utilizamos a requisição diretamente, e extraímos o corpo como `bytes`. Isso significa que o FastAPI não vai sequer tentar analisar o corpo da requisição como JSON. + +E então no nosso código, nós analisamos o conteúdo YAML diretamente, e estamos utilizando o mesmo modelo Pydantic para validar o conteúdo YAML: + +//// tab | Pydantic v2 + +```Python hl_lines="26-33" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="26-33" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` + +//// + +/// info | Informação + +Na versão 1 do Pydantic, o método para analisar e validar um objeto era `Item.parse_obj()`, na versão 2 do Pydantic, o método é chamado de `Item.model_validate()`. + +/// + +///tip | Dica + +Aqui reutilizamos o mesmo modelo do Pydantic. + +Mas da mesma forma, nós poderíamos ter validado de alguma outra forma. + +/// diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md new file mode 100644 index 000000000..2ac5eca18 --- /dev/null +++ b/docs/pt/docs/advanced/response-change-status-code.md @@ -0,0 +1,33 @@ +# Retorno - Altere o Código de Status + +Você provavelmente leu anteriormente que você pode definir um [Código de Status do Retorno](../tutorial/response-status-code.md){.internal-link target=_blank} padrão. + +Porém em alguns casos você precisa retornar um código de status diferente do padrão. + +## Caso de uso + +Por exemplo, imagine que você deseja retornar um código de status HTTP de "OK" `200` por padrão. + +Mas se o dado não existir, você quer criá-lo e retornar um código de status HTTP de "CREATED" `201`. + +Mas você ainda quer ser capaz de filtrar e converter o dado que você retornará com um `response_model`. + +Para estes casos, você pode utilizar um parâmetro `Response`. + +## Use um parâmetro `Response` + +Você pode declarar um parâmetro do tipo `Response` em sua *função de operação de rota* (assim como você pode fazer para cookies e headers). + +E então você pode definir o `status_code` neste objeto de retorno temporal. + +```Python hl_lines="1 9 12" +{!../../docs_src/response_change_status_code/tutorial001.py!} +``` + +E então você pode retornar qualquer objeto que você precise, como você faria normalmente (um `dict`, um modelo de banco de dados, etc.). + +E se você declarar um `response_model`, ele ainda será utilizado para filtrar e converter o objeto que você retornou. + +O **FastAPI** utilizará este retorno *temporal* para extrair o código de status (e também cookies e headers), e irá colocá-los no retorno final que contém o valor que você retornou, filtrado por qualquer `response_model`. + +Você também pode declarar o parâmetro `Response` nas dependências, e definir o código de status nelas. Mas lembre-se que o último que for definido é o que prevalecerá. diff --git a/docs/pt/docs/advanced/response-cookies.md b/docs/pt/docs/advanced/response-cookies.md new file mode 100644 index 000000000..cd8f39db3 --- /dev/null +++ b/docs/pt/docs/advanced/response-cookies.md @@ -0,0 +1,55 @@ +# Cookies de Resposta + +## Usando um parâmetro `Response` + +Você pode declarar um parâmetro do tipo `Response` na sua *função de operação de rota*. + +E então você pode definir cookies nesse objeto de resposta *temporário*. + +```Python hl_lines="1 8-9" +{!../../docs_src/response_cookies/tutorial002.py!} +``` + +Em seguida, você pode retornar qualquer objeto que precise, como normalmente faria (um `dict`, um modelo de banco de dados, etc). + +E se você declarou um `response_model`, ele ainda será usado para filtrar e converter o objeto que você retornou. + +**FastAPI** usará essa resposta *temporária* para extrair os cookies (também os cabeçalhos e código de status) e os colocará na resposta final que contém o valor que você retornou, filtrado por qualquer `response_model`. + +Você também pode declarar o parâmetro `Response` em dependências e definir cookies (e cabeçalhos) nelas. + +## Retornando uma `Response` diretamente + +Você também pode criar cookies ao retornar uma `Response` diretamente no seu código. + +Para fazer isso, você pode criar uma resposta como descrito em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}. + +Então, defina os cookies nela e a retorne: + +```Python hl_lines="10-12" +{!../../docs_src/response_cookies/tutorial001.py!} +``` + +/// tip | Dica + +Lembre-se de que se você retornar uma resposta diretamente em vez de usar o parâmetro `Response`, FastAPI a retornará diretamente. + +Portanto, você terá que garantir que seus dados sejam do tipo correto. E.g. será compatível com JSON se você estiver retornando um `JSONResponse`. + +E também que você não esteja enviando nenhum dado que deveria ter sido filtrado por um `response_model`. + +/// + +### Mais informações + +/// note | Detalhes Técnicos + +Você também poderia usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`. + +**FastAPI** fornece as mesmas `starlette.responses` em `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette. + +E como o `Response` pode ser usado frequentemente para definir cabeçalhos e cookies, o **FastAPI** também o fornece em `fastapi.Response`. + +/// + +Para ver todos os parâmetros e opções disponíveis, verifique a documentação no Starlette. diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md new file mode 100644 index 000000000..fd2a0eef1 --- /dev/null +++ b/docs/pt/docs/advanced/response-directly.md @@ -0,0 +1,70 @@ +# Retornando uma Resposta Diretamente + +Quando você cria uma *operação de rota* no **FastAPI** você pode retornar qualquer dado nela: um dicionário (`dict`), uma lista (`list`), um modelo do Pydantic ou do seu banco de dados, etc. + +Por padrão, o **FastAPI** irá converter automaticamente o valor do retorno para JSON utilizando o `jsonable_encoder` explicado em [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +Então, por baixo dos panos, ele incluiria esses dados compatíveis com JSON (e.g. um `dict`) dentro de uma `JSONResponse` que é utilizada para enviar uma resposta para o cliente. + +Mas você pode retornar a `JSONResponse` diretamente nas suas *operações de rota*. + +Pode ser útil para retornar cabeçalhos e cookies personalizados, por exemplo. + +## Retornando uma `Response` + +Na verdade, você pode retornar qualquer `Response` ou subclasse dela. + +/// tip | Dica + +A própria `JSONResponse` é uma subclasse de `Response`. + +/// + +E quando você retorna uma `Response`, o **FastAPI** vai repassá-la diretamente. + +Ele não vai fazer conversões de dados com modelos do Pydantic, não irá converter a tipagem de nenhum conteúdo, etc. + +Isso te dá bastante flexibilidade. Você pode retornar qualquer tipo de dado, sobrescrever qualquer declaração e validação nos dados, etc. + +## Utilizando o `jsonable_encoder` em uma `Response` + +Como o **FastAPI** não realiza nenhuma mudança na `Response` que você retorna, você precisa garantir que o conteúdo dela está pronto para uso. + +Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` sem antes convertê-lo em um `dict` com todos os tipos de dados (como `datetime`, `UUID`, etc) convertidos para tipos compatíveis com JSON. + +Para esses casos, você pode usar o `jsonable_encoder` para converter seus dados antes de repassá-los para a resposta: + +```Python hl_lines="6-7 21-22" +{!../../docs_src/response_directly/tutorial001.py!} +``` + +/// note | Detalhes Técnicos + +Você também pode utilizar `from starlette.responses import JSONResponse`. + +**FastAPI** utiliza a mesma `starlette.responses` como `fastapi.responses` apenas como uma conveniência para você, desenvolvedor. Mas maior parte das respostas disponíveis vem diretamente do Starlette. + +/// + +## Retornando uma `Response` + +O exemplo acima mostra todas as partes que você precisa, mas ainda não é muito útil, já que você poderia ter retornado o `item` diretamente, e o **FastAPI** colocaria em uma `JSONResponse` para você, convertendo em um `dict`, etc. Tudo isso por padrão. + +Agora, vamos ver como você pode usar isso para retornar uma resposta personalizada. + +Vamos dizer quer retornar uma resposta XML. + +Você pode colocar o seu conteúdo XML em uma string, colocar em uma `Response`, e retorná-lo: + +```Python hl_lines="1 18" +{!../../docs_src/response_directly/tutorial002.py!} +``` + +## Notas + +Quando você retorna uma `Response` diretamente os dados não são validados, convertidos (serializados) ou documentados automaticamente. + +Mas você ainda pode documentar como descrito em [Retornos Adicionais no OpenAPI +](additional-responses.md){.internal-link target=_blank}. + +Você pode ver nas próximas seções como usar/declarar essas `Responses` customizadas enquanto mantém a conversão e documentação automática dos dados. diff --git a/docs/pt/docs/advanced/response-headers.md b/docs/pt/docs/advanced/response-headers.md new file mode 100644 index 000000000..98a7e0b6d --- /dev/null +++ b/docs/pt/docs/advanced/response-headers.md @@ -0,0 +1,45 @@ +# Cabeçalhos de resposta + +## Usando um parâmetro `Response` + +Você pode declarar um parâmetro do tipo `Response` na sua *função de operação de rota* (assim como você pode fazer para cookies). + +Então você pode definir os cabeçalhos nesse objeto de resposta *temporário*. + +```Python hl_lines="1 7-8" +{!../../docs_src/response_headers/tutorial002.py!} +``` + +Em seguida você pode retornar qualquer objeto que precisar, da maneira que faria normalmente (um `dict`, um modelo de banco de dados, etc.). + +Se você declarou um `response_model`, ele ainda será utilizado para filtrar e converter o objeto que você retornou. + +**FastAPI** usará essa resposta *temporária* para extrair os cabeçalhos (cookies e código de status também) e os colocará na resposta final que contém o valor que você retornou, filtrado por qualquer `response_model`. + +Você também pode declarar o parâmetro `Response` em dependências e definir cabeçalhos (e cookies) nelas. + +## Retornar uma `Response` diretamente + +Você também pode adicionar cabeçalhos quando retornar uma `Response` diretamente. + +Crie uma resposta conforme descrito em [Retornar uma resposta diretamente](response-directly.md){.internal-link target=_blank} e passe os cabeçalhos como um parâmetro adicional: + +```Python hl_lines="10-12" +{!../../docs_src/response_headers/tutorial001.py!} +``` + +/// note | Detalhes técnicos + +Você também pode usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`. + +**FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como uma conveniência para você, desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette. + +E como a `Response` pode ser usada frequentemente para definir cabeçalhos e cookies, **FastAPI** também a fornece em `fastapi.Response`. + +/// + +## Cabeçalhos personalizados + +Tenha em mente que cabeçalhos personalizados proprietários podem ser adicionados usando o prefixo 'X-'. + +Porém, se voce tiver cabeçalhos personalizados que deseja que um cliente no navegador possa ver, você precisa adicioná-los às suas configurações de CORS (saiba mais em [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), usando o parâmetro `expose_headers` descrito na documentação de CORS do Starlette. diff --git a/docs/pt/docs/advanced/security/http-basic-auth.md b/docs/pt/docs/advanced/security/http-basic-auth.md new file mode 100644 index 000000000..28c718f64 --- /dev/null +++ b/docs/pt/docs/advanced/security/http-basic-auth.md @@ -0,0 +1,192 @@ +# HTTP Basic Auth + +Para os casos mais simples, você pode utilizar o HTTP Basic Auth. + +No HTTP Basic Auth, a aplicação espera um cabeçalho que contém um usuário e uma senha. + +Caso ela não receba, ela retorna um erro HTTP 401 "Unauthorized" (*Não Autorizado*). + +E retorna um cabeçalho `WWW-Authenticate` com o valor `Basic`, e um parâmetro opcional `realm`. + +Isso sinaliza ao navegador para mostrar o prompt integrado para um usuário e senha. + +Então, quando você digitar o usuário e senha, o navegador os envia automaticamente no cabeçalho. + +## HTTP Basic Auth Simples + +* Importe `HTTPBasic` e `HTTPBasicCredentials`. +* Crie um "esquema `security`" utilizando `HTTPBasic`. +* Utilize o `security` com uma dependência em sua *operação de rota*. +* Isso retorna um objeto do tipo `HTTPBasicCredentials`: + * Isto contém o `username` e o `password` enviado. + +//// tab | Python 3.9+ + +```Python hl_lines="4 8 12" +{!> ../../docs_src/security/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 7 11" +{!> ../../docs_src/security/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="2 6 10" +{!> ../../docs_src/security/tutorial006.py!} +``` + +//// + +Quando você tentar abrir a URL pela primeira vez (ou clicar no botão "Executar" nos documentos) o navegador vai pedir pelo seu usuário e senha: + + + +## Verifique o usuário + +Aqui está um exemplo mais completo. + +Utilize uma dependência para verificar se o usuário e a senha estão corretos. + +Para isso, utilize o módulo padrão do Python `secrets` para verificar o usuário e senha. + +O `secrets.compare_digest()` necessita receber `bytes` ou `str` que possuem apenas caracteres ASCII (os em inglês). Isso significa que não funcionaria com caracteres como o `á`, como em `Sebastián`. + +Para lidar com isso, primeiramente nós convertemos o `username` e o `password` para `bytes`, codificando-os com UTF-8. + +Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `credentials.username` é `"stanleyjobson"`, e que o `credentials.password` é `"swordfish"`. + +//// tab | Python 3.9+ + +```Python hl_lines="1 12-24" +{!> ../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 12-24" +{!> ../../docs_src/security/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="1 11-21" +{!> ../../docs_src/security/tutorial007.py!} +``` + +//// + +Isso seria parecido com: + +```Python +if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): + # Return some error + ... +``` + +Porém, ao utilizar o `secrets.compare_digest()`, isso estará seguro contra um tipo de ataque chamado "timing attacks" (ataques de temporização). + +### Ataques de Temporização + +Mas o que é um "timing attack" (ataque de temporização)? + +Vamos imaginar que alguns invasores estão tentando adivinhar o usuário e a senha. + +E eles enviam uma requisição com um usuário `johndoe` e uma senha `love123`. + +Então o código Python em sua aplicação seria equivalente a algo como: + +```Python +if "johndoe" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Mas no exato momento que o Python compara o primeiro `j` em `johndoe` contra o primeiro `s` em `stanleyjobson`, ele retornará `False`, porque ele já sabe que aquelas duas strings não são a mesma, pensando que "não existe a necessidade de desperdiçar mais poder computacional comparando o resto das letras". E a sua aplicação dirá "Usuário ou senha incorretos". + +Então os invasores vão tentar com o usuário `stanleyjobsox` e a senha `love123`. + +E a sua aplicação faz algo como: + +```Python +if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +O Python terá que comparar todo o `stanleyjobso` tanto em `stanleyjobsox` como em `stanleyjobson` antes de perceber que as strings não são a mesma. Então isso levará alguns microssegundos a mais para retornar "Usuário ou senha incorretos". + +#### O tempo para responder ajuda os invasores + +Neste ponto, ao perceber que o servidor demorou alguns microssegundos a mais para enviar o retorno "Usuário ou senha incorretos", os invasores irão saber que eles acertaram _alguma coisa_, algumas das letras iniciais estavam certas. + +E eles podem tentar de novo sabendo que provavelmente é algo mais parecido com `stanleyjobsox` do que com `johndoe`. + +#### Um ataque "profissional" + +Claro, os invasores não tentariam tudo isso de forma manual, eles escreveriam um programa para fazer isso, possivelmente com milhares ou milhões de testes por segundo. E obteriam apenas uma letra a mais por vez. + +Mas fazendo isso, em alguns minutos ou horas os invasores teriam adivinhado o usuário e senha corretos, com a "ajuda" da nossa aplicação, apenas usando o tempo levado para responder. + +#### Corrija com o `secrets.compare_digest()` + +Mas em nosso código já estamos utilizando o `secrets.compare_digest()`. + +Resumindo, levará o mesmo tempo para comparar `stanleyjobsox` com `stanleyjobson` do que comparar `johndoe` com `stanleyjobson`. E o mesmo para a senha. + +Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação, ela estará a salvo contra toda essa gama de ataques de segurança. + + +### Retorne o erro + +Após detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente: + +//// tab | Python 3.9+ + +```Python hl_lines="26-30" +{!> ../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="26-30" +{!> ../../docs_src/security/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="23-27" +{!> ../../docs_src/security/tutorial007.py!} +``` + +//// diff --git a/docs/pt/docs/advanced/security/index.md b/docs/pt/docs/advanced/security/index.md new file mode 100644 index 000000000..6c7becb67 --- /dev/null +++ b/docs/pt/docs/advanced/security/index.md @@ -0,0 +1,19 @@ +# Segurança Avançada + +## Funcionalidades Adicionais + +Existem algumas funcionalidades adicionais para lidar com segurança além das cobertas em [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}. + +/// tip | Dica + +As próximas seções **não são necessariamente "avançadas"**. + +E é possível que para o seu caso de uso, a solução está em uma delas. + +/// + +## Leia o Tutorial primeiro + +As próximas seções pressupõem que você já leu o principal [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}. + +Todas elas são baseadas nos mesmos conceitos, mas permitem algumas funcionalidades extras. diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 000000000..49fb75944 --- /dev/null +++ b/docs/pt/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,786 @@ +# Escopos OAuth2 + +Você pode utilizar escopos do OAuth2 diretamente com o **FastAPI**, eles são integrados para funcionar perfeitamente. + +Isso permitiria que você tivesse um sistema de permissionamento mais refinado, seguindo o padrão do OAuth2 integrado na sua aplicação OpenAPI (e as documentações da API). + +OAuth2 com escopos é o mecanismo utilizado por muitos provedores de autenticação, como o Facebook, Google, GitHub, Microsoft, Twitter, etc. Eles utilizam isso para prover permissões específicas para os usuários e aplicações. + +Toda vez que você "se autentica com" Facebook, Google, GitHub, Microsoft, Twitter, aquela aplicação está utilizando o OAuth2 com escopos. + +Nesta seção, você verá como gerenciar a autenticação e autorização com os mesmos escopos do OAuth2 em sua aplicação **FastAPI**. + +/// warning | Aviso + +Isso é uma seção mais ou menos avançada. Se você está apenas começando, você pode pular. + +Você não necessariamente precisa de escopos do OAuth2, e você pode lidar com autenticação e autorização da maneira que você achar melhor. + +Mas o OAuth2 com escopos pode ser integrado de maneira fácil em sua API (com OpenAPI) e a sua documentação de API. + +No entando, você ainda aplica estes escopos, ou qualquer outro requisito de segurança/autorização, conforme necessário, em seu código. + +Em muitos casos, OAuth2 com escopos pode ser um exagero. + +Mas se você sabe que precisa, ou está curioso, continue lendo. + +/// + +## Escopos OAuth2 e OpenAPI + +A especificação OAuth2 define "escopos" como uma lista de strings separadas por espaços. + +O conteúdo de cada uma dessas strings pode ter qualquer formato, mas não devem possuir espaços. + +Estes escopos representam "permissões". + +No OpenAPI (e.g. os documentos da API), você pode definir "esquemas de segurança". + +Quando um desses esquemas de segurança utiliza OAuth2, você pode também declarar e utilizar escopos. + +Cada "escopo" é apenas uma string (sem espaços). + +Eles são normalmente utilizados para declarar permissões de segurança específicas, como por exemplo: + +* `users:read` or `users:write` são exemplos comuns. +* `instagram_basic` é utilizado pelo Facebook / Instagram. +* `https://www.googleapis.com/auth/drive` é utilizado pelo Google. + +/// info | Informação + +No OAuth2, um "escopo" é apenas uma string que declara uma permissão específica necessária. + +Não importa se ela contém outros caracteres como `:` ou se ela é uma URL. + +Estes detalhes são específicos da implementação. + +Para o OAuth2, eles são apenas strings. + +/// + +## Visão global + +Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial - Guia de Usuário** para [OAuth2 com Senha (e hash), Bearer com tokens JWT](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Agora utilizando escopos OAuth2: + +//// tab | Python 3.10+ + +```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// + +Agora vamos revisar essas mudanças passo a passo. + +## Esquema de segurança OAuth2 + +A primeira mudança é que agora nós estamos declarando o esquema de segurança OAuth2 com dois escopos disponíveis, `me` e `items`. + +O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descrição como valor: + +//// tab | Python 3.10+ + +```Python hl_lines="63-66" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="63-66" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="64-67" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="62-65" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="63-66" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="63-66" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// + +Pelo motivo de estarmos declarando estes escopos, eles aparecerão nos documentos da API quando você se autenticar/autorizar. + +E você poderá selecionar quais escopos você deseja dar acesso: `me` e `items`. + +Este é o mesmo mecanismo utilizado quando você adiciona permissões enquanto se autentica com o Facebook, Google, GitHub, etc: + + + +## Token JWT com escopos + +Agora, modifique o *caminho de rota* para retornar os escopos solicitados. + +Nós ainda estamos utilizando o mesmo `OAuth2PasswordRequestForm`. Ele inclui a propriedade `scopes` com uma `list` de `str`, com cada escopo que ele recebeu na requisição. + +E nós retornamos os escopos como parte do token JWT. + +/// danger | Cuidado + +Para manter as coisas simples, aqui nós estamos apenas adicionando os escopos recebidos diretamente ao token. + +Porém em sua aplicação, por segurança, você deve garantir que você apenas adiciona os escopos que o usuário possui permissão de fato, ou aqueles que você predefiniu. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="156" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="156" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="157" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="155" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="156" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="156" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// + +## Declare escopos em *operações de rota* e dependências + +Agora nós declaramos que a *operação de rota* para `/users/me/items/` exige o escopo `items`. + +Para isso, nós importamos e utilizamos `Security` de `fastapi`. + +Você pode utilizar `Security` para declarar dependências (assim como `Depends`), porém o `Security` também recebe o parâmetros `scopes` com uma lista de escopos (strings). + +Neste caso, nós passamos a função `get_current_active_user` como dependência para `Security` (da mesma forma que nós faríamos com `Depends`). + +Mas nós também passamos uma `list` de escopos, neste caso com apenas um escopo: `items` (poderia ter mais). + +E a função de dependência `get_current_active_user` também pode declarar subdependências, não apenas com `Depends`, mas também com `Security`. Ao declarar sua própria função de subdependência (`get_current_user`), e mais requisitos de escopo. + +Neste caso, ele requer o escopo `me` (poderia requerer mais de um escopo). + +/// note | Nota + +Você não necessariamente precisa adicionar diferentes escopos em diferentes lugares. + +Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escopos declarados em diferentes níveis. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="5 140 171" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="5 140 171" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="5 141 172" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="4 139 168" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="5 140 169" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="5 140 169" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// + +/// info | Informações Técnicas + +`Security` é na verdade uma subclasse de `Depends`, e ele possui apenas um parâmetro extra que veremos depois. + +Porém ao utilizar `Security` no lugar de `Depends`, o **FastAPI** saberá que ele pode declarar escopos de segurança, utilizá-los internamente, e documentar a API com o OpenAPI. + +Mas quando você importa `Query`, `Path`, `Depends`, `Security` entre outros de `fastapi`, eles são na verdade funções que retornam classes especiais. + +/// + +## Utilize `SecurityScopes` + +Agora atualize a dependência `get_current_user`. + +Este é o usado pelas dependências acima. + +Aqui é onde estamos utilizando o mesmo esquema OAuth2 que nós declaramos antes, declarando-o como uma dependência: `oauth2_scheme`. + +Porque esta função de dependência não possui nenhum requerimento de escopo, nós podemos utilizar `Depends` com o `oauth2_scheme`. Nós não precisamos utilizar `Security` quando nós não precisamos especificar escopos de segurança. + +Nós também declaramos um parâmetro especial do tipo `SecurityScopes`, importado de `fastapi.security`. + +A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utilizada para obter o objeto da requisição diretamente). + +//// tab | Python 3.10+ + +```Python hl_lines="9 106" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 106" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 107" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="8 105" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9 106" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9 106" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// + +## Utilize os `scopes` + +O parâmetro `security_scopes` será do tipo `SecurityScopes`. + +Ele terá a propriedade `scopes` com uma lista contendo todos os escopos requeridos por ele e todas as dependências que utilizam ele como uma subdependência. Isso significa, todos os "dependentes"... pode soar meio confuso, e isso será explicado novamente mais adiante. + +O objeto `security_scopes` (da classe `SecurityScopes`) também oferece um atributo `scope_str` com uma única string, contendo os escopos separados por espaços (nós vamos utilizar isso). + +Nós criamos uma `HTTPException` que nós podemos reutilizar (`raise`) mais tarde em diversos lugares. + +Nesta exceção, nós incluímos os escopos necessários (se houver algum) como uma string separada por espaços (utilizando `scope_str`). Nós colocamos esta string contendo os escopos no cabeçalho `WWW-Authenticate` (isso é parte da especificação). + +//// tab | Python 3.10+ + +```Python hl_lines="106 108-116" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="106 108-116" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="107 109-117" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="105 107-115" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="106 108-116" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="106 108-116" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// + +## Verifique o `username` e o formato dos dados + +Nós verificamos que nós obtemos um `username`, e extraímos os escopos. + +E depois nós validamos esse dado com o modelo Pydantic (capturando a exceção `ValidationError`), e se nós obtemos um erro ao ler o token JWT ou validando os dados com o Pydantic, nós levantamos a exceção `HTTPException` que criamos anteriormente. + +Para isso, nós atualizamos o modelo Pydantic `TokenData` com a nova propriedade `scopes`. + +Ao validar os dados com o Pydantic nós podemos garantir que temos, por exemplo, exatamente uma `list` de `str` com os escopos e uma `str` com o `username`. + +No lugar de, por exemplo, um `dict`, ou alguma outra coisa, que poderia quebrar a aplicação em algum lugar mais tarde, tornando isso um risco de segurança. + +Nós também verificamos que nós temos um usuário com o "*username*", e caso contrário, nós levantamos a mesma exceção que criamos anteriormente. + +//// tab | Python 3.10+ + +```Python hl_lines="47 117-128" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="47 117-128" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="48 118-129" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="46 116-127" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="47 117-128" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="47 117-128" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// + +## Verifique os `scopes` + +Nós verificamos agora que todos os escopos necessários, por essa dependência e todos os dependentes (incluindo as *operações de rota*) estão incluídas nos escopos fornecidos pelo token recebido, caso contrário, levantamos uma `HTTPException`. + +Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com todos esses escopos como uma `str`. + +//// tab | Python 3.10+ + +```Python hl_lines="129-135" +{!> ../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="129-135" +{!> ../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="130-136" +{!> ../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="128-134" +{!> ../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="129-135" +{!> ../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="129-135" +{!> ../../docs_src/security/tutorial005.py!} +``` + +//// + +## Árvore de dependência e escopos + +Vamos rever novamente essa árvore de dependência e os escopos. + +Como a dependência `get_current_active_user` possui uma subdependência em `get_current_user`, o escopo `"me"` declarado em `get_current_active_user` será incluído na lista de escopos necessários em `security_scopes.scopes` passado para `get_current_user`. + +A própria *operação de rota* também declara o escopo, `"items"`, então ele também estará na lista de `security_scopes.scopes` passado para o `get_current_user`. + +Aqui está como a hierarquia de dependências e escopos parecem: + +* A *operação de rota* `read_own_items` possui: + * Escopos necessários `["items"]` com a dependência: + * `get_current_active_user`: + * A função de dependência `get_current_active_user` possui: + * Escopos necessários `["me"]` com a dependência: + * `get_current_user`: + * A função de dependência `get_current_user` possui: + * Nenhum escopo necessário. + * Uma dependência utilizando `oauth2_scheme`. + * Um parâmetro `security_scopes` do tipo `SecurityScopes`: + * Este parâmetro `security_scopes` possui uma propriedade `scopes` com uma `list` contendo todos estes escopos declarados acima, então: + * `security_scopes.scopes` terá `["me", "items"]` para a *operação de rota* `read_own_items`. + * `security_scopes.scopes` terá `["me"]` para a *operação de rota* `read_users_me`, porque ela declarou na dependência `get_current_active_user`. + * `security_scopes.scopes` terá `[]` (nada) para a *operação de rota* `read_system_status`, porque ele não declarou nenhum `Security` com `scopes`, e sua dependência, `get_current_user`, não declara nenhum `scopes` também. + +/// tip | Dica + +A coisa importante e "mágica" aqui é que `get_current_user` terá diferentes listas de `scopes` para validar para cada *operação de rota*. + +Tudo depende dos `scopes` declarados em cada *operação de rota* e cada dependência da árvore de dependências para aquela *operação de rota* específica. + +/// + +## Mais detalhes sobre `SecurityScopes` + +Você pode utilizar `SecurityScopes` em qualquer lugar, e em diversos lugares. Ele não precisa estar na dependência "raiz". + +Ele sempre terá os escopos de segurança declarados nas dependências atuais de `Security` e todos os dependentes para **aquela** *operação de rota* **específica** e **aquela** árvore de dependência **específica**. + +Porque o `SecurityScopes` terá todos os escopos declarados por dependentes, você pode utilizá-lo para verificar se o token possui os escopos necessários em uma função de dependência central, e depois declarar diferentes requisitos de escopo em diferentes *operações de rota*. + +Todos eles serão validados independentemente para cada *operação de rota*. + +## Verifique + +Se você abrir os documentos da API, você pode antenticar e especificar quais escopos você quer autorizar. + + + +Se você não selecionar nenhum escopo, você terá "autenticado", mas quando você tentar acessar `/users/me/` ou `/users/me/items/`, você vai obter um erro dizendo que você não possui as permissões necessárias. Você ainda poderá acessar `/status/`. + +E se você selecionar o escopo `me`, mas não o escopo `items`, você poderá acessar `/users/me/`, mas não `/users/me/items/`. + +Isso é o que aconteceria se uma aplicação terceira que tentou acessar uma dessas *operações de rota* com um token fornecido por um usuário, dependendo de quantas permissões o usuário forneceu para a aplicação. + +## Sobre integrações de terceiros + +Neste exemplos nós estamos utilizando o fluxo de senha do OAuth2. + +Isso é apropriado quando nós estamos autenticando em nossa própria aplicação, provavelmente com o nosso próprio "*frontend*". + +Porque nós podemos confiar nele para receber o `username` e o `password`, pois nós controlamos isso. + +Mas se nós estamos construindo uma aplicação OAuth2 que outros poderiam conectar (i.e., se você está construindo um provedor de autenticação equivalente ao Facebook, Google, GitHub, etc.) você deveria utilizar um dos outros fluxos. + +O mais comum é o fluxo implícito. + +O mais seguro é o fluxo de código, mas ele é mais complexo para implementar, pois ele necessita mais passos. Como ele é mais complexo, muitos provedores terminam sugerindo o fluxo implícito. + +/// note | Nota + +É comum que cada provedor de autenticação nomeie os seus fluxos de forma diferente, para torná-lo parte de sua marca. + +Mas no final, eles estão implementando o mesmo padrão OAuth2. + +/// + +O **FastAPI** inclui utilitários para todos esses fluxos de autenticação OAuth2 em `fastapi.security.oauth2`. + +## `Security` em docoradores de `dependências` + +Da mesma forma que você pode definir uma `list` de `Depends` no parâmetro de `dependencias` do decorador (como explicado em [Dependências em decoradores de operações de rota](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), você também pode utilizar `Security` com escopos lá. diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md new file mode 100644 index 000000000..d32b70ed4 --- /dev/null +++ b/docs/pt/docs/advanced/settings.md @@ -0,0 +1,566 @@ +# Configurações e Variáveis de Ambiente + +Em muitos casos a sua aplicação pode precisar de configurações externas, como chaves secretas, credenciais de banco de dados, credenciais para serviços de email, etc. + +A maioria dessas configurações é variável (podem mudar), como URLs de bancos de dados. E muitas delas podem conter dados sensíveis, como tokens secretos. + +Por isso é comum prover essas configurações como variáveis de ambiente que são utilizidas pela aplicação. + +## Variáveis de Ambiente + +/// dica + +Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico. + +/// + +Uma variável de ambiente (abreviada em inglês para "env var") é uma variável definida fora do código Python, no sistema operacional, e pode ser lida pelo seu código Python (ou por outros programas). + +Você pode criar e utilizar variáveis de ambiente no terminal, sem precisar utilizar Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Você pode criar uma env var MY_NAME usando +$ export MY_NAME="Wade Wilson" + +// E utilizá-la em outros programas, como +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Criando env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Usando em outros programas, como +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +### Lendo variáveis de ambiente com Python + +Você também pode criar variáveis de ambiente fora do Python, no terminal (ou com qualquer outro método), e realizar a leitura delas no Python. + +Por exemplo, você pode definir um arquivo `main.py` com o seguinte código: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// dica + +O segundo parâmetro em `os.getenv()` é o valor padrão para o retorno. + +Se nenhum valor for informado, `None` é utilizado por padrão, aqui definimos `"World"` como o valor padrão a ser utilizado. + +/// + +E depois você pode executar esse arquivo: + +
+ +```console +// Aqui ainda não definimos a env var +$ python main.py + +// Por isso obtemos o valor padrão + +Hello World from Python + +// Mas se definirmos uma variável de ambiente primeiro +$ export MY_NAME="Wade Wilson" + +// E executarmos o programa novamente +$ python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python +``` + +
+ +Como variáveis de ambiente podem ser definidas fora do código da aplicação, mas acessadas pela aplicação, e não precisam ser armazenadas (versionadas com `git`) junto dos outros arquivos, é comum utilizá-las para guardar configurações. + +Você também pode criar uma variável de ambiente específica para uma invocação de um programa, que é acessível somente para esse programa, e somente enquanto ele estiver executando. + +Para fazer isso, crie a variável imediatamente antes de iniciar o programa, na mesma linha: + +
+ +```console +// Criando uma env var MY_NAME na mesma linha da execução do programa +$ MY_NAME="Wade Wilson" python main.py + +// Agora a aplicação consegue ler a variável de ambiente + +Hello Wade Wilson from Python + +// E a variável deixa de existir após isso +$ python main.py + +Hello World from Python +``` + +
+ +/// dica + +Você pode ler mais sobre isso em: The Twelve-Factor App: Configurações. + +/// + +### Tipagem e Validação + +Essas variáveis de ambiente suportam apenas strings, por serem externas ao Python e por que precisam ser compatíveis com outros programas e o resto do sistema (e até mesmo com outros sistemas operacionais, como Linux, Windows e macOS). + +Isso significa que qualquer valor obtido de uma variável de ambiente em Python terá o tipo `str`, e qualquer conversão para um tipo diferente ou validação deve ser realizada no código. + +## Pydantic `Settings` + +Por sorte, o Pydantic possui uma funcionalidade para lidar com essas configurações vindas de variáveis de ambiente utilizando Pydantic: Settings management. + +### Instalando `pydantic-settings` + +Primeiro, instale o pacote `pydantic-settings`: + +
+ +```console +$ pip install pydantic-settings +---> 100% +``` + +
+ +Ele também está incluído no fastapi quando você instala com a opção `all`: + +
+ +```console +$ pip install "fastapi[all]" +---> 100% +``` + +
+ +/// info + +Na v1 do Pydantic ele estava incluído no pacote principal. Agora ele está distribuido como um pacote independente para que você possa optar por instalar ou não caso você não precise dessa funcionalidade. + +/// + +### Criando o objeto `Settings` + +Importe a classe `BaseSettings` do Pydantic e crie uma nova subclasse, de forma parecida com um modelo do Pydantic. + +Os atributos da classe são declarados com anotações de tipo, e possíveis valores padrão, da mesma maneira que os modelos do Pydantic. + +Você pode utilizar todas as ferramentas e funcionalidades de validação que são utilizadas nos modelos do Pydantic, como tipos de dados diferentes e validações adicionei com `Field()`. + +//// tab | Pydantic v2 + +```Python hl_lines="2 5-8 11" +{!> ../../docs_src/settings/tutorial001.py!} +``` + +//// + +//// tab | Pydantic v1 + +/// info + +Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`. + +/// + +```Python hl_lines="2 5-8 11" +{!> ../../docs_src/settings/tutorial001_pv1.py!} +``` + +//// + +/// dica + +Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo. + +/// + +Portanto, quando você cria uma instância da classe `Settings` (nesse caso, o objeto `settings`), o Pydantic lê as variáveis de ambiente sem diferenciar maiúsculas e minúsculas, por isso, uma variável maiúscula `APP_NAME` será usada para o atributo `app_name`. + +Depois ele irá converter e validar os dados. Assim, quando você utilizar aquele objeto `settings`, os dados terão o tipo que você declarou (e.g. `items_per_user` será do tipo `int`). + +### Usando o objeto `settings` + +Depois, Você pode utilizar o novo objeto `settings` na sua aplicação: + +```Python hl_lines="18-20" +{!../../docs_src/settings/tutorial001.py!} +``` + +### Executando o servidor + +No próximo passo, você pode inicializar o servidor passando as configurações em forma de variáveis de ambiente, por exemplo, você poderia definir `ADMIN_EMAIL` e `APP_NAME` da seguinte forma: + +
+ +```console +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +/// dica + +Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando. + +/// + +Assim, o atributo `admin_email` seria definido como `"deadpool@example.com"`. + +`app_name` seria `"ChimichangApp"`. + +E `items_per_user` manteria o valor padrão de `50`. + +## Configurações em um módulo separado + +Você também pode incluir essas configurações em um arquivo de um módulo separado como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. + +Por exemplo, você pode adicionar um arquivo `config.py` com: + +```Python +{!../../docs_src/settings/app01/config.py!} +``` + +E utilizar essa configuração em `main.py`: + +```Python hl_lines="3 11-13" +{!../../docs_src/settings/app01/main.py!} +``` + +/// dica + +Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. + +/// + +## Configurações em uma dependência + +Em certas ocasiões, pode ser útil fornecer essas configurações a partir de uma dependência, em vez de definir um objeto global `settings` que é utilizado em toda a aplicação. + +Isso é especialmente útil durante os testes, já que é bastante simples sobrescrever uma dependência com suas configurações personalizadas. + +### O arquivo de configuração + +Baseando-se no exemplo anterior, seu arquivo `config.py` seria parecido com isso: + +```Python hl_lines="10" +{!../../docs_src/settings/app02/config.py!} +``` + +Perceba que dessa vez não criamos uma instância padrão `settings = Settings()`. + +### O arquivo principal da aplicação + +Agora criamos a dependência que retorna um novo objeto `config.Settings()`. + +//// tab | Python 3.9+ + +```Python hl_lines="6 12-13" +{!> ../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="6 12-13" +{!> ../../docs_src/settings/app02_an/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="5 11-12" +{!> ../../docs_src/settings/app02/main.py!} +``` + +//// + +/// dica + +Vamos discutir sobre `@lru_cache` logo mais. + +Por enquanto, você pode considerar `get_settings()` como uma função normal. + +/// + +E então podemos declarar essas configurações como uma dependência na função de operação da rota e utilizar onde for necessário. + +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="17 19-21" +{!> ../../docs_src/settings/app02_an/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="16 18-20" +{!> ../../docs_src/settings/app02/main.py!} +``` + +//// + +### Configurações e testes + +Então seria muito fácil fornecer uma configuração diferente durante a execução dos testes sobrescrevendo a dependência de `get_settings`: + +```Python hl_lines="9-10 13 21" +{!../../docs_src/settings/app02/test_main.py!} +``` + +Na sobrescrita da dependência, definimos um novo valor para `admin_email` quando instanciamos um novo objeto `Settings`, e então retornamos esse novo objeto. + +Após isso, podemos testar se o valor está sendo utilizado. + +## Lendo um arquivo `.env` + +Se você tiver muitas configurações que variem bastante, talvez em ambientes distintos, pode ser útil colocá-las em um arquivo e depois lê-las como se fossem variáveis de ambiente. + +Essa prática é tão comum que possui um nome, essas variáveis de ambiente normalmente são colocadas em um arquivo `.env`, e esse arquivo é chamado de "dotenv". + +/// dica + +Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS. + +Mas um arquivo dotenv não precisa ter esse nome exato. + +/// + +Pydantic suporta a leitura desses tipos de arquivos utilizando uma biblioteca externa. Você pode ler mais em Pydantic Settings: Dotenv (.env) support. + +/// dica + +Para que isso funcione você precisa executar `pip install python-dotenv`. + +/// + +### O arquivo `.env` + +Você pode definir um arquivo `.env` com o seguinte conteúdo: + +```bash +ADMIN_EMAIL="deadpool@example.com" +APP_NAME="ChimichangApp" +``` + +### Obtendo configurações do `.env` + +E então adicionar o seguinte código em `config.py`: + +//// tab | Pydantic v2 + +```Python hl_lines="9" +{!> ../../docs_src/settings/app03_an/config.py!} +``` + +/// dica + +O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. + +/// + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="9-10" +{!> ../../docs_src/settings/app03_an/config_pv1.py!} +``` + +/// dica + +A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. + +/// + +//// + +/// info + +Na versão 1 do Pydantic a configuração é realizada por uma classe interna `Config`, na versão 2 do Pydantic isso é feito com o atributo `model_config`. Esse atributo recebe um `dict`, para utilizar o autocomplete e checagem de erros do seu editor de texto você pode importar e utilizar `SettingsConfigDict` para definir esse `dict`. + +/// + +Aqui definimos a configuração `env_file` dentro da classe `Settings` do Pydantic, e definimos o valor como o nome do arquivo dotenv que queremos utilizar. + +### Declarando `Settings` apenas uma vez com `lru_cache` + +Ler o conteúdo de um arquivo em disco normalmente é uma operação custosa (lenta), então você provavelmente quer fazer isso apenas um vez e reutilizar o mesmo objeto settings depois, em vez de ler os valores a cada requisição. + +Mas cada vez que fazemos: + +```Python +Settings() +``` + +um novo objeto `Settings` é instanciado, e durante a instanciação, o arquivo `.env` é lido novamente. + +Se a função da dependência fosse apenas: + +```Python +def get_settings(): + return Settings() +``` + +Iriamos criar um novo objeto a cada requisição, e estaríamos lendo o arquivo `.env` a cada requisição. ⚠️ + +Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` é criado apenas uma vez, na primeira vez que a função é chamada. ✔️ + +//// tab | Python 3.9+ + +```Python hl_lines="1 11" +{!> ../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../docs_src/settings/app03_an/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="1 10" +{!> ../../docs_src/settings/app03/main.py!} +``` + +//// + +Dessa forma, todas as chamadas da função `get_settings()` nas dependências das próximas requisições, em vez de executar o código interno de `get_settings()` e instanciar um novo objeto `Settings`, irão retornar o mesmo objeto que foi retornado na primeira chamada, de novo e de novo. + +#### Detalhes Técnicos de `lru_cache` + +`@lru_cache` modifica a função decorada para retornar o mesmo valor que foi retornado na primeira vez, em vez de calculá-lo novamente, executando o código da função toda vez. + +Assim, a função abaixo do decorador é executada uma única vez para cada combinação dos argumentos passados. E os valores retornados para cada combinação de argumentos são sempre reutilizados para cada nova chamada da função com a mesma combinação de argumentos. + +Por exemplo, se você definir uma função: + +```Python +@lru_cache +def say_hi(name: str, salutation: str = "Ms."): + return f"Hello {salutation} {name}" +``` + +Seu programa poderia executar dessa forma: + +```mermaid +sequenceDiagram + +participant code as Código +participant function as say_hi() +participant execute as Executar Função + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Camila") + function ->> execute: executar código da função + execute ->> code: retornar o resultado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: retornar resultado armazenado + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick") + function ->> execute: executar código da função + execute ->> code: retornar o resultado + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick", salutation="Mr.") + function ->> execute: executar código da função + execute ->> code: retornar o resultado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Rick") + function ->> code: retornar resultado armazenado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: retornar resultado armazenado + end +``` + +No caso da nossa dependência `get_settings()`, a função não recebe nenhum argumento, então ela sempre retorna o mesmo valor. + +Dessa forma, ela se comporta praticamente como uma variável global, mas ao ser utilizada como uma função de uma dependência, pode facilmente ser sobrescrita durante os testes. + +`@lru_cache` é definido no módulo `functools` que faz parte da biblioteca padrão do Python, você pode ler mais sobre esse decorador no link Python Docs sobre `@lru_cache`. + +## Recapitulando + +Você pode usar o módulo Pydantic Settings para gerenciar as configurações de sua aplicação, utilizando todo o poder dos modelos Pydantic. + +- Utilizar dependências simplifica os testes. +- Você pode utilizar arquivos .env junto das configurações do Pydantic. +- Utilizar o decorador `@lru_cache` evita que o arquivo .env seja lido de novo e de novo para cada requisição, enquanto permite que você sobrescreva durante os testes. diff --git a/docs/pt/docs/advanced/sub-applications.md b/docs/pt/docs/advanced/sub-applications.md new file mode 100644 index 000000000..7f0381cc2 --- /dev/null +++ b/docs/pt/docs/advanced/sub-applications.md @@ -0,0 +1,73 @@ +# Sub Aplicações - Montagens + +Se você precisar ter duas aplicações FastAPI independentes, cada uma com seu próprio OpenAPI e suas próprias interfaces de documentação, você pode ter um aplicativo principal e "montar" uma (ou mais) sub-aplicações. + +## Montando uma aplicação **FastAPI** + +"Montar" significa adicionar uma aplicação completamente "independente" em um caminho específico, que então se encarrega de lidar com tudo sob esse caminho, com as operações de rota declaradas nessa sub-aplicação. + +### Aplicação de nível superior + +Primeiro, crie a aplicação principal, de nível superior, **FastAPI**, e suas *operações de rota*: + +```Python hl_lines="3 6-8" +{!../../docs_src/sub_applications/tutorial001.py!} +``` + +### Sub-aplicação + +Em seguida, crie sua sub-aplicação e suas *operações de rota*. + +Essa sub-aplicação é apenas outra aplicação FastAPI padrão, mas esta é a que será "montada": + +```Python hl_lines="11 14-16" +{!../../docs_src/sub_applications/tutorial001.py!} +``` + +### Monte a sub-aplicação + +Na sua aplicação de nível superior, `app`, monte a sub-aplicação, `subapi`. + +Neste caso, ela será montada no caminho `/subapi`: + +```Python hl_lines="11 19" +{!../../docs_src/sub_applications/tutorial001.py!} +``` + +### Verifique a documentação automática da API + +Agora, execute `uvicorn` com a aplicação principal, se o seu arquivo for `main.py`, seria: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +E abra a documentação em http://127.0.0.1:8000/docs. + +Você verá a documentação automática da API para a aplicação principal, incluindo apenas suas próprias _operações de rota_: + + + +E então, abra a documentação para a sub-aplicação, em http://127.0.0.1:8000/subapi/docs. + +Você verá a documentação automática da API para a sub-aplicação, incluindo apenas suas próprias _operações de rota_, todas sob o prefixo de sub-caminho correto `/subapi`: + + + +Se você tentar interagir com qualquer uma das duas interfaces de usuário, elas funcionarão corretamente, porque o navegador será capaz de se comunicar com cada aplicação ou sub-aplicação específica. + +### Detalhes Técnicos: `root_path` + +Quando você monta uma sub-aplicação como descrito acima, o FastAPI se encarrega de comunicar o caminho de montagem para a sub-aplicação usando um mecanismo da especificação ASGI chamado `root_path`. + +Dessa forma, a sub-aplicação saberá usar esse prefixo de caminho para a interface de documentação. + +E a sub-aplicação também poderia ter suas próprias sub-aplicações montadas e tudo funcionaria corretamente, porque o FastAPI lida com todos esses `root_path`s automaticamente. + +Você aprenderá mais sobre o `root_path` e como usá-lo explicitamente na seção sobre [Atrás de um Proxy](behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md index 3bada5e43..2314fed91 100644 --- a/docs/pt/docs/advanced/templates.md +++ b/docs/pt/docs/advanced/templates.md @@ -26,30 +26,37 @@ $ pip install jinja2 * Use o `template` que você criou para renderizar e retornar uma `TemplateResponse`, passe o nome do template, o request object, e um "context" dict com pares chave-valor a serem usados dentro do template do Jinja2. ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` -!!! note - Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro. +/// note - Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2. +Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro. +Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2. -!!! tip "Dica" - Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. +/// +/// tip | Dica -!!! note "Detalhes Técnicos" - Você também poderia usar `from starlette.templating import Jinja2Templates`. +Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. - **FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`. +/// + +/// note | Detalhes Técnicos + +Você também poderia usar `from starlette.templating import Jinja2Templates`. + +**FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`. + +/// ## Escrevendo Templates Então você pode escrever um template em `templates/item.html`, por exemplo: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### Interpolação de Valores no Template @@ -103,13 +110,13 @@ Por exemplo, com um ID de `42`, isso renderizará: Você também pode usar `url_for()` dentro do template e usá-lo, por examplo, com o `StaticFiles` que você montou com o `name="static"`. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` Neste exemplo, ele seria vinculado a um arquivo CSS em `static/styles.css` com: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` E como você está usando `StaticFiles`, este arquivo CSS será automaticamente servido pela sua aplicação FastAPI na URL `/static/styles.css`. diff --git a/docs/pt/docs/advanced/testing-dependencies.md b/docs/pt/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..94594e7e9 --- /dev/null +++ b/docs/pt/docs/advanced/testing-dependencies.md @@ -0,0 +1,103 @@ +# Testando Dependências com Sobreposição (Overrides) + +## Sobrepondo dependências durante os testes + +Existem alguns cenários onde você deseje sobrepor uma dependência durante os testes. + +Você não quer que a dependência original execute (e nenhuma das subdependências que você possa ter). + +Em vez disso, você deseja fornecer uma dependência diferente que será usada somente durante os testes (possivelmente apenas para alguns testes específicos) e fornecerá um valor que pode ser usado onde o valor da dependência original foi usado. + +### Casos de uso: serviço externo + +Um exemplo pode ser que você possua um provedor de autenticação externo que você precisa chamar. + +Você envia ao serviço um *token* e ele retorna um usuário autenticado. + +Este provedor pode cobrar por requisição, e chamá-lo pode levar mais tempo do que se você tivesse um usuário fixo para os testes. + +Você provavelmente quer testar o provedor externo uma vez, mas não necessariamente chamá-lo em todos os testes que executarem. + +Neste caso, você pode sobrepor (*override*) a dependência que chama o provedor, e utilizar uma dependência customizada que retorna um *mock* do usuário, apenas para os seus testes. + +### Utilize o atributo `app.dependency_overrides` + +Para estes casos, a sua aplicação **FastAPI** possui o atributo `app.dependency_overrides`. Ele é um simples `dict`. + +Para sobrepor a dependência para os testes, você coloca como chave a dependência original (a função), e como valor, a sua sobreposição da dependência (outra função). + +E então o **FastAPI** chamará a sobreposição no lugar da dependência original. + +//// tab | Python 3.10+ + +```Python hl_lines="26-27 30" +{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="28-29 32" +{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="29-30 33" +{!> ../../docs_src/dependency_testing/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="24-25 28" +{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="28-29 32" +{!> ../../docs_src/dependency_testing/tutorial001.py!} +``` + +//// + +/// tip | Dica + +Você pode definir uma sobreposição de dependência para uma dependência que é utilizada em qualquer lugar da sua aplicação **FastAPI**. + +A dependência original pode estar sendo utilizada em uma *função de operação de rota*, um *docorador de operação de rota* (quando você não utiliza o valor retornado), uma chamada ao `.include_router()`, etc. + +O FastAPI ainda poderá sobrescrevê-lo. + +/// + +E então você pode redefinir as suas sobreposições (removê-las) definindo o `app.dependency_overrides` como um `dict` vazio: + +```Python +app.dependency_overrides = {} +``` + +/// tip | Dica + +Se você quer sobrepor uma dependência apenas para alguns testes, você pode definir a sobreposição no início do testes (dentro da função de teste) e reiniciá-la ao final (no final da função de teste). + +/// diff --git a/docs/pt/docs/advanced/testing-events.md b/docs/pt/docs/advanced/testing-events.md new file mode 100644 index 000000000..b6796e835 --- /dev/null +++ b/docs/pt/docs/advanced/testing-events.md @@ -0,0 +1,7 @@ +# Testando Eventos: inicialização - encerramento + +Quando você precisa que os seus manipuladores de eventos (`startup` e `shutdown`) sejam executados em seus testes, você pode utilizar o `TestClient` usando a instrução `with`: + +```Python hl_lines="9-12 20-24" +{!../../docs_src/app_testing/tutorial003.py!} +``` diff --git a/docs/pt/docs/advanced/testing-websockets.md b/docs/pt/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..99e1a6db4 --- /dev/null +++ b/docs/pt/docs/advanced/testing-websockets.md @@ -0,0 +1,15 @@ +# Testando WebSockets + +Você pode usar o mesmo `TestClient` para testar WebSockets. + +Para isso, você utiliza o `TestClient` dentro de uma instrução `with`, conectando com o WebSocket: + +```Python hl_lines="27-31" +{!../../docs_src/app_testing/tutorial002.py!} +``` + +/// note | Nota + +Para mais detalhes, confira a documentação do Starlette para testar WebSockets. + +/// diff --git a/docs/pt/docs/advanced/using-request-directly.md b/docs/pt/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..df7e01833 --- /dev/null +++ b/docs/pt/docs/advanced/using-request-directly.md @@ -0,0 +1,58 @@ +# Utilizando o Request diretamente + +Até agora você declarou as partes da requisição que você precisa utilizando os seus tipos. + +Obtendo dados de: + +* Os parâmetros das rotas. +* Cabeçalhos (*Headers*). +* Cookies. +* etc. + +E ao fazer isso, o **FastAPI** está validando as informações, convertendo-as e gerando documentação para a sua API automaticamente. + +Porém há situações em que você possa precisar acessar o objeto `Request` diretamente. + +## Detalhes sobre o objeto `Request` + +Como o **FastAPI** é na verdade o **Starlette** por baixo, com camadas de diversas funcionalidades por cima, você pode utilizar o objeto `Request` do Starlette diretamente quando precisar. + +Isso significaria também que se você obtiver informações do objeto `Request` diretamente (ler o corpo da requisição por exemplo), as informações não serão validadas, convertidas ou documentadas (com o OpenAPI, para a interface de usuário automática da API) pelo FastAPI. + +Embora qualquer outro parâmetro declarado normalmente (o corpo da requisição com um modelo Pydantic, por exemplo) ainda seria validado, convertido, anotado, etc. + +Mas há situações específicas onde é útil utilizar o objeto `Request`. + +## Utilize o objeto `Request` diretamente + +Vamos imaginar que você deseja obter o endereço de IP/host do cliente dentro da sua *função de operação de rota*. + +Para isso você precisa acessar a requisição diretamente. + +```Python hl_lines="1 7-8" +{!../../docs_src/using_request_directly/tutorial001.py!} +``` + +Ao declarar o parâmetro com o tipo sendo um `Request` em sua *função de operação de rota*, o **FastAPI** saberá como passar o `Request` neste parâmetro. + +/// tip | Dica + +Note que neste caso, nós estamos declarando o parâmetro da rota ao lado do parâmetro da requisição. + +Assim, o parâmetro da rota será extraído, validado, convertido para o tipo especificado e anotado com OpenAPI. + +Do mesmo jeito, você pode declarar qualquer outro parâmetro normalmente, e além disso, obter o `Request` também. + +/// + +## Documentação do `Request` + +Você pode ler mais sobre os detalhes do objeto `Request` no site da documentação oficial do Starlette.. + +/// note | Detalhes Técnicos + +Você também pode utilizar `from starlette.requests import Request`. + +O **FastAPI** fornece isso diretamente apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente do Starlette. + +/// diff --git a/docs/pt/docs/advanced/websockets.md b/docs/pt/docs/advanced/websockets.md new file mode 100644 index 000000000..694f2bb5d --- /dev/null +++ b/docs/pt/docs/advanced/websockets.md @@ -0,0 +1,188 @@ +# WebSockets + +Você pode usar WebSockets com **FastAPI**. + +## Instalando `WebSockets` + +Garanta que você criou um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, o ativou e instalou o `websockets`: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## Cliente WebSockets + +### Em produção + +Em seu sistema de produção, você provavelmente tem um frontend criado com um framework moderno como React, Vue.js ou Angular. + +E para comunicar usando WebSockets com seu backend, você provavelmente usaria as utilidades do seu frontend. + +Ou você pode ter um aplicativo móvel nativo que se comunica diretamente com seu backend WebSocket, em código nativo. + +Ou você pode ter qualquer outra forma de comunicar com o endpoint WebSocket. + +--- + +Mas para este exemplo, usaremos um documento HTML muito simples com algum JavaScript, tudo dentro de uma string longa. + +Esse, é claro, não é o ideal e você não o usaria para produção. + +Na produção, você teria uma das opções acima. + +Mas é a maneira mais simples de focar no lado do servidor de WebSockets e ter um exemplo funcional: + +```Python hl_lines="2 6-38 41-43" +{!../../docs_src/websockets/tutorial001.py!} +``` + +## Criando um `websocket` + +Em sua aplicação **FastAPI**, crie um `websocket`: + +{*../../docs_src/websockets/tutorial001.py hl[46:47]*} + +/// note | Detalhes Técnicos + +Você também poderia usar `from starlette.websockets import WebSocket`. + +A **FastAPI** fornece o mesmo `WebSocket` diretamente apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente do Starlette. + +/// + +## Aguardar por mensagens e enviar mensagens + +Em sua rota WebSocket você pode esperar (`await`) por mensagens e enviar mensagens. + +{*../../docs_src/websockets/tutorial001.py hl[48:52]*} + +Você pode receber e enviar dados binários, de texto e JSON. + +## Tente você mesmo + +Se seu arquivo for nomeado `main.py`, execute sua aplicação com: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Abra seu navegador em: http://127.0.0.1:8000. + +Você verá uma página simples como: + + + +Você pode digitar mensagens na caixa de entrada e enviá-las: + + + +E sua aplicação **FastAPI** com WebSockets responderá de volta: + + + +Você pode enviar (e receber) muitas mensagens: + + + +E todas elas usarão a mesma conexão WebSocket. + +## Usando `Depends` e outros + +Nos endpoints WebSocket você pode importar do `fastapi` e usar: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +Eles funcionam da mesma forma que para outros endpoints FastAPI/*operações de rota*: + +{*../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82]*} + +/// info | Informação + +Como isso é um WebSocket, não faz muito sentido levantar uma `HTTPException`, em vez disso levantamos uma `WebSocketException`. + +Você pode usar um código de fechamento dos códigos válidos definidos na especificação. + +/// + +### Tente os WebSockets com dependências + +Se seu arquivo for nomeado `main.py`, execute sua aplicação com: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Abrar seu browser em: http://127.0.0.1:8000. + +Lá você pode definir: + +* O "Item ID", usado na rota. +* O "Token" usado como um parâmetro de consulta. + +/// tip | Dica + +Perceba que a consulta `token` será manipulada por uma dependência. + +/// + +Com isso você pode conectar o WebSocket e então enviar e receber mensagens: + + + +## Lidando com desconexões e múltiplos clientes + +Quando uma conexão WebSocket é fechada, o `await websocket.receive_text()` levantará uma exceção `WebSocketDisconnect`, que você pode então capturar e lidar como neste exemplo. + +{*../../docs_src/websockets/tutorial003_py39.py hl[79:81]*} + +Para testar: + +* Abrar o aplicativo com várias abas do navegador. +* Escreva mensagens a partir delas. +* Então feche uma das abas. + +Isso levantará a exceção `WebSocketDisconnect`, e todos os outros clientes receberão uma mensagem como: + +``` +Client #1596980209979 left the chat +``` + +/// tip | Dica + +O app acima é um exemplo mínimo e simples para demonstrar como lidar e transmitir mensagens para várias conexões WebSocket. + +Mas tenha em mente que, como tudo é manipulado na memória, em uma única lista, ele só funcionará enquanto o processo estiver em execução e só funcionará com um único processo. + +Se você precisa de algo fácil de integrar com o FastAPI, mas que seja mais robusto, suportado por Redis, PostgreSQL ou outros, verifique o encode/broadcaster. + +/// + +## Mais informações + +Para aprender mais sobre as opções, verifique a documentação do Starlette para: + +* A classe `WebSocket`. +* Manipulação de WebSockets baseada em classes. diff --git a/docs/pt/docs/advanced/wsgi.md b/docs/pt/docs/advanced/wsgi.md new file mode 100644 index 000000000..e6d08c8db --- /dev/null +++ b/docs/pt/docs/advanced/wsgi.md @@ -0,0 +1,37 @@ +# Adicionando WSGI - Flask, Django, entre outros + +Como você viu em [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank} e [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}, você pode **"montar"** aplicações WSGI. + +Para isso, você pode utilizar o `WSGIMiddleware` para encapsular a sua aplicação WSGI, como por exemplo Flask, Django, etc. + +## Usando o `WSGIMiddleware` + +Você precisa importar o `WSGIMiddleware`. + +Em seguinda, encapsular a aplicação WSGI (e.g. Flask) com o middleware. + +E então **"montar"** em um caminho de rota. + +```Python hl_lines="2-3 23" +{!../../docs_src/wsgi/tutorial001.py!} +``` + +## Conferindo + +Agora todas as requisições sob o caminho `/v1/` serão manipuladas pela aplicação utilizando Flask. + +E o resto será manipulado pelo **FastAPI**. + +Se você rodar a aplicação e ir até http://localhost:8000/v1/, você verá o retorno do Flask: + +```txt +Hello, World from Flask! +``` + +E se você for até http://localhost:8000/v2, você verá o retorno do FastAPI: + +```JSON +{ + "message": "Hello World" +} +``` diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md index ba721536f..29c9693bb 100644 --- a/docs/pt/docs/alternatives.md +++ b/docs/pt/docs/alternatives.md @@ -1,6 +1,6 @@ # Alternativas, Inspiração e Comparações -O que inspirou **FastAPI**, como ele se compara a outras alternativas e o que FastAPI aprendeu delas. +O que inspirou o **FastAPI**, como ele se compara às alternativas e o que FastAPI aprendeu delas. ## Introdução @@ -30,11 +30,17 @@ Ele é utilizado por muitas companhias incluindo Mozilla, Red Hat e Eventbrite. Ele foi um dos primeiros exemplos de **documentação automática de API**, e essa foi especificamente uma das primeiras idéias que inspirou "a busca por" **FastAPI**. -!!! note "Nota" - Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado. +/// note | Nota -!!! check "**FastAPI** inspirado para" - Ter uma documentação automática da API em interface web. +Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado. + +/// + +/// check | **FastAPI** inspirado para + +Ter uma documentação automática da API em interface web. + +/// ### Flask @@ -50,10 +56,13 @@ Esse desacoplamento de partes, e sendo um "microframework" que pode ser extendid Dada a simplicidade do Flask, parecia uma ótima opção para construção de APIs. A próxima coisa a procurar era um "Django REST Framework" para Flask. -!!! check "**FastAPI** inspirado para" - Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias. +/// check | **FastAPI** inspirado para - Ser simples e com sistema de roteamento fácil de usar. +Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias. + +Ser simples e com sistema de roteamento fácil de usar. + +/// ### Requests @@ -89,10 +98,13 @@ def read_url(): Veja as similaridades em `requests.get(...)` e `@app.get(...)`. -!!! check "**FastAPI** inspirado para" - * Ter uma API simples e intuitiva. - * Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo. - * Ter padrões sensíveis, mas customizações poderosas. +/// check | **FastAPI** inspirado para + +* Ter uma API simples e intuitiva. +* Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo. +* Ter padrões sensíveis, mas customizações poderosas. + +/// ### Swagger / OpenAPI @@ -106,15 +118,18 @@ Em algum ponto, Swagger foi dado para a Fundação Linux, e foi renomeado OpenAP Isso acontece porquê quando alguém fala sobre a versão 2.0 é comum dizer "Swagger", e para a versão 3+, "OpenAPI". -!!! check "**FastAPI** inspirado para" - Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado. +/// check | **FastAPI** inspirado para + +Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado. + +E integrar ferramentas de interface para usuários baseado nos padrões: - E integrar ferramentas de interface para usuários baseado nos padrões: +* Swagger UI +* ReDoc - * Swagger UI - * ReDoc +Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**). - Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**). +/// ### Flask REST frameworks @@ -132,8 +147,11 @@ Esses recursos são o que Marshmallow foi construído para fornecer. Ele é uma Mas ele foi criado antes da existência do _type hints_ do Python. Então, para definir todo o _schema_ você precisa utilizar específicas ferramentas e classes fornecidas pelo Marshmallow. -!!! check "**FastAPI** inspirado para" - Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação. +/// check | **FastAPI** inspirado para + +Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação. + +/// ### Webargs @@ -145,11 +163,17 @@ Ele utiliza Marshmallow por baixo para validação de dados. E ele foi criado pe Ele é uma grande ferramenta e eu também a utilizei muito, antes de ter o **FastAPI**. -!!! info - Webargs foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +Webargs foi criado pelos mesmos desenvolvedores do Marshmallow. -!!! check "**FastAPI** inspirado para" - Ter validação automática de dados vindos de requisições. +/// + +/// check | **FastAPI** inspirado para + +Ter validação automática de dados vindos de requisições. + +/// ### APISpec @@ -169,11 +193,17 @@ Mas então, nós temos novamente o problema de ter uma micro-sintaxe, dentro de O editor não poderá ajudar muito com isso. E se nós modificarmos os parâmetros dos _schemas_ do Marshmallow e esquecer de modificar também aquela _docstring_ YAML, o _schema_ gerado pode ficar obsoleto. -!!! info - APISpec foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +APISpec foi criado pelos mesmos desenvolvedores do Marshmallow. + +/// + +/// check | **FastAPI** inspirado para -!!! check "**FastAPI** inspirado para" - Dar suporte a padrões abertos para APIs, OpenAPI. +Dar suporte a padrões abertos para APIs, OpenAPI. + +/// ### Flask-apispec @@ -185,7 +215,7 @@ Ele utiliza a informação do Webargs e Marshmallow para gerar automaticamente _ Isso resolveu o problema de ter que escrever YAML (outra sintaxe) dentro das _docstrings_ Python. -Essa combinação de Flask, Flask-apispec com Marshmallow e Webargs foi meu _backend stack_ favorito até construir **FastAPI**. +Essa combinação de Flask, Flask-apispec com Marshmallow e Webargs foi meu _backend stack_ favorito até construir o **FastAPI**. Usando essa combinação levou a criação de vários geradores Flask _full-stack_. Há muitas _stacks_ que eu (e vários times externos) estou utilizando até agora: @@ -195,11 +225,17 @@ Usando essa combinação levou a criação de vários geradores Flask _full-stac E esses mesmos geradores _full-stack_ foram a base dos [Geradores de Projetos **FastAPI**](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow. + +/// -!!! check "**FastAPI** inspirado para" - Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação. +/// check | **FastAPI** inspirado para + +Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação. + +/// ### NestJS (and Angular) @@ -207,7 +243,7 @@ NestJS, que não é nem Python, é um framework NodeJS JavaScript (TypeScript) i Ele alcança de uma forma similar ao que pode ser feito com o Flask-apispec. -Ele tem um sistema de injeção de dependência integrado, inspirado pelo Angular dois. É necessário fazer o pré-registro dos "injetáveis" (como todos os sistemas de injeção de dependência que conheço), então, adicionando verbosidade e repetição de código. +Ele tem um sistema de injeção de dependência integrado, inspirado pelo Angular 2. É necessário fazer o pré-registro dos "injetáveis" (como todos os sistemas de injeção de dependência que conheço), então, adicionando verbosidade e repetição de código. Como os parâmetros são descritos com tipos TypeScript (similar aos _type hints_ do Python), o suporte ao editor é muito bom. @@ -215,24 +251,33 @@ Mas como os dados TypeScript não são preservados após a compilação para o J Ele também não controla modelos aninhados muito bem. Então, se o corpo JSON na requisição for um objeto JSON que contém campos internos que contém objetos JSON aninhados, ele não consegue ser validado e documentado apropriadamente. -!!! check "**FastAPI** inspirado para" - Usar tipos Python para ter um ótimo suporte do editor. +/// check | **FastAPI** inspirado para + +Usar tipos Python para ter um ótimo suporte do editor. - Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código. +Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código. + +/// ### Sanic Ele foi um dos primeiros frameworks Python extremamente rápido baseado em `asyncio`. Ele foi feito para ser muito similar ao Flask. -!!! note "Detalhes técnicos" - Ele utiliza `uvloop` ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido. +/// note | Detalhes técnicos + +Ele utiliza `uvloop` ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido. + +Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos. + +/// - Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos. +/// check | **FastAPI** inspirado para -!!! check "**FastAPI** inspirado para" - Achar um jeito de ter uma performance insana. +Achar um jeito de ter uma performance insana. - É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros). +É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros). + +/// ### Falcon @@ -244,12 +289,15 @@ Ele é projetado para ter funções que recebem dois parâmetros, uma "requisiç Então, validação de dados, serialização e documentação tem que ser feitos no código, não automaticamente. Ou eles terão que ser implementados como um framework acima do Falcon, como o Hug. Essa mesma distinção acontece em outros frameworks que são inspirados pelo design do Falcon, tendo um objeto de requisição e um objeto de resposta como parâmetros. -!!! check "**FastAPI** inspirado para" - Achar jeitos de conseguir melhor performance. +/// check | **FastAPI** inspirado para + +Achar jeitos de conseguir melhor performance. + +Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta` nas funções. - Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta`nas funções. +Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos. - Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos. +/// ### Molten @@ -267,12 +315,15 @@ O sistema de injeção de dependência exige pré-registro das dependências e a Rotas são declaradas em um único lugar, usando funções declaradas em outros lugares (ao invés de usar decoradores que possam ser colocados diretamente acima da função que controla o _endpoint_). Isso é mais perto de como o Django faz isso do que como Flask (e Starlette) faz. Ele separa no código coisas que são relativamente amarradas. -!!! check "**FastAPI** inspirado para" - Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes. +/// check | **FastAPI** inspirado para - Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic). +Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes. -### Hug +Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic). + +/// + +### Hug Hug foi um dos primeiros frameworks a implementar a declaração de tipos de parâmetros usando Python _type hints_. Isso foi uma ótima idéia que inspirou outras ferramentas a fazer o mesmo. @@ -286,15 +337,21 @@ Hug tinha um incomum, interessante recurso: usando o mesmo framework, é possív Como é baseado nos padrões anteriores de frameworks web síncronos (WSGI), ele não pode controlar _Websockets_ e outras coisas, embora ele ainda tenha uma alta performance também. -!!! info - Hug foi criado por Timothy Crosley, o mesmo criador do `isort`, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python. +/// info + +Hug foi criado por Timothy Crosley, o mesmo criador do `isort`, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python. + +/// + +/// check | Idéias inspiradas para o **FastAPI** + +Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar. -!!! check "Idéias inspiradas para o **FastAPI**" - Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar. +Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente. - Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente. +Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies. - Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies. +/// ### APIStar (<= 0.5) @@ -320,23 +377,29 @@ Ele não era mais um framework web API, como o criador precisava focar no Starle Agora APIStar é um conjunto de ferramentas para validar especificações OpenAPI, não um framework web. -!!! info - APIStar foi criado por Tom Christie. O mesmo cara que criou: +/// info - * Django REST Framework - * Starlette (no qual **FastAPI** é baseado) - * Uvicorn (usado por Starlette e **FastAPI**) +APIStar foi criado por Tom Christie. O mesmo cara que criou: -!!! check "**FastAPI** inspirado para" - Existir. +* Django REST Framework +* Starlette (no qual **FastAPI** é baseado) +* Uvicorn (usado por Starlette e **FastAPI**) - A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia. +/// - E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível. +/// check | **FastAPI** inspirado para - Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**. +Existir. - Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima. +A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia. + +E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível. + +Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**. + +Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima. + +/// ## Usados por **FastAPI** @@ -348,10 +411,13 @@ Isso faz dele extremamente intuitivo. Ele é comparável ao Marshmallow. Embora ele seja mais rápido que Marshmallow em testes de performance. E ele é baseado nos mesmos Python _type hints_, o suporte ao editor é ótimo. -!!! check "**FastAPI** usa isso para" - Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema). +/// check | **FastAPI** usa isso para + +Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema). + +**FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz. - **FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz. +/// ### Starlette @@ -366,7 +432,7 @@ Ele tem: * Suporte a GraphQL. * Tarefas de processamento interno por trás dos panos. * Eventos de inicialização e encerramento. -* Cliente de testes construído com requests. +* Cliente de testes construído com HTTPX. * Respostas CORS, GZip, Arquivos Estáticos, Streaming. * Suporte para Sessão e Cookie. * 100% coberto por testes. @@ -381,17 +447,23 @@ Mas ele não fornece validação de dados automática, serialização e document Essa é uma das principais coisas que **FastAPI** adiciona no topo, tudo baseado em Python _type hints_ (usando Pydantic). Isso, mais o sistema de injeção de dependência, utilidades de segurança, geração de _schema_ OpenAPI, etc. -!!! note "Detalhes Técnicos" - ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso. +/// note | Detalhes Técnicos - No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`. +ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso. -!!! check "**FastAPI** usa isso para" - Controlar todas as partes web centrais. Adiciona recursos no topo. +No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`. - A classe `FastAPI` em si herda `Starlette`. +/// - Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides. +/// check | **FastAPI** usa isso para + +Controlar todas as partes web centrais. Adiciona recursos no topo. + +A classe `FastAPI` em si herda `Starlette`. + +Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides. + +/// ### Uvicorn @@ -401,12 +473,15 @@ Ele não é um framework web, mas sim um servidor. Por exemplo, ele não fornece Ele é o servidor recomendado para Starlette e **FastAPI**. -!!! check "**FastAPI** recomenda isso para" - O principal servidor web para rodar aplicações **FastAPI**. +/// check | **FastAPI** recomenda isso para + +O principal servidor web para rodar aplicações **FastAPI**. + +Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono. - Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono. +Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}. - Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}. +/// ## Performance e velocidade diff --git a/docs/pt/docs/async.md b/docs/pt/docs/async.md index fe2363386..0d6bdbf0e 100644 --- a/docs/pt/docs/async.md +++ b/docs/pt/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - Você só pode usar `await` dentro de funções criadas com `async def`. +/// note + +Você só pode usar `await` dentro de funções criadas com `async def`. + +/// --- @@ -261,7 +264,7 @@ Mas você também pode explorar os benefícios do paralelismo e multiprocessamen Isso, mais o simples fato que Python é a principal linguagem para **Data Science**, Machine Learning e especialmente Deep Learning, faz do FastAPI uma ótima escolha para APIs web e aplicações com Data Science / Machine Learning (entre muitas outras). -Para ver como alcançar esse paralelismo em produção veja a seção sobre [Deployment](deployment.md){.internal-link target=_blank}. +Para ver como alcançar esse paralelismo em produção veja a seção sobre [Deployment](deployment/index.md){.internal-link target=_blank}. ## `async` e `await` @@ -356,12 +359,15 @@ Tudo isso é o que deixa o FastAPI poderoso (através do Starlette) e que o faz ## Detalhes muito técnicos -!!! warning - Você pode provavelmente pular isso. +/// warning + +Você pode provavelmente pular isso. + +Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô. - Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô. +Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente. - Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente. +/// ### Funções de operação de rota diff --git a/docs/pt/docs/contributing.md b/docs/pt/docs/contributing.md index 02895fcfc..bb518a2fa 100644 --- a/docs/pt/docs/contributing.md +++ b/docs/pt/docs/contributing.md @@ -24,72 +24,85 @@ Isso criará o diretório `./env/` com os binários Python e então você será Ative o novo ambiente com: -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
- Ou se você usa Bash para Windows (por exemplo Git Bash): +//// -
+//// tab | Windows Bash - ```console - $ source ./env/Scripts/activate - ``` +Ou se você usa Bash para Windows (por exemplo Git Bash): -
+
+ +```console +$ source ./env/Scripts/activate +``` + +
+ +//// Para verificar se funcionou, use: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ Get-Command pip +
- some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip -
+some/directory/fastapi/env/bin/pip +``` + +
+ +//// Se ele exibir o binário `pip` em `env/bin/pip` então funcionou. 🎉 -!!! tip - Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente. +/// tip + +Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente. - Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente. +Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente. + +/// ### pip @@ -153,8 +166,11 @@ A documentação usa _pull requests_ existentes para a sua linguagem e faça revisões das alterações e aprove elas. +* Verifique sempre os _pull requests_ existentes para a sua linguagem e faça revisões das alterações e aprove elas. + +/// tip + +Você pode adicionar comentários com sugestões de alterações para _pull requests_ existentes. -!!! tip - Você pode adicionar comentários com sugestões de alterações para _pull requests_ existentes. +Verifique as documentações sobre adicionar revisão ao _pull request_ para aprovação ou solicitação de alterações. - Verifique as documentações sobre adicionar revisão ao _pull request_ para aprovação ou solicitação de alterações. +/// -* Verifique em _issues_ para ver se existe alguém coordenando traduções para a sua linguagem. +* Verifique em _issues_ para ver se existe alguém coordenando traduções para a sua linguagem. * Adicione um único _pull request_ por página traduzida. Isso tornará muito mais fácil a revisão para as outras pessoas. @@ -264,8 +283,11 @@ Vamos dizer que você queira traduzir uma página para uma linguagem que já ten No caso do Espanhol, o código de duas letras é `es`. Então, o diretório para traduções em Espanhol está localizada em `docs/es/`. -!!! tip - A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`. +/// tip + +A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`. + +/// Agora rode o _servidor ao vivo_ para as documentações em Espanhol: @@ -302,8 +324,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - Observe que a única mudança na rota é o código da linguagem, de `en` para `es`. +/// tip + +Observe que a única mudança na rota é o código da linguagem, de `en` para `es`. + +/// * Agora abra o arquivo de configuração MkDocs para Inglês em: @@ -374,10 +399,13 @@ Updating en Agora você pode verificar em seu editor de código o mais novo diretório criado `docs/ht/`. -!!! tip - Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções. +/// tip + +Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções. + +Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀 - Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀 +/// Inicie traduzindo a página principal, `docs/ht/index.md`. diff --git a/docs/pt/docs/deployment.md b/docs/pt/docs/deployment.md deleted file mode 100644 index 2272467fd..000000000 --- a/docs/pt/docs/deployment.md +++ /dev/null @@ -1,394 +0,0 @@ -# Implantação - -Implantar uma aplicação **FastAPI** é relativamente fácil. - -Existem vários modos de realizar o _deploy_ dependendo de seu caso de uso específico e as ferramentas que você utiliza. - -Você verá mais sobre alguns modos de fazer o _deploy_ nas próximas seções. - -## Versões do FastAPI - -**FastAPI** já está sendo utilizado em produção em muitas aplicações e sistemas. E a cobertura de teste é mantida a 100%. Mas seu desenvolvimento continua andando rapidamente. - -Novos recursos são adicionados frequentemente, _bugs_ são corrigidos regularmente, e o código está continuamente melhorando. - -É por isso que as versões atuais estão ainda no `0.x.x`, isso reflete que cada versão poderia ter potencialmente alterações que podem quebrar. Isso segue as convenções de Versionamento Semântico. - -Você pode criar aplicações para produção com **FastAPI** bem agora (e você provavelmente já faça isso por um tempo), você tem que ter certeza de utilizar uma versão que funcione corretamente com o resto do seu código. - -### Anote sua versão `fastapi` - -A primeira coisa que você deve fazer é "fixar" a versão do **FastAPI** que está utilizando para a última versão específica que você sabe que funciona corretamente para a sua aplicação. - -Por exemplo, vamos dizer que você esteja utilizando a versão `0.45.0` no seu _app_. - -Se você usa um arquivo `requirements.txt`, dá para especificar a versão assim: - -```txt -fastapi==0.45.0 -``` - -isso significa que você pode usar exatamente a versão `0.45.0`. - -Ou você poderia fixar assim: - -```txt -fastapi>=0.45.0,<0.46.0 -``` - -o que significa que você pode usar as versões `0.45.0` ou acima, mas menor que `0.46.0`. Por exemplo, a versão `0.45.2` poderia ser aceita. - -Se você usa qualquer outra ferramenta para gerenciar suas instalações, como Poetry, Pipenv ou outro, todos terão um modo que você possa usar para definir versões específicas para seus pacotes. - -### Versões disponíveis - -Você pode ver as versões disponíveis (por exemplo, para verificar qual é a versão atual) nas [Notas de Lançamento](release-notes.md){.internal-link target=_blank}. - -### Sobre as versões - -Seguindo as convenções do Versionamento Semântico, qualquer versão abaixo de `1.0.0` pode potencialmente adicionar mudanças que quebrem. - -FastAPI também segue a convenção que qualquer versão de _"PATCH"_ seja para ajustes de _bugs_ e mudanças que não quebrem a aplicação. - -!!! tip - O _"PATCH"_ é o último número, por exemplo, em `0.2.3`, a versão do _PATCH_ é `3`. - -Então, você poderia ser capaz de fixar para uma versão como: - -```txt -fastapi>=0.45.0,<0.46.0 -``` - -Mudanças que quebram e novos recursos são adicionados em versões _"MINOR"_. - -!!! tip - O _"MINOR"_ é o número do meio, por exemplo, em `0.2.3`, a versão _MINOR_ é `2`. - -### Atualizando as versões FastAPI - -Você pode adicionar testes em sua aplicação. - -Com o **FastAPI** é muito fácil (graças ao Starlette), verifique a documentação: [Testando](tutorial/testing.md){.internal-link target=_blank} - -Após você ter os testes, então você pode fazer o _upgrade_ da versão **FastAPI** para uma mais recente, e ter certeza que todo seu código esteja funcionando corretamente rodando seus testes. - -Se tudo estiver funcionando, ou após você fazer as alterações necessárias, e todos seus testes estiverem passando, então você poderá fixar o `fastapi` para a versão mais recente. - -### Sobre Starlette - -Você não deve fixar a versão do `starlette`. - -Versões diferentes do **FastAPI** irão utilizar uma versão mais nova específica do Starlette. - -Então, você pode deixar que o **FastAPI** use a versão correta do Starlette. - -### Sobre Pydantic - -Pydantic inclui os testes para **FastAPI** em seus próprios testes, então novas versões do Pydantic (acima de `1.0.0`) são sempre compatíveis com FastAPI. - -Você pode fixar o Pydantic para qualquer versão acima de `1.0.0` e abaixo de `2.0.0` que funcionará. - -Por exemplo: - -```txt -pydantic>=1.2.0,<2.0.0 -``` - -## Docker - -Nessa seção você verá instruções e _links_ para guias de saber como: - -* Fazer uma imagem/container da sua aplicação **FastAPI** com máxima performance. Em aproximadamente **5 min**. -* (Opcionalmente) entender o que você, como desenvolvedor, precisa saber sobre HTTPS. -* Inicializar um _cluster_ Docker Swarm Mode com HTTPS automático, mesmo em um simples servidor de $5 dólares/mês. Em aproximadamente **20 min**. -* Gere e implante uma aplicação **FastAPI** completa, usando seu _cluster_ Docker Swarm, com HTTPS etc. Em aproxiamadamente **10 min**. - -Você pode usar **Docker** para implantação. Ele tem várias vantagens como segurança, replicabilidade, desenvolvimento simplificado etc. - -Se você está usando Docker, você pode utilizar a imagem Docker oficial: - -### tiangolo/uvicorn-gunicorn-fastapi - -Essa imagem tem um mecanismo incluído de "auto-ajuste", para que você possa apenas adicionar seu código e ter uma alta performance automaticamente. E sem fazer sacrifícios. - -Mas você pode ainda mudar e atualizar todas as configurações com variáveis de ambiente ou arquivos de configuração. - -!!! tip - Para ver todas as configurações e opções, vá para a página da imagem do Docker: tiangolo/uvicorn-gunicorn-fastapi. - -### Crie um `Dockerfile` - -* Vá para o diretório de seu projeto. -* Crie um `Dockerfile` com: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 - -COPY ./app /app -``` - -#### Grandes aplicações - -Se você seguiu a seção sobre criação de [Grandes Aplicações com Múltiplos Arquivos](tutorial/bigger-applications.md){.internal-link target=_blank}, seu `Dockerfile` poderia parecer como: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 - -COPY ./app /app/app -``` - -#### Raspberry Pi e outras arquiteturas - -Se você estiver rodando Docker em um Raspberry Pi (que possui um processador ARM) ou qualquer outra arquitetura, você pode criar um `Dockerfile` do zero, baseado em uma imagem base Python (que é multi-arquitetural) e utilizar Uvicorn sozinho. - -Nesse caso, seu `Dockerfile` poderia parecer assim: - -```Dockerfile -FROM python:3.7 - -RUN pip install fastapi uvicorn - -EXPOSE 80 - -COPY ./app /app - -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] -``` - -### Crie o código **FastAPI** - -* Crie um diretório `app` e entre nele. -* Crie um arquivo `main.py` com: - -```Python -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/") -def read_root(): - return {"Hello": "World"} - - -@app.get("/items/{item_id}") -def read_item(item_id: int, q: str = None): - return {"item_id": item_id, "q": q} -``` - -* Você deve ter uma estrutura de diretórios assim: - -``` -. -├── app -│ └── main.py -└── Dockerfile -``` - -### Construa a imagem Docker - -* Vá para o diretório do projeto (onde seu `Dockerfile` está, contendo seu diretório `app`. -* Construa sua imagem FastAPI: - -
- -```console -$ docker build -t myimage . - ----> 100% -``` - -
- -### Inicie o container Docker - -* Rode um container baseado em sua imagem: - -
- -```console -$ docker run -d --name mycontainer -p 80:80 myimage -``` - -
- -Agora você tem um servidor FastAPI otimizado em um container Docker. Auto-ajustado para seu servidor atual (e número de núcleos de CPU). - -### Verifique - -Você deve ser capaz de verificar na URL de seu container Docker, por exemplo: http://192.168.99.100/items/5?q=somequery ou http://127.0.0.1/items/5?q=somequery (ou equivalente, usando seu _host_ Docker). - -Você verá algo como: - -```JSON -{"item_id": 5, "q": "somequery"} -``` - -### API interativa de documetação - -Agora você pode ir para http://192.168.99.100/docs ou http://127.0.0.1/docs (ou equivalente, usando seu _host_ Docker). - -Você verá a API interativa de documentação (fornecida por Swagger UI): - -![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) - -### APIs alternativas de documentação - -E você pode também ir para http://192.168.99.100/redoc ou http://127.0.0.1/redoc (ou equivalente, usando seu _host_ Docker). - -Você verá a documentação automática alternativa (fornecida por ReDoc): - -![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) - -## HTTPS - -### Sobre HTTPS - -É fácil assumir que HTTPS seja algo que esteja apenas "habilitado" ou não. - -Mas ele é um pouquinho mais complexo do que isso. - -!!! tip - Se você está com pressa ou não se importa, continue na próxima seção com instruções passo a passo para configurar tudo. - -Para aprender o básico de HTTPS, pela perspectiva de um consumidor, verifique https://howhttps.works/. - -Agora, pela perspectiva de um desenvolvedor, aqui estão algumas coisas para se ter em mente enquanto se pensa sobre HTTPS: - -* Para HTTPS, o servidor precisa ter "certificados" gerados por terceiros. - * Esses certificados são na verdade adquiridos por terceiros, não "gerados". -* Certificados tem um prazo de uso. - * Eles expiram. - * E então eles precisam ser renovados, adquiridos novamente por terceiros. -* A encriptação da conexão acontece no nível TCP. - * TCP é uma camada abaixo do HTTP. - * Então, o controle de certificado e encriptação é feito antes do HTTP. -* TCP não conhece nada sobre "domínios". Somente sobre endereços IP. - * A informação sobre o domínio requisitado vai nos dados HTTP. -* Os certificados HTTPS "certificam" um certo domínio, mas o protocolo e a encriptação acontecem no nível TCP, antes de saber qual domínio está sendo lidado. -* Por padrão, isso significa que você pode ter somente um certificado HTTPS por endereço IP. - * Não importa quão grande é seu servidor ou quão pequena cada aplicação que você tenha possar ser. - * No entanto, existe uma solução para isso. -* Existe uma extensão para o protocolo TLS (o que controla a encriptação no nível TCP, antes do HTTP) chamada SNI. - * Essa extensão SNI permite um único servidor (com um único endereço IP) a ter vários certificados HTTPS e servir múltiplas aplicações/domínios HTTPS. - * Para que isso funcione, um único componente (programa) rodando no servidor, ouvindo no endereço IP público, deve ter todos os certificados HTTPS no servidor. -* Após obter uma conexão segura, o protocolo de comunicação ainda é HTTP. - * O conteúdo está encriptado, mesmo embora ele esteja sendo enviado com o protocolo HTTP. - -É uma prática comum ter um servidor HTTP/programa rodando no servidor (a máquina, _host_ etc.) e gerenciar todas as partes HTTP: enviar as requisições HTTP decriptadas para a aplicação HTTP rodando no mesmo servidor (a aplicação **FastAPI**, nesse caso), pega a resposta HTTP da aplicação, encripta utilizando o certificado apropriado e enviando de volta para o cliente usando HTTPS. Esse servidor é frequentemente chamado TLS _Termination Proxy_. - -### Vamos encriptar - -Antes de encriptar, esses certificados HTTPS foram vendidos por terceiros de confiança. - -O processo para adquirir um desses certificados costumava ser chato, exigia muita papelada e eram bem caros. - -Mas então _Let's Encrypt_ foi criado. - -É um projeto da Fundação Linux.Ele fornece certificados HTTPS de graça. De um jeito automatizado. Esses certificados utilizam todos os padrões de segurança criptográfica, e tem vida curta (cerca de 3 meses), para que a segurança seja melhor devido ao seu curto período de vida. - -Os domínios são seguramente verificados e os certificados são gerados automaticamente. Isso também permite automatizar a renovação desses certificados. - -A idéia é automatizar a aquisição e renovação desses certificados, para que você possa ter um HTTPS seguro, grátis, para sempre. - -### Traefik - -Traefik é um _proxy_ reverso / _load balancer_ de alta performance. Ele pode fazer o trabalho do _"TLS Termination Proxy"_ (à parte de outros recursos). - -Ele tem integração com _Let's Encrypt_. Assim, ele pode controlar todas as partes HTTPS, incluindo a aquisição e renovação de certificados. - -Ele também tem integrações com Docker. Assim, você pode declarar seus domínios em cada configuração de aplicação e leitura dessas configurações, gerando os certificados HTTPS e servindo o HTTPS para sua aplicação automaticamente, sem exigir qualquer mudança em sua configuração. - ---- - -Com essas ferramentas e informações, continue com a próxima seção para combinar tudo. - -## _Cluster_ de Docker Swarm Mode com Traefik e HTTPS - -Você pode ter um _cluster_ de Docker Swarm Mode configurado em minutos (cerca de 20) com o Traefik controlando HTTPS (incluindo aquisição e renovação de certificados). - -Utilizando o Docker Swarm Mode, você pode iniciar com um _"cluster"_ de apenas uma máquina (que pode até ser um servidor por 5 dólares / mês) e então você pode aumentar conforme a necessidade adicionando mais servidores. - -Para configurar um _cluster_ Docker Swarm Mode com Traefik controlando HTTPS, siga essa orientação: - -### Docker Swarm Mode and Traefik for an HTTPS cluster - -### Faça o _deploy_ de uma aplicação FastAPI - -O jeito mais fácil de configurar tudo pode ser utilizando o [Gerador de Projetos **FastAPI**](project-generation.md){.internal-link target=_blank}. - -Ele é designado para ser integrado com esse _cluster_ Docker Swarm com Traefik e HTTPS descrito acima. - -Você pode gerar um projeto em cerca de 2 minutos. - -O projeto gerado tem instruções para fazer o _deploy_, fazendo isso leva outros 2 minutos. - -## Alternativamente, faça o _deploy_ **FastAPI** sem Docker - -Você pode fazer o _deploy_ do **FastAPI** diretamente sem o Docker também. - -Você apenas precisa instalar um servidor ASGI compatível como: - -=== "Uvicorn" - - * Uvicorn, um servidor ASGI peso leve, construído sobre uvloop e httptools. - -
- - ```console - $ pip install "uvicorn[standard]" - - ---> 100% - ``` - -
- -=== "Hypercorn" - - * Hypercorn, um servidor ASGI também compatível com HTTP/2. - -
- - ```console - $ pip install hypercorn - - ---> 100% - ``` - -
- - ...ou qualquer outro servidor ASGI. - -E rode sua applicação do mesmo modo que você tem feito nos tutoriais, mas sem a opção `--reload`, por exemplo: - -=== "Uvicorn" - -
- - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 - - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` - -
- -=== "Hypercorn" - -
- - ```console - $ hypercorn main:app --bind 0.0.0.0:80 - - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` - -
- -Você deve querer configurar mais algumas ferramentas para ter certeza que ele seja reinicializado automaticamante se ele parar. - -Você também deve querer instalar Gunicorn e utilizar ele como um gerenciador para o Uvicorn, ou usar Hypercorn com múltiplos _workers_. - -Tenha certeza de ajustar o número de _workers_ etc. - -Mas se você estiver fazendo tudo isso, você pode apenas usar uma imagem Docker que fará isso automaticamente. diff --git a/docs/pt/docs/deployment/cloud.md b/docs/pt/docs/deployment/cloud.md new file mode 100644 index 000000000..e6522f50f --- /dev/null +++ b/docs/pt/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# Implantar FastAPI em provedores de nuvem + +Você pode usar praticamente **qualquer provedor de nuvem** para implantar seu aplicativo FastAPI. + +Na maioria dos casos, os principais provedores de nuvem têm guias para implantar o FastAPI com eles. + +## Provedores de Nuvem - Patrocinadores + +Alguns provedores de nuvem ✨ [**patrocinam o FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, o que garante o **desenvolvimento** contínuo e saudável do FastAPI e seu **ecossistema**. + +E isso mostra seu verdadeiro comprometimento com o FastAPI e sua **comunidade** (você), pois eles não querem apenas fornecer a você um **bom serviço**, mas também querem ter certeza de que você tenha uma **estrutura boa e saudável**, o FastAPI. 🙇 + +Talvez você queira experimentar os serviços deles e seguir os guias: + +* Platform.sh +* Porter +* Coherence diff --git a/docs/pt/docs/deployment/concepts.md b/docs/pt/docs/deployment/concepts.md new file mode 100644 index 000000000..8cf70d0b4 --- /dev/null +++ b/docs/pt/docs/deployment/concepts.md @@ -0,0 +1,321 @@ +# Conceitos de Implantações + +Ao implantar um aplicativo **FastAPI**, ou na verdade, qualquer tipo de API da web, há vários conceitos com os quais você provavelmente se importa e, usando-os, você pode encontrar a maneira **mais apropriada** de **implantar seu aplicativo**. + +Alguns dos conceitos importantes são: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Etapas anteriores antes de iniciar + +Veremos como eles afetariam as **implantações**. + +No final, o principal objetivo é ser capaz de **atender seus clientes de API** de uma forma **segura**, **evitar interrupções** e usar os **recursos de computação** (por exemplo, servidores remotos/máquinas virtuais) da forma mais eficiente possível. 🚀 + +Vou lhe contar um pouco mais sobre esses **conceitos** aqui, e espero que isso lhe dê a **intuição** necessária para decidir como implantar sua API em ambientes muito diferentes, possivelmente até mesmo em **futuros** ambientes que ainda não existem. + +Ao considerar esses conceitos, você será capaz de **avaliar e projetar** a melhor maneira de implantar **suas próprias APIs**. + +Nos próximos capítulos, darei a você mais **receitas concretas** para implantar aplicativos FastAPI. + +Mas por enquanto, vamos verificar essas importantes **ideias conceituais**. Esses conceitos também se aplicam a qualquer outro tipo de API da web. 💡 + +## Segurança - HTTPS + +No [capítulo anterior sobre HTTPS](https.md){.internal-link target=_blank} aprendemos como o HTTPS fornece criptografia para sua API. + +Também vimos que o HTTPS normalmente é fornecido por um componente **externo** ao seu servidor de aplicativos, um **Proxy de terminação TLS**. + +E tem que haver algo responsável por **renovar os certificados HTTPS**, pode ser o mesmo componente ou pode ser algo diferente. + +### Ferramentas de exemplo para HTTPS + +Algumas das ferramentas que você pode usar como um proxy de terminação TLS são: + +* Traefik + * Lida automaticamente com renovações de certificados ✨ +* Caddy + * Lida automaticamente com renovações de certificados ✨ +* Nginx + * Com um componente externo como o Certbot para renovações de certificados +* HAProxy + * Com um componente externo como o Certbot para renovações de certificados +* Kubernetes com um controlador Ingress como o Nginx + * Com um componente externo como cert-manager para renovações de certificados +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços (leia abaixo 👇) + +Outra opção é que você poderia usar um **serviço de nuvem** que faz mais do trabalho, incluindo a configuração de HTTPS. Ele pode ter algumas restrições ou cobrar mais, etc. Mas, nesse caso, você não teria que configurar um Proxy de terminação TLS sozinho. + +Mostrarei alguns exemplos concretos nos próximos capítulos. + +--- + +Os próximos conceitos a serem considerados são todos sobre o programa que executa sua API real (por exemplo, Uvicorn). + +## Programa e Processo + +Falaremos muito sobre o "**processo**" em execução, então é útil ter clareza sobre o que ele significa e qual é a diferença com a palavra "**programa**". + +### O que é um Programa + +A palavra **programa** é comumente usada para descrever muitas coisas: + +* O **código** que você escreve, os **arquivos Python**. +* O **arquivo** que pode ser **executado** pelo sistema operacional, por exemplo: `python`, `python.exe` ou `uvicorn`. +* Um programa específico enquanto está **em execução** no sistema operacional, usando a CPU e armazenando coisas na memória. Isso também é chamado de **processo**. + +### O que é um Processo + +A palavra **processo** normalmente é usada de forma mais específica, referindo-se apenas ao que está sendo executado no sistema operacional (como no último ponto acima): + +* Um programa específico enquanto está **em execução** no sistema operacional. + * Isso não se refere ao arquivo, nem ao código, refere-se **especificamente** à coisa que está sendo **executada** e gerenciada pelo sistema operacional. +* Qualquer programa, qualquer código, **só pode fazer coisas** quando está sendo **executado**. Então, quando há um **processo em execução**. +* O processo pode ser **terminado** (ou "morto") por você, ou pelo sistema operacional. Nesse ponto, ele para de rodar/ser executado, e ele **não pode mais fazer coisas**. +* Cada aplicativo que você tem em execução no seu computador tem algum processo por trás dele, cada programa em execução, cada janela, etc. E normalmente há muitos processos em execução **ao mesmo tempo** enquanto um computador está ligado. +* Pode haver **vários processos** do **mesmo programa** em execução ao mesmo tempo. + +Se você verificar o "gerenciador de tarefas" ou o "monitor do sistema" (ou ferramentas semelhantes) no seu sistema operacional, poderá ver muitos desses processos em execução. + +E, por exemplo, você provavelmente verá que há vários processos executando o mesmo programa de navegador (Firefox, Chrome, Edge, etc.). Eles normalmente executam um processo por aba, além de alguns outros processos extras. + + + +--- + +Agora que sabemos a diferença entre os termos **processo** e **programa**, vamos continuar falando sobre implantações. + +## Executando na inicialização + +Na maioria dos casos, quando você cria uma API web, você quer que ela esteja **sempre em execução**, ininterrupta, para que seus clientes possam sempre acessá-la. Isso é claro, a menos que você tenha um motivo específico para querer que ela seja executada somente em certas situações, mas na maioria das vezes você quer que ela esteja constantemente em execução e **disponível**. + +### Em um servidor remoto + +Ao configurar um servidor remoto (um servidor em nuvem, uma máquina virtual, etc.), a coisa mais simples que você pode fazer é usar `fastapi run` (que usa Uvicorn) ou algo semelhante, manualmente, da mesma forma que você faz ao desenvolver localmente. + +E funcionará e será útil **durante o desenvolvimento**. + +Mas se sua conexão com o servidor for perdida, o **processo em execução** provavelmente morrerá. + +E se o servidor for reiniciado (por exemplo, após atualizações ou migrações do provedor de nuvem), você provavelmente **não notará**. E por causa disso, você nem saberá que precisa reiniciar o processo manualmente. Então, sua API simplesmente permanecerá inativa. 😱 + +### Executar automaticamente na inicialização + +Em geral, você provavelmente desejará que o programa do servidor (por exemplo, Uvicorn) seja iniciado automaticamente na inicialização do servidor e, sem precisar de nenhuma **intervenção humana**, tenha um processo sempre em execução com sua API (por exemplo, Uvicorn executando seu aplicativo FastAPI). + +### Programa separado + +Para conseguir isso, você normalmente terá um **programa separado** que garantiria que seu aplicativo fosse executado na inicialização. E em muitos casos, ele também garantiria que outros componentes ou aplicativos também fossem executados, por exemplo, um banco de dados. + +### Ferramentas de exemplo para executar na inicialização + +Alguns exemplos de ferramentas que podem fazer esse trabalho são: + +* Docker +* Kubernetes +* Docker Compose +* Docker em Modo Swarm +* Systemd +* Supervisor +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços +* Outros... + +Darei exemplos mais concretos nos próximos capítulos. + +## Reinicializações + +Semelhante a garantir que seu aplicativo seja executado na inicialização, você provavelmente também deseja garantir que ele seja **reiniciado** após falhas. + +### Nós cometemos erros + +Nós, como humanos, cometemos **erros** o tempo todo. O software quase *sempre* tem **bugs** escondidos em lugares diferentes. 🐛 + +E nós, como desenvolvedores, continuamos aprimorando o código à medida que encontramos esses bugs e implementamos novos recursos (possivelmente adicionando novos bugs também 😅). + +### Pequenos erros são tratados automaticamente + +Ao criar APIs da web com FastAPI, se houver um erro em nosso código, o FastAPI normalmente o conterá na única solicitação que acionou o erro. 🛡 + +O cliente receberá um **Erro Interno do Servidor 500** para essa solicitação, mas o aplicativo continuará funcionando para as próximas solicitações em vez de travar completamente. + +### Erros maiores - Travamentos + +No entanto, pode haver casos em que escrevemos algum código que **trava todo o aplicativo**, fazendo com que o Uvicorn e o Python travem. 💥 + +E ainda assim, você provavelmente não gostaria que o aplicativo permanecesse inativo porque houve um erro em um lugar, você provavelmente quer que ele **continue em execução** pelo menos para as *operações de caminho* que não estão quebradas. + +### Reiniciar após falha + +Mas nos casos com erros realmente graves que travam o **processo** em execução, você vai querer um componente externo que seja responsável por **reiniciar** o processo, pelo menos algumas vezes... + +/// tip | Dica + +...Embora se o aplicativo inteiro estiver **travando imediatamente**, provavelmente não faça sentido reiniciá-lo para sempre. Mas nesses casos, você provavelmente notará isso durante o desenvolvimento, ou pelo menos logo após a implantação. + +Então, vamos nos concentrar nos casos principais, onde ele pode travar completamente em alguns casos específicos **no futuro**, e ainda faz sentido reiniciá-lo. + +/// + +Você provavelmente gostaria de ter a coisa responsável por reiniciar seu aplicativo como um **componente externo**, porque a essa altura, o mesmo aplicativo com Uvicorn e Python já havia travado, então não há nada no mesmo código do mesmo aplicativo que possa fazer algo a respeito. + +### Ferramentas de exemplo para reiniciar automaticamente + +Na maioria dos casos, a mesma ferramenta usada para **executar o programa na inicialização** também é usada para lidar com **reinicializações** automáticas. + +Por exemplo, isso poderia ser resolvido por: + +* Docker +* Kubernetes +* Docker Compose +* Docker no Modo Swarm +* Systemd +* Supervisor +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços +* Outros... + +## Replicação - Processos e Memória + +Com um aplicativo FastAPI, usando um programa de servidor como o comando `fastapi` que executa o Uvicorn, executá-lo uma vez em **um processo** pode atender a vários clientes simultaneamente. + +Mas em muitos casos, você desejará executar vários processos de trabalho ao mesmo tempo. + +### Processos Múltiplos - Trabalhadores + +Se você tiver mais clientes do que um único processo pode manipular (por exemplo, se a máquina virtual não for muito grande) e tiver **vários núcleos** na CPU do servidor, você poderá ter **vários processos** em execução com o mesmo aplicativo ao mesmo tempo e distribuir todas as solicitações entre eles. + +Quando você executa **vários processos** do mesmo programa de API, eles são comumente chamados de **trabalhadores**. + +### Processos do Trabalhador e Portas + +Lembra da documentação [Sobre HTTPS](https.md){.internal-link target=_blank} que diz que apenas um processo pode escutar em uma combinação de porta e endereço IP em um servidor? + +Isso ainda é verdade. + +Então, para poder ter **vários processos** ao mesmo tempo, tem que haver um **único processo escutando em uma porta** que então transmite a comunicação para cada processo de trabalho de alguma forma. + +### Memória por Processo + +Agora, quando o programa carrega coisas na memória, por exemplo, um modelo de aprendizado de máquina em uma variável, ou o conteúdo de um arquivo grande em uma variável, tudo isso **consome um pouco da memória (RAM)** do servidor. + +E vários processos normalmente **não compartilham nenhuma memória**. Isso significa que cada processo em execução tem suas próprias coisas, variáveis ​​e memória. E se você estiver consumindo uma grande quantidade de memória em seu código, **cada processo** consumirá uma quantidade equivalente de memória. + +### Memória do servidor + +Por exemplo, se seu código carrega um modelo de Machine Learning com **1 GB de tamanho**, quando você executa um processo com sua API, ele consumirá pelo menos 1 GB de RAM. E se você iniciar **4 processos** (4 trabalhadores), cada um consumirá 1 GB de RAM. Então, no total, sua API consumirá **4 GB de RAM**. + +E se o seu servidor remoto ou máquina virtual tiver apenas 3 GB de RAM, tentar carregar mais de 4 GB de RAM causará problemas. 🚨 + +### Processos Múltiplos - Um Exemplo + +Neste exemplo, há um **Processo Gerenciador** que inicia e controla dois **Processos de Trabalhadores**. + +Este Processo de Gerenciador provavelmente seria o que escutaria na **porta** no IP. E ele transmitiria toda a comunicação para os processos de trabalho. + +Esses processos de trabalho seriam aqueles que executariam seu aplicativo, eles executariam os cálculos principais para receber uma **solicitação** e retornar uma **resposta**, e carregariam qualquer coisa que você colocasse em variáveis ​​na RAM. + + + +E, claro, a mesma máquina provavelmente teria **outros processos** em execução, além do seu aplicativo. + +Um detalhe interessante é que a porcentagem da **CPU usada** por cada processo pode **variar** muito ao longo do tempo, mas a **memória (RAM)** normalmente fica mais ou menos **estável**. + +Se você tiver uma API que faz uma quantidade comparável de cálculos todas as vezes e tiver muitos clientes, então a **utilização da CPU** provavelmente *também será estável* (em vez de ficar constantemente subindo e descendo rapidamente). + +### Exemplos de ferramentas e estratégias de replicação + +Pode haver várias abordagens para conseguir isso, e falarei mais sobre estratégias específicas nos próximos capítulos, por exemplo, ao falar sobre Docker e contêineres. + +A principal restrição a ser considerada é que tem que haver um **único** componente manipulando a **porta** no **IP público**. E então tem que ter uma maneira de **transmitir** a comunicação para os **processos/trabalhadores** replicados. + +Aqui estão algumas combinações e estratégias possíveis: + +* **Uvicorn** com `--workers` + * Um **gerenciador de processos** Uvicorn escutaria no **IP** e na **porta** e iniciaria **vários processos de trabalho Uvicorn**. +* **Kubernetes** e outros **sistemas de contêineres** distribuídos + * Algo na camada **Kubernetes** escutaria no **IP** e na **porta**. A replicação seria por ter **vários contêineres**, cada um com **um processo Uvicorn** em execução. +* **Serviços de nuvem** que cuidam disso para você + * O serviço de nuvem provavelmente **cuidará da replicação para você**. Ele possivelmente deixaria você definir **um processo para executar**, ou uma **imagem de contêiner** para usar, em qualquer caso, provavelmente seria **um único processo Uvicorn**, e o serviço de nuvem seria responsável por replicá-lo. + +/// tip | Dica + +Não se preocupe se alguns desses itens sobre **contêineres**, Docker ou Kubernetes ainda não fizerem muito sentido. + +Falarei mais sobre imagens de contêiner, Docker, Kubernetes, etc. em um capítulo futuro: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +/// + +## Etapas anteriores antes de começar + +Há muitos casos em que você deseja executar algumas etapas **antes de iniciar** sua aplicação. + +Por exemplo, você pode querer executar **migrações de banco de dados**. + +Mas na maioria dos casos, você precisará executar essas etapas apenas **uma vez**. + +Portanto, você vai querer ter um **processo único** para executar essas **etapas anteriores** antes de iniciar o aplicativo. + +E você terá que se certificar de que é um único processo executando essas etapas anteriores *mesmo* se depois, você iniciar **vários processos** (vários trabalhadores) para o próprio aplicativo. Se essas etapas fossem executadas por **vários processos**, eles **duplicariam** o trabalho executando-o em **paralelo**, e se as etapas fossem algo delicado como uma migração de banco de dados, elas poderiam causar conflitos entre si. + +Claro, há alguns casos em que não há problema em executar as etapas anteriores várias vezes; nesse caso, é muito mais fácil de lidar. + +/// tip | Dica + +Além disso, tenha em mente que, dependendo da sua configuração, em alguns casos você **pode nem precisar de nenhuma etapa anterior** antes de iniciar sua aplicação. + +Nesse caso, você não precisaria se preocupar com nada disso. 🤷 + +/// + +### Exemplos de estratégias de etapas anteriores + +Isso **dependerá muito** da maneira como você **implanta seu sistema** e provavelmente estará conectado à maneira como você inicia programas, lida com reinicializações, etc. + +Aqui estão algumas ideias possíveis: + +* Um "Init Container" no Kubernetes que roda antes do seu app container +* Um script bash que roda os passos anteriores e então inicia seu aplicativo + * Você ainda precisaria de uma maneira de iniciar/reiniciar *aquele* script bash, detectar erros, etc. + +/// tip | Dica + +Darei exemplos mais concretos de como fazer isso com contêineres em um capítulo futuro: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +/// + +## Utilização de recursos + +Seu(s) servidor(es) é(são) um **recurso** que você pode consumir ou **utilizar**, com seus programas, o tempo de computação nas CPUs e a memória RAM disponível. + +Quanto dos recursos do sistema você quer consumir/utilizar? Pode ser fácil pensar "não muito", mas, na realidade, você provavelmente vai querer consumir **o máximo possível sem travar**. + +Se você está pagando por 3 servidores, mas está usando apenas um pouco de RAM e CPU, você provavelmente está **desperdiçando dinheiro** 💸, e provavelmente **desperdiçando energia elétrica do servidor** 🌎, etc. + +Nesse caso, seria melhor ter apenas 2 servidores e usar uma porcentagem maior de seus recursos (CPU, memória, disco, largura de banda de rede, etc). + +Por outro lado, se você tem 2 servidores e está usando **100% da CPU e RAM deles**, em algum momento um processo pedirá mais memória, e o servidor terá que usar o disco como "memória" (o que pode ser milhares de vezes mais lento), ou até mesmo **travar**. Ou um processo pode precisar fazer alguma computação e teria que esperar até que a CPU esteja livre novamente. + +Nesse caso, seria melhor obter **um servidor extra** e executar alguns processos nele para que todos tenham **RAM e tempo de CPU suficientes**. + +Também há a chance de que, por algum motivo, você tenha um **pico** de uso da sua API. Talvez ela tenha se tornado viral, ou talvez alguns outros serviços ou bots comecem a usá-la. E você pode querer ter recursos extras para estar seguro nesses casos. + +Você poderia colocar um **número arbitrário** para atingir, por exemplo, algo **entre 50% a 90%** da utilização de recursos. O ponto é que essas são provavelmente as principais coisas que você vai querer medir e usar para ajustar suas implantações. + +Você pode usar ferramentas simples como `htop` para ver a CPU e a RAM usadas no seu servidor ou a quantidade usada por cada processo. Ou você pode usar ferramentas de monitoramento mais complexas, que podem ser distribuídas entre servidores, etc. + +## Recapitular + +Você leu aqui alguns dos principais conceitos que provavelmente precisa ter em mente ao decidir como implantar seu aplicativo: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Etapas anteriores antes de iniciar + +Entender essas ideias e como aplicá-las deve lhe dar a intuição necessária para tomar qualquer decisão ao configurar e ajustar suas implantações. 🤓 + +Nas próximas seções, darei exemplos mais concretos de possíveis estratégias que você pode seguir. 🚀 diff --git a/docs/pt/docs/deployment/docker.md b/docs/pt/docs/deployment/docker.md index 42c31db29..cf18bb153 100644 --- a/docs/pt/docs/deployment/docker.md +++ b/docs/pt/docs/deployment/docker.md @@ -4,9 +4,11 @@ Ao fazer o deploy de aplicações FastAPI uma abordagem comum é construir uma * Usando contêineres Linux você tem diversas vantagens incluindo **segurança**, **replicabilidade**, **simplicidade**, entre outras. -!!! Dica - Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#build-a-docker-image-for-fastapi). +/// tip | Dica +Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#construindo-uma-imagem-docker-para-fastapi). + +///
Visualização do Dockerfile 👀 @@ -109,7 +111,7 @@ Isso pode depender principalmente da ferramenta que você usa para **instalar** O caminho mais comum de fazer isso é ter um arquivo `requirements.txt` com os nomes dos pacotes e suas versões, um por linha. -Você, naturalmente, usaria as mesmas ideias que você leu em [Sobre Versões do FastAPI](./versions.md){.internal-link target=_blank} para definir os intervalos de versões. +Você, naturalmente, usaria as mesmas ideias que você leu em [Sobre Versões do FastAPI](versions.md){.internal-link target=_blank} para definir os intervalos de versões. Por exemplo, seu `requirements.txt` poderia parecer com: @@ -131,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info - Há outros formatos e ferramentas para definir e instalar dependências de pacote. +/// info + +Há outros formatos e ferramentas para definir e instalar dependências de pacote. + +Eu vou mostrar um exemplo depois usando Poetry em uma seção abaixo. 👇 - Eu vou mostrar um exemplo depois usando Poetry em uma seção abaixo. 👇 +/// ### Criando o Código do **FastAPI** @@ -200,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] A opção `--no-cache-dir` diz ao `pip` para não salvar os pacotes baixados localmente, pois isso só aconteceria se `pip` fosse executado novamente para instalar os mesmos pacotes, mas esse não é o caso quando trabalhamos com contêineres. - !!! note - `--no-cache-dir` é apenas relacionado ao `pip`, não tem nada a ver com Docker ou contêineres. + /// note + + `--no-cache-dir` é apenas relacionado ao `pip`, não tem nada a ver com Docker ou contêineres. + + /// A opção `--upgrade` diz ao `pip` para atualizar os pacotes se eles já estiverem instalados. @@ -223,8 +231,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Porque o programa será iniciado em `/code` e dentro dele está o diretório `./app` com seu código, o **Uvicorn** será capaz de ver e **importar** `app` de `app.main`. -!!! tip - Revise o que cada linha faz clicando em cada bolha com o número no código. 👆 +/// tip + +Revise o que cada linha faz clicando em cada bolha com o número no código. 👆 + +/// Agora você deve ter uma estrutura de diretório como: @@ -294,10 +305,13 @@ $ docker build -t myimage . -!!! tip - Note o `.` no final, é equivalente a `./`, ele diz ao Docker o diretório a ser usado para construir a imagem do contêiner. +/// tip + +Note o `.` no final, é equivalente a `./`, ele diz ao Docker o diretório a ser usado para construir a imagem do contêiner. + +Nesse caso, é o mesmo diretório atual (`.`). - Nesse caso, é o mesmo diretório atual (`.`). +/// ### Inicie o contêiner Docker @@ -374,7 +388,7 @@ Então ajuste o comando Uvicorn para usar o novo módulo `main` em vez de `app.m ## Conceitos de Implantação -Vamos falar novamente sobre alguns dos mesmos [Conceitos de Implantação](./concepts.md){.internal-link target=_blank} em termos de contêineres. +Vamos falar novamente sobre alguns dos mesmos [Conceitos de Implantação](concepts.md){.internal-link target=_blank} em termos de contêineres. Contêineres são principalmente uma ferramenta para simplificar o processo de **construção e implantação** de um aplicativo, mas eles não impõem uma abordagem particular para lidar com esses **conceitos de implantação** e existem várias estratégias possíveis. @@ -395,8 +409,11 @@ Se nos concentrarmos apenas na **imagem do contêiner** para um aplicativo FastA Isso poderia ser outro contêiner, por exemplo, com Traefik, lidando com **HTTPS** e aquisição **automática** de **certificados**. -!!! tip - Traefik tem integrações com Docker, Kubernetes e outros, portanto, é muito fácil configurar e configurar o HTTPS para seus contêineres com ele. +/// tip + +Traefik tem integrações com Docker, Kubernetes e outros, portanto, é muito fácil configurar e configurar o HTTPS para seus contêineres com ele. + +/// Alternativamente, o HTTPS poderia ser tratado por um provedor de nuvem como um de seus serviços (enquanto ainda executasse o aplicativo em um contêiner). @@ -424,8 +441,11 @@ Quando usando contêineres, normalmente você terá algum componente **escutando Como esse componente assumiria a **carga** de solicitações e distribuiria isso entre os trabalhadores de uma maneira (esperançosamente) **balanceada**, ele também é comumente chamado de **Balanceador de Carga**. -!!! tip - O mesmo componente **Proxy de Terminação TLS** usado para HTTPS provavelmente também seria um **Balanceador de Carga**. +/// tip + +O mesmo componente **Proxy de Terminação TLS** usado para HTTPS provavelmente também seria um **Balanceador de Carga**. + +/// E quando trabalhar com contêineres, o mesmo sistema que você usa para iniciar e gerenciá-los já terá ferramentas internas para transmitir a **comunicação de rede** (por exemplo, solicitações HTTP) do **balanceador de carga** (que também pode ser um **Proxy de Terminação TLS**) para o(s) contêiner(es) com seu aplicativo. @@ -504,8 +524,11 @@ Se você estiver usando contêineres (por exemplo, Docker, Kubernetes), existem Se você tiver **múltiplos contêineres**, provavelmente cada um executando um **único processo** (por exemplo, em um cluster do **Kubernetes**), então provavelmente você gostaria de ter um **contêiner separado** fazendo o trabalho dos **passos anteriores** em um único contêiner, executando um único processo, **antes** de executar os contêineres trabalhadores replicados. -!!! info - Se você estiver usando o Kubernetes, provavelmente será um Init Container. +/// info + +Se você estiver usando o Kubernetes, provavelmente será um Init Container. + +/// Se no seu caso de uso não houver problema em executar esses passos anteriores **em paralelo várias vezes** (por exemplo, se você não estiver executando migrações de banco de dados, mas apenas verificando se o banco de dados está pronto), então você também pode colocá-los em cada contêiner logo antes de iniciar o processo principal. @@ -515,14 +538,17 @@ Se você tiver uma configuração simples, com um **único contêiner** que ent ## Imagem Oficial do Docker com Gunicorn - Uvicorn -Há uma imagem oficial do Docker que inclui o Gunicorn executando com trabalhadores Uvicorn, conforme detalhado em um capítulo anterior: [Server Workers - Gunicorn com Uvicorn](./server-workers.md){.internal-link target=_blank}. +Há uma imagem oficial do Docker que inclui o Gunicorn executando com trabalhadores Uvicorn, conforme detalhado em um capítulo anterior: [Server Workers - Gunicorn com Uvicorn](server-workers.md){.internal-link target=_blank}. -Essa imagem seria útil principalmente nas situações descritas acima em: [Contêineres com Múltiplos Processos e Casos Especiais](#contêineres-com-múltiplos-processos-e-casos-Especiais). +Essa imagem seria útil principalmente nas situações descritas acima em: [Contêineres com Múltiplos Processos e Casos Especiais](#conteineres-com-multiplos-processos-e-casos-especiais). * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning - Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construa-uma-imagem-docker-para-o-fastapi). +/// warning + +Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construindo-uma-imagem-docker-para-fastapi). + +/// Essa imagem tem um mecanismo de **auto-ajuste** incluído para definir o **número de processos trabalhadores** com base nos núcleos de CPU disponíveis. @@ -530,8 +556,11 @@ Isso tem **padrões sensíveis**, mas você ainda pode alterar e atualizar todas Há também suporte para executar **passos anteriores antes de iniciar** com um script. -!!! tip - Para ver todas as configurações e opções, vá para a página da imagem Docker: tiangolo/uvicorn-gunicorn-fastapi. +/// tip + +Para ver todas as configurações e opções, vá para a página da imagem Docker: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### Número de Processos na Imagem Oficial do Docker @@ -579,7 +608,7 @@ COPY ./app /app/app Você provavelmente **não** deve usar essa imagem base oficial (ou qualquer outra semelhante) se estiver usando **Kubernetes** (ou outros) e já estiver definindo **replicação** no nível do cluster, com vários **contêineres**. Nesses casos, é melhor **construir uma imagem do zero** conforme descrito acima: [Construindo uma Imagem Docker para FastAPI](#construindo-uma-imagem-docker-para-fastapi). -Essa imagem seria útil principalmente nos casos especiais descritos acima em [Contêineres com Múltiplos Processos e Casos Especiais](#contêineres-com-múltiplos-processos-e-casos-Especiais). Por exemplo, se sua aplicação for **simples o suficiente** para que a configuração padrão de número de processos com base na CPU funcione bem, você não quer se preocupar com a configuração manual da replicação no nível do cluster e não está executando mais de um contêiner com seu aplicativo. Ou se você estiver implantando com **Docker Compose**, executando em um único servidor, etc. +Essa imagem seria útil principalmente nos casos especiais descritos acima em [Contêineres com Múltiplos Processos e Casos Especiais](#conteineres-com-multiplos-processos-e-casos-especiais). Por exemplo, se sua aplicação for **simples o suficiente** para que a configuração padrão de número de processos com base na CPU funcione bem, você não quer se preocupar com a configuração manual da replicação no nível do cluster e não está executando mais de um contêiner com seu aplicativo. Ou se você estiver implantando com **Docker Compose**, executando em um único servidor, etc. ## Deploy da Imagem do Contêiner @@ -660,8 +689,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Execute o comando `uvicorn`, informando-o para usar o objeto `app` importado de `app.main`. -!!! tip - Clique nos números das bolhas para ver o que cada linha faz. +/// tip + +Clique nos números das bolhas para ver o que cada linha faz. + +/// Um **estágio do Docker** é uma parte de um `Dockerfile` que funciona como uma **imagem temporária do contêiner** que só é usada para gerar alguns arquivos para serem usados posteriormente. diff --git a/docs/pt/docs/deployment/https.md b/docs/pt/docs/deployment/https.md index f85861e92..9a13977ec 100644 --- a/docs/pt/docs/deployment/https.md +++ b/docs/pt/docs/deployment/https.md @@ -4,8 +4,11 @@ Mas é bem mais complexo do que isso. -!!! tip "Dica" - Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas. +/// tip | Dica + +Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas. + +/// Para aprender o básico de HTTPS de uma perspectiva do usuário, verifique https://howhttps.works/pt-br/. diff --git a/docs/pt/docs/deployment/manually.md b/docs/pt/docs/deployment/manually.md new file mode 100644 index 000000000..237f4f8b9 --- /dev/null +++ b/docs/pt/docs/deployment/manually.md @@ -0,0 +1,169 @@ +# Execute um Servidor Manualmente + +## Utilize o comando `fastapi run` + +Em resumo, utilize o comando `fastapi run` para inicializar sua aplicação FastAPI: + +
+ +```console +$ fastapi run main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭─────────── FastAPI CLI - Production mode ───────────╮ + │ │ + │ Serving at: http://0.0.0.0:8000 │ + │ │ + │ API docs: http://0.0.0.0:8000/docs │ + │ │ + │ Running in production mode, for development use: │ + │ │ + fastapi dev + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Started server process [2306215] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +``` + +
+ +Isto deve funcionar para a maioria dos casos. 😎 + +Você pode utilizar esse comando, por exemplo, para iniciar sua aplicação **FastAPI** em um contêiner, em um servidor, etc. + +## Servidores ASGI + +Vamos nos aprofundar um pouco mais em detalhes. + +FastAPI utiliza um padrão para construir frameworks e servidores web em Python chamado ASGI. FastAPI é um framework web ASGI. + +A principal coisa que você precisa para executar uma aplicação **FastAPI** (ou qualquer outra aplicação ASGI) em uma máquina de servidor remoto é um programa de servidor ASGI como o **Uvicorn**, que é o que vem por padrão no comando `fastapi`. + +Existem diversas alternativas, incluindo: + +* Uvicorn: um servidor ASGI de alta performance. +* Hypercorn: um servidor ASGI compátivel com HTTP/2, Trio e outros recursos. +* Daphne: servidor ASGI construído para Django Channels. +* Granian: um servidor HTTP Rust para aplicações Python. +* NGINX Unit: NGINX Unit é um runtime de aplicação web leve e versátil. + +## Máquina Servidora e Programa Servidor + +Existe um pequeno detalhe sobre estes nomes para se manter em mente. 💡 + +A palavra "**servidor**" é comumente usada para se referir tanto ao computador remoto/nuvem (a máquina física ou virtual) quanto ao programa que está sendo executado nessa máquina (por exemplo, Uvicorn). + +Apenas tenha em mente que quando você ler "servidor" em geral, isso pode se referir a uma dessas duas coisas. + +Quando se refere à máquina remota, é comum chamá-la de **servidor**, mas também de **máquina**, **VM** (máquina virtual), **nó**. Todos esses termos se referem a algum tipo de máquina remota, normalmente executando Linux, onde você executa programas. + +## Instale o Programa Servidor + +Quando você instala o FastAPI, ele vem com um servidor de produção, o Uvicorn, e você pode iniciá-lo com o comando `fastapi run`. + +Mas você também pode instalar um servidor ASGI manualmente. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e, em seguida, você pode instalar a aplicação do servidor. + +Por exemplo, para instalar o Uvicorn: + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +Um processo semelhante se aplicaria a qualquer outro programa de servidor ASGI. + +/// tip | Dica + +Adicionando o `standard`, o Uvicorn instalará e usará algumas dependências extras recomendadas. + +Isso inclui o `uvloop`, a substituição de alto desempenho para `asyncio`, que fornece um grande aumento de desempenho de concorrência. + +Quando você instala o FastAPI com algo como `pip install "fastapi[standard]"`, você já obtém `uvicorn[standard]` também. + +/// + +## Execute o Programa Servidor + +Se você instalou um servidor ASGI manualmente, normalmente precisará passar uma string de importação em um formato especial para que ele importe sua aplicação FastAPI: + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` + +
+ +/// note | Nota + +O comando `uvicorn main:app` refere-se a: + +* `main`: o arquivo `main.py` (o "módulo" Python). +* `app`: o objeto criado dentro de `main.py` com a linha `app = FastAPI()`. + +É equivalente a: + +```Python +from main import app +``` + +/// + +Cada programa de servidor ASGI alternativo teria um comando semelhante, você pode ler mais na documentação respectiva. + +/// warning | Aviso + +Uvicorn e outros servidores suportam a opção `--reload` que é útil durante o desenvolvimento. + +A opção `--reload` consome muito mais recursos, é mais instável, etc. + +Ela ajuda muito durante o **desenvolvimento**, mas você **não deve** usá-la em **produção**. + +/// + +## Conceitos de Implantação + +Esses exemplos executam o programa do servidor (por exemplo, Uvicorn), iniciando **um único processo**, ouvindo em todos os IPs (`0.0.0.0`) em uma porta predefinida (por exemplo, `80`). + +Esta é a ideia básica. Mas você provavelmente vai querer cuidar de algumas coisas adicionais, como: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Passos anteriores antes de começar + +Vou te contar mais sobre cada um desses conceitos, como pensar sobre eles e alguns exemplos concretos com estratégias para lidar com eles nos próximos capítulos. 🚀 diff --git a/docs/pt/docs/deployment/server-workers.md b/docs/pt/docs/deployment/server-workers.md new file mode 100644 index 000000000..63eda56b4 --- /dev/null +++ b/docs/pt/docs/deployment/server-workers.md @@ -0,0 +1,152 @@ +# Trabalhadores do Servidor - Uvicorn com Trabalhadores + +Vamos rever os conceitos de implantação anteriores: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* **Replicação (o número de processos em execução)** +* Memória +* Etapas anteriores antes de iniciar + +Até este ponto, com todos os tutoriais nos documentos, você provavelmente estava executando um **programa de servidor**, por exemplo, usando o comando `fastapi`, que executa o Uvicorn, executando um **único processo**. + +Ao implantar aplicativos, você provavelmente desejará ter alguma **replicação de processos** para aproveitar **vários núcleos** e poder lidar com mais solicitações. + +Como você viu no capítulo anterior sobre [Conceitos de implantação](concepts.md){.internal-link target=_blank}, há várias estratégias que você pode usar. + +Aqui mostrarei como usar o **Uvicorn** com **processos de trabalho** usando o comando `fastapi` ou o comando `uvicorn` diretamente. + +/// info | Informação + +Se você estiver usando contêineres, por exemplo com Docker ou Kubernetes, falarei mais sobre isso no próximo capítulo: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +Em particular, ao executar no **Kubernetes** você provavelmente **não** vai querer usar vários trabalhadores e, em vez disso, executar **um único processo Uvicorn por contêiner**, mas falarei sobre isso mais adiante neste capítulo. + +/// + +## Vários trabalhadores + +Você pode iniciar vários trabalhadores com a opção de linha de comando `--workers`: + +//// tab | `fastapi` + +Se você usar o comando `fastapi`: + +
+ +```console +$
 fastapi run --workers 4 main.py
+INFO     Using path main.py
+INFO     Resolved absolute path /home/user/code/awesomeapp/main.py
+INFO     Searching for package file structure from directories with __init__.py files
+INFO     Importing from /home/user/code/awesomeapp
+
+ ╭─ Python module file ─╮
+ │                      │
+ │  🐍 main.py          │
+ │                      │
+ ╰──────────────────────╯
+
+INFO     Importing module main
+INFO     Found importable FastAPI app
+
+ ╭─ Importable FastAPI app ─╮
+ │                          │
+ │  from main import app    │
+ │                          │
+ ╰──────────────────────────╯
+
+INFO     Using import string main:app
+
+ ╭─────────── FastAPI CLI - Production mode ───────────╮
+ │                                                     │
+ │  Serving at: http://0.0.0.0:8000                    │
+ │                                                     │
+ │  API docs: http://0.0.0.0:8000/docs                 │
+ │                                                     │
+ │  Running in production mode, for development use:   │
+ │                                                     │
+ fastapi dev
+ │                                                     │
+ ╰─────────────────────────────────────────────────────╯
+
+INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
+INFO:     Started parent process [27365]
+INFO:     Started server process [27368]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27369]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27370]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27367]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+
+``` + +
+ +//// + +//// tab | `uvicorn` + +Se você preferir usar o comando `uvicorn` diretamente: + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 +INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +//// + +A única opção nova aqui é `--workers` informando ao Uvicorn para iniciar 4 processos de trabalho. + +Você também pode ver que ele mostra o **PID** de cada processo, `27365` para o processo pai (este é o **gerenciador de processos**) e um para cada processo de trabalho: `27368`, `27369`, `27370` e `27367`. + +## Conceitos de Implantação + +Aqui você viu como usar vários **trabalhadores** para **paralelizar** a execução do aplicativo, aproveitar **vários núcleos** na CPU e conseguir atender **mais solicitações**. + +Da lista de conceitos de implantação acima, o uso de trabalhadores ajudaria principalmente com a parte da **replicação** e um pouco com as **reinicializações**, mas você ainda precisa cuidar dos outros: + +* **Segurança - HTTPS** +* **Executando na inicialização** +* ***Reinicializações*** +* Replicação (o número de processos em execução) +* **Memória** +* **Etapas anteriores antes de iniciar** + +## Contêineres e Docker + +No próximo capítulo sobre [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}, explicarei algumas estratégias que você pode usar para lidar com os outros **conceitos de implantação**. + +Vou mostrar como **construir sua própria imagem do zero** para executar um único processo Uvicorn. É um processo simples e provavelmente é o que você gostaria de fazer ao usar um sistema de gerenciamento de contêineres distribuídos como o **Kubernetes**. + +## Recapitular + +Você pode usar vários processos de trabalho com a opção CLI `--workers` com os comandos `fastapi` ou `uvicorn` para aproveitar as vantagens de **CPUs multi-core** e executar **vários processos em paralelo**. + +Você pode usar essas ferramentas e ideias se estiver configurando **seu próprio sistema de implantação** enquanto cuida dos outros conceitos de implantação. + +Confira o próximo capítulo para aprender sobre **FastAPI** com contêineres (por exemplo, Docker e Kubernetes). Você verá que essas ferramentas têm maneiras simples de resolver os outros **conceitos de implantação** também. ✨ diff --git a/docs/pt/docs/deployment/versions.md b/docs/pt/docs/deployment/versions.md index 77d9bab69..323ddbd45 100644 --- a/docs/pt/docs/deployment/versions.md +++ b/docs/pt/docs/deployment/versions.md @@ -42,8 +42,11 @@ Seguindo as convenções de controle de versão semântica, qualquer versão aba FastAPI também segue a convenção de que qualquer alteração de versão "PATCH" é para correção de bugs e alterações não significativas. -!!! tip "Dica" - O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`. +/// tip | Dica + +O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`. + +/// Logo, você deveria conseguir fixar a versão, como: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Mudanças significativas e novos recursos são adicionados em versões "MINOR". -!!! tip "Dica" - O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`. +/// tip | Dica + +O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`. + +/// ## Atualizando as versões do FastAPI diff --git a/docs/pt/docs/environment-variables.md b/docs/pt/docs/environment-variables.md new file mode 100644 index 000000000..432f78af0 --- /dev/null +++ b/docs/pt/docs/environment-variables.md @@ -0,0 +1,298 @@ +# Variáveis de Ambiente + +/// tip | Dica + +Se você já sabe o que são "variáveis de ambiente" e como usá-las, pode pular esta seção. + +/// + +Uma variável de ambiente (também conhecida como "**env var**") é uma variável que existe **fora** do código Python, no **sistema operacional**, e pode ser lida pelo seu código Python (ou por outros programas também). + +Variáveis de ambiente podem ser úteis para lidar com **configurações** do aplicativo, como parte da **instalação** do Python, etc. + +## Criar e Usar Variáveis de Ambiente + +Você pode **criar** e usar variáveis de ambiente no **shell (terminal)**, sem precisar do Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Você pode criar uma variável de ambiente MY_NAME com +$ export MY_NAME="Wade Wilson" + +// Então você pode usá-la com outros programas, como +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Criar uma variável de ambiente MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Usá-la com outros programas, como +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Ler Variáveis de Ambiente no Python + +Você também pode criar variáveis de ambiente **fora** do Python, no terminal (ou com qualquer outro método) e depois **lê-las no Python**. + +Por exemplo, você poderia ter um arquivo `main.py` com: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip | Dica + +O segundo argumento para `os.getenv()` é o valor padrão a ser retornado. + +Se não for fornecido, é `None` por padrão, Aqui fornecemos `"World"` como o valor padrão a ser usado. + +/// + +Então você poderia chamar esse programa Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Aqui ainda não definimos a variável de ambiente +$ python main.py + +// Como não definimos a variável de ambiente, obtemos o valor padrão + +Hello World from Python + +// Mas se criarmos uma variável de ambiente primeiro +$ export MY_NAME="Wade Wilson" + +// E então chamar o programa novamente +$ python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Aqui ainda não definimos a variável de ambiente +$ python main.py + +// Como não definimos a variável de ambiente, obtemos o valor padrão + +Hello World from Python + +// Mas se criarmos uma variável de ambiente primeiro +$ $Env:MY_NAME = "Wade Wilson" + +// E então chamar o programa novamente +$ python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python +``` + +
+ +//// + +Como as variáveis de ambiente podem ser definidas fora do código, mas podem ser lidas pelo código e não precisam ser armazenadas (com versão no `git`) com o restante dos arquivos, é comum usá-las para configurações ou **definições**. + +Você também pode criar uma variável de ambiente apenas para uma **invocação específica do programa**, que só está disponível para aquele programa e apenas pela duração dele. + +Para fazer isso, crie-a na mesma linha, antes do próprio programa: + +
+ +```console +// Criar uma variável de ambiente MY_NAME para esta chamada de programa +$ MY_NAME="Wade Wilson" python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python + +// A variável de ambiente não existe mais depois +$ python main.py + +Hello World from Python +``` + +
+ +/// tip | Dica + +Você pode ler mais sobre isso em The Twelve-Factor App: Config. + +/// + +## Tipos e Validação + +Essas variáveis de ambiente só podem lidar com **strings de texto**, pois são externas ao Python e precisam ser compatíveis com outros programas e com o resto do sistema (e até mesmo com diferentes sistemas operacionais, como Linux, Windows, macOS). + +Isso significa que **qualquer valor** lido em Python de uma variável de ambiente **será uma `str`**, e qualquer conversão para um tipo diferente ou qualquer validação precisa ser feita no código. + +Você aprenderá mais sobre como usar variáveis de ambiente para lidar com **configurações do aplicativo** no [Guia do Usuário Avançado - Configurações e Variáveis de Ambiente](./advanced/settings.md){.internal-link target=_blank}. + +## Variável de Ambiente `PATH` + +Existe uma variável de ambiente **especial** chamada **`PATH`** que é usada pelos sistemas operacionais (Linux, macOS, Windows) para encontrar programas para executar. + +O valor da variável `PATH` é uma longa string composta por diretórios separados por dois pontos `:` no Linux e macOS, e por ponto e vírgula `;` no Windows. + +Por exemplo, a variável de ambiente `PATH` poderia ter esta aparência: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Isso significa que o sistema deve procurar programas nos diretórios: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Isso significa que o sistema deve procurar programas nos diretórios: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Quando você digita um **comando** no terminal, o sistema operacional **procura** o programa em **cada um dos diretórios** listados na variável de ambiente `PATH`. + +Por exemplo, quando você digita `python` no terminal, o sistema operacional procura um programa chamado `python` no **primeiro diretório** dessa lista. + +Se ele o encontrar, então ele o **usará**. Caso contrário, ele continua procurando nos **outros diretórios**. + +### Instalando o Python e Atualizando o `PATH` + +Durante a instalação do Python, você pode ser questionado sobre a atualização da variável de ambiente `PATH`. + +//// tab | Linux, macOS + +Vamos supor que você instale o Python e ele fique em um diretório `/opt/custompython/bin`. + +Se você concordar em atualizar a variável de ambiente `PATH`, o instalador adicionará `/opt/custompython/bin` para a variável de ambiente `PATH`. + +Poderia parecer assim: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Dessa forma, ao digitar `python` no terminal, o sistema encontrará o programa Python em `/opt/custompython/bin` (último diretório) e o utilizará. + +//// + +//// tab | Windows + +Digamos que você instala o Python e ele acaba em um diretório `C:\opt\custompython\bin`. + +Se você disser sim para atualizar a variável de ambiente `PATH`, o instalador adicionará `C:\opt\custompython\bin` à variável de ambiente `PATH`. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Dessa forma, quando você digitar `python` no terminal, o sistema encontrará o programa Python em `C:\opt\custompython\bin` (o último diretório) e o utilizará. + +//// + +Então, se você digitar: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +O sistema **encontrará** o programa `python` em `/opt/custompython/bin` e o executará. + +Seria aproximadamente equivalente a digitar: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +O sistema **encontrará** o programa `python` em `C:\opt\custompython\bin\python` e o executará. + +Seria aproximadamente equivalente a digitar: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +Essas informações serão úteis ao aprender sobre [Ambientes Virtuais](virtual-environments.md){.internal-link target=_blank}. + +## Conclusão + +Com isso, você deve ter uma compreensão básica do que são **variáveis ​​de ambiente** e como usá-las em Python. + +Você também pode ler mais sobre elas na Wikipedia para Variáveis ​​de Ambiente. + +Em muitos casos, não é muito óbvio como as variáveis ​​de ambiente seriam úteis e aplicáveis ​​imediatamente. Mas elas continuam aparecendo em muitos cenários diferentes quando você está desenvolvendo, então é bom saber sobre elas. + +Por exemplo, você precisará dessas informações na próxima seção, sobre [Ambientes Virtuais](virtual-environments.md). diff --git a/docs/pt/docs/external-links.md b/docs/pt/docs/external-links.md deleted file mode 100644 index 77ec32351..000000000 --- a/docs/pt/docs/external-links.md +++ /dev/null @@ -1,33 +0,0 @@ -# Links externos e Artigos - -**FastAPI** tem uma grande comunidade em crescimento constante. - -Existem muitas postagens, artigos, ferramentas e projetos relacionados ao **FastAPI**. - -Aqui tem uma lista, incompleta, de algumas delas. - -!!! tip "Dica" - Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um _Pull Request_ adicionando ele. - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projetos - -Últimos projetos no GitHub com o tópico `fastapi`: - -
-
diff --git a/docs/pt/docs/fastapi-cli.md b/docs/pt/docs/fastapi-cli.md new file mode 100644 index 000000000..829686631 --- /dev/null +++ b/docs/pt/docs/fastapi-cli.md @@ -0,0 +1,87 @@ +# FastAPI CLI + +**FastAPI CLI** é uma interface por linha de comando do `fastapi` que você pode usar para rodar sua app FastAPI, gerenciar seu projeto FastAPI e mais. + +Quando você instala o FastAPI (ex.: com `pip install fastapi`), isso inclui um pacote chamado `fastapi-cli`. Esse pacote disponibiliza o comando `fastapi` no terminal. + +Para rodar seu app FastAPI em desenvolvimento, você pode usar o comando `fastapi dev`: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +Aquele commando por linha de programa chamado `fastapi` é o **FastAPI CLI**. + +O FastAPI CLI recebe o caminho do seu programa Python, detecta automaticamente a variável com o FastAPI (comumente nomeada `app`) e como importá-la, e então a serve. + +Para produção você usaria `fastapi run` no lugar. 🚀 + +Internamente, **FastAPI CLI** usa Uvicorn, um servidor ASGI de alta performance e pronto para produção. 😎 + +## `fastapi dev` + +Quando você roda `fastapi dev`, isso vai executar em modo de desenvolvimento. + +Por padrão, teremos o **recarregamento automático** ativo, então o programa irá recarregar o servidor automaticamente toda vez que você fizer mudanças no seu código. Isso usa muitos recursos e pode ser menos estável. Você deve apenas usá-lo em modo de desenvolvimento. + +O servidor de desenvolvimento escutará no endereço de IP `127.0.0.1` por padrão, este é o IP que sua máquina usa para se comunicar com ela mesma (`localhost`). + +## `fastapi run` + +Quando você rodar `fastapi run`, isso executará em modo de produção por padrão. + +Este modo terá **recarregamento automático desativado** por padrão. + +Isso irá escutar no endereço de IP `0.0.0.0`, o que significa todos os endereços IP disponíveis, dessa forma o programa estará acessível publicamente para qualquer um que consiga se comunicar com a máquina. Isso é como você normalmente roda em produção em um contêiner, por exemplo. + +Em muitos casos você pode ter (e deveria ter) um "proxy de saída" tratando HTTPS no topo, isso dependerá de como você fará o deploy da sua aplicação, seu provedor pode fazer isso pra você ou talvez seja necessário fazer você mesmo. + +/// tip + +Você pode aprender mais sobre em [documentação de deployment](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/pt/docs/fastapi-people.md b/docs/pt/docs/fastapi-people.md deleted file mode 100644 index 20061bfd9..000000000 --- a/docs/pt/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# Pessoas do FastAPI - -FastAPI possue uma comunidade incrível que recebe pessoas de todos os níveis. - -## Criador - Mantenedor - -Ei! 👋 - -Este sou eu: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Respostas: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Eu sou o criador e mantenedor do **FastAPI**. Você pode ler mais sobre isso em [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Mas aqui eu quero mostrar a você a comunidade. - ---- - -**FastAPI** recebe muito suporte da comunidade. E quero destacar suas contribuições. - -Estas são as pessoas que: - -* [Help others with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Create Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Revisar Pull Requests, [especially important for translations](contributing.md#translations){.internal-link target=_blank}. - -Uma salva de palmas para eles. 👏 🙇 - -## Usuários mais ativos do ultimo mês - -Estes são os usuários que estão [helping others the most with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} durante o ultimo mês. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Issues respondidas: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Especialistas - -Aqui está os **Especialistas do FastAPI**. 🤓 - - -Estes são os usuários que [helped others the most with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} em *todo o tempo*. - -Eles provaram ser especialistas ajudando muitos outros. ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Issues respondidas: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Top Contribuidores - -Aqui está os **Top Contribuidores**. 👷 - -Esses usuários têm [created the most Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} que tem sido *mergeado*. - -Eles contribuíram com o código-fonte, documentação, traduções, etc. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Existem muitos outros contribuidores (mais de uma centena), você pode ver todos eles em Página de Contribuidores do FastAPI no GitHub. 👷 - -## Top Revisores - -Esses usuários são os **Top Revisores**. 🕵️ - -### Revisões para Traduções - -Eu só falo algumas línguas (e não muito bem 😅). Então, os revisores são aqueles que têm o [**poder de aprovar traduções**](contributing.md#translations){.internal-link target=_blank} da documentação. Sem eles, não haveria documentação em vários outros idiomas. - ---- - -Os **Top Revisores** 🕵️ revisaram a maior parte de Pull Requests de outros, garantindo a qualidade do código, documentação, e especialmente, as **traduções**. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Revisões: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Patrocinadores - -Esses são os **Patrocinadores**. 😎 - -Eles estão apoiando meu trabalho **FastAPI** (e outros), principalmente através de GitHub Sponsors. - -{% if sponsors %} -{% if sponsors.gold %} - -### Patrocinadores Ouro - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Patrocinadores Prata - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Patrocinadores Bronze - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -### Patrocinadores Individuais - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -{% endif %} - -## Sobre os dados - detalhes técnicos - -A principal intenção desta página é destacar o esforço da comunidade para ajudar os outros. - -Especialmente incluindo esforços que normalmente são menos visíveis, e em muitos casos mais árduo, como ajudar os outros com issues e revisando Pull Requests com traduções. - -Os dados são calculados todo mês, você pode ler o código fonte aqui. - -Aqui também estou destacando contribuições de patrocinadores. - -Eu também me reservo o direito de atualizar o algoritmo, seções, limites, etc (só para prevenir 🤷). diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md index 64efeeae1..a90a8094b 100644 --- a/docs/pt/docs/features.md +++ b/docs/pt/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` quer dizer: +/// info - Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` quer dizer: + +Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Suporte de editores diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md index 06a4db1e0..3d6e1f9d2 100644 --- a/docs/pt/docs/help-fastapi.md +++ b/docs/pt/docs/help-fastapi.md @@ -26,13 +26,13 @@ Você pode se inscrever (pouco frequente) [**FastAPI e amigos** newsletter](news ## Favorite o **FastAPI** no GitHub -Você pode "favoritar" o FastAPI no GitHub (clicando na estrela no canto superior direito): https://github.com/tiangolo/fastapi. ⭐️ +Você pode "favoritar" o FastAPI no GitHub (clicando na estrela no canto superior direito): https://github.com/fastapi/fastapi. ⭐️ Favoritando, outros usuários poderão encontrar mais facilmente e verão que já foi útil para muita gente. ## Acompanhe novos updates no repositorio do GitHub -Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no botão com um "olho" no canto superior direito): https://github.com/tiangolo/fastapi. 👀 +Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no botão com um "olho" no canto superior direito): https://github.com/fastapi/fastapi. 👀 Podendo selecionar apenas "Novos Updates". @@ -59,7 +59,7 @@ Você pode: ## Tweete sobre **FastAPI** -Tweete sobre o **FastAPI** e compartilhe comigo e com os outros o porque de gostar do FastAPI. 🎉 +Tweete sobre o **FastAPI** e compartilhe comigo e com os outros o porque de gostar do FastAPI. 🎉 Adoro ouvir sobre como o **FastAPI** é usado, o que você gosta nele, em qual projeto/empresa está sendo usado, etc. @@ -70,13 +70,13 @@ Adoro ouvir sobre como o **FastAPI** é usado, o que você gosta nele, em qual p ## Responda perguntas no GitHub -Você pode acompanhar as perguntas existentes e tentar ajudar outros, . 🤓 +Você pode acompanhar as perguntas existentes e tentar ajudar outros, . 🤓 -Ajudando a responder as questões de varias pessoas, você pode se tornar um [Expert em FastAPI](fastapi-people.md#experts){.internal-link target=_blank} oficial. 🎉 +Ajudando a responder as questões de varias pessoas, você pode se tornar um [Expert em FastAPI](fastapi-people.md#especialistas){.internal-link target=_blank} oficial. 🎉 ## Acompanhe o repositório do GitHub -Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no "olho" no canto superior direito): https://github.com/tiangolo/fastapi. 👀 +Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no "olho" no canto superior direito): https://github.com/fastapi/fastapi. 👀 Se você selecionar "Acompanhando" (Watching) em vez de "Apenas Lançamentos" (Releases only) você receberá notificações quando alguém tiver uma nova pergunta. @@ -84,7 +84,7 @@ Assim podendo tentar ajudar a resolver essas questões. ## Faça perguntas -É possível criar uma nova pergunta no repositório do GitHub, por exemplo: +É possível criar uma nova pergunta no repositório do GitHub, por exemplo: * Faça uma **pergunta** ou pergunte sobre um **problema**. * Sugira novos **recursos**. @@ -96,9 +96,9 @@ Assim podendo tentar ajudar a resolver essas questões. É possível [contribuir](contributing.md){.internal-link target=_blank} no código fonte fazendo Pull Requests, por exemplo: * Para corrigir um erro de digitação que você encontrou na documentação. -* Para compartilhar um artigo, video, ou podcast criados por você sobre o FastAPI editando este arquivo. +* Para compartilhar um artigo, video, ou podcast criados por você sobre o FastAPI editando este arquivo. * Não se esqueça de adicionar o link no começo da seção correspondente. -* Para ajudar [traduzir a documentação](contributing.md#translations){.internal-link target=_blank} para sua lingua. +* Para ajudar [traduzir a documentação](contributing.md#traducoes){.internal-link target=_blank} para sua lingua. * Também é possivel revisar as traduções já existentes. * Para propor novas seções na documentação. * Para corrigir um bug/questão. @@ -109,10 +109,13 @@ Assim podendo tentar ajudar a resolver essas questões. Entre no 👥 server de conversa do Discord 👥 e conheça novas pessoas da comunidade do FastAPI. -!!! dica - Para perguntas, pergunte nas questões do GitHub, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#experts){.internal-link target=_blank}. +/// tip | Dica - Use o chat apenas para outro tipo de assunto. +Para perguntas, pergunte nas questões do GitHub, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. + +Use o chat apenas para outro tipo de assunto. + +/// ### Não faça perguntas no chat @@ -120,7 +123,7 @@ Tenha em mente que os chats permitem uma "conversa mais livre", dessa forma é m Nas questões do GitHub o template irá te guiar para que você faça a sua pergunta de um jeito mais correto, fazendo com que você receba respostas mais completas, e até mesmo que você mesmo resolva o problema antes de perguntar. E no GitHub eu garanto que sempre irei responder todas as perguntas, mesmo que leve um tempo. Eu pessoalmente não consigo fazer isso via chat. 😅 -Conversas no chat não são tão fáceis de serem encontrados quanto no GitHub, então questões e respostas podem se perder dentro da conversa. E apenas as que estão nas questões do GitHub contam para você se tornar um [Expert em FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, então você receberá mais atenção nas questões do GitHub. +Conversas no chat não são tão fáceis de serem encontrados quanto no GitHub, então questões e respostas podem se perder dentro da conversa. E apenas as que estão nas questões do GitHub contam para você se tornar um [Expert em FastAPI](fastapi-people.md#especialistas){.internal-link target=_blank}, então você receberá mais atenção nas questões do GitHub. Por outro lado, existem milhares de usuários no chat, então tem uma grande chance de você encontrar alguém para trocar uma idéia por lá em qualquer horário. 😄 diff --git a/docs/pt/docs/history-design-future.md b/docs/pt/docs/history-design-future.md index a7a177660..4ec217405 100644 --- a/docs/pt/docs/history-design-future.md +++ b/docs/pt/docs/history-design-future.md @@ -1,6 +1,6 @@ # História, Design e Futuro -Há algum tempo, um usuário **FastAPI** perguntou: +Há algum tempo, um usuário **FastAPI** perguntou: > Qual é a história desse projeto? Parece que surgiu do nada e se tornou incrível em poucas semanas [...] diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..675b812e6 --- /dev/null +++ b/docs/pt/docs/how-to/conditional-openapi.md @@ -0,0 +1,58 @@ +# OpenAPI condicional + +Se necessário, você pode usar configurações e variáveis ​​de ambiente para configurar o OpenAPI condicionalmente, dependendo do ambiente, e até mesmo desativá-lo completamente. + +## Sobre segurança, APIs e documentos + +Ocultar suas interfaces de usuário de documentação na produção *não deveria* ser a maneira de proteger sua API. + +Isso não adiciona nenhuma segurança extra à sua API; as *operações de rotas* ainda estarão disponíveis onde estão. + +Se houver uma falha de segurança no seu código, ela ainda existirá. + +Ocultar a documentação apenas torna mais difícil entender como interagir com sua API e pode dificultar sua depuração na produção. Pode ser considerado simplesmente uma forma de Segurança através da obscuridade. + +Se você quiser proteger sua API, há várias coisas melhores que você pode fazer, por exemplo: + +* Certifique-se de ter modelos Pydantic bem definidos para seus corpos de solicitação e respostas. +* Configure quaisquer permissões e funções necessárias usando dependências. +* Nunca armazene senhas em texto simples, apenas hashes de senha. +* Implemente e use ferramentas criptográficas bem conhecidas, como tokens JWT e Passlib, etc. +* Adicione controles de permissão mais granulares com escopos OAuth2 quando necessário. +* ...etc. + +No entanto, você pode ter um caso de uso muito específico em que realmente precisa desabilitar a documentação da API para algum ambiente (por exemplo, para produção) ou dependendo de configurações de variáveis ​​de ambiente. + +## OpenAPI condicional com configurações e variáveis ​​de ambiente + +Você pode usar facilmente as mesmas configurações do Pydantic para configurar sua OpenAPI gerada e as interfaces de usuário de documentos. + +Por exemplo: + +```Python hl_lines="6 11" +{!../../docs_src/conditional_openapi/tutorial001.py!} +``` + +Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`. + +E então o usamos ao criar o aplicativo `FastAPI`. + +Então você pode desabilitar o OpenAPI (incluindo os documentos da interface do usuário) definindo a variável de ambiente `OPENAPI_URL` como uma string vazia, como: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Então, se você acessar as URLs em `/openapi.json`, `/docs` ou `/redoc`, você receberá apenas um erro `404 Não Encontrado` como: + +```JSON +{ + "detail": "Not Found" +} +``` diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..58bb1557c --- /dev/null +++ b/docs/pt/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,78 @@ +# Configurar Swagger UI + +Você pode configurar alguns parâmetros extras da UI do Swagger. + +Para configurá-los, passe o argumento `swagger_ui_parameters` ao criar o objeto de aplicativo `FastAPI()` ou para a função `get_swagger_ui_html()`. + +`swagger_ui_parameters` recebe um dicionário com as configurações passadas diretamente para o Swagger UI. + +O FastAPI converte as configurações para **JSON** para torná-las compatíveis com JavaScript, pois é disso que o Swagger UI precisa. + +## Desabilitar realce de sintaxe + +Por exemplo, você pode desabilitar o destaque de sintaxe na UI do Swagger. + +Sem alterar as configurações, o destaque de sintaxe é habilitado por padrão: + + + +Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: + +```Python hl_lines="3" +{!../../docs_src/configure_swagger_ui/tutorial001.py!} +``` + +...e então o Swagger UI não mostrará mais o destaque de sintaxe: + + + +## Alterar o tema + +Da mesma forma que você pode definir o tema de destaque de sintaxe com a chave `"syntaxHighlight.theme"` (observe que há um ponto no meio): + +```Python hl_lines="3" +{!../../docs_src/configure_swagger_ui/tutorial002.py!} +``` + +Essa configuração alteraria o tema de cores de destaque de sintaxe: + + + +## Alterar parâmetros de UI padrão do Swagger + +O FastAPI inclui alguns parâmetros de configuração padrão apropriados para a maioria dos casos de uso. + +Inclui estas configurações padrão: + +```Python +{!../../fastapi/openapi/docs.py[ln:7-23]!} +``` + +Você pode substituir qualquer um deles definindo um valor diferente no argumento `swagger_ui_parameters`. + +Por exemplo, para desabilitar `deepLinking` você pode passar essas configurações para `swagger_ui_parameters`: + +```Python hl_lines="3" +{!../../docs_src/configure_swagger_ui/tutorial003.py!} +``` + +## Outros parâmetros da UI do Swagger + +Para ver todas as outras configurações possíveis que você pode usar, leia a documentação oficial dos parâmetros da UI do Swagger. + +## Configurações somente JavaScript + +A interface do usuário do Swagger também permite que outras configurações sejam objetos **somente JavaScript** (por exemplo, funções JavaScript). + +O FastAPI também inclui estas configurações de `predefinições` somente para JavaScript: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +Esses são objetos **JavaScript**, não strings, então você não pode passá-los diretamente do código Python. + +Se você precisar usar configurações somente JavaScript como essas, você pode usar um dos métodos acima. Sobrescreva todas as *operações de rotas* do Swagger UI e escreva manualmente qualquer JavaScript que você precisar. diff --git a/docs/pt/docs/how-to/custom-docs-ui-assets.md b/docs/pt/docs/how-to/custom-docs-ui-assets.md new file mode 100644 index 000000000..00dd144c9 --- /dev/null +++ b/docs/pt/docs/how-to/custom-docs-ui-assets.md @@ -0,0 +1,205 @@ +# Recursos Estáticos Personalizados para a UI de Documentação (Hospedagem Própria) + +A documentação da API usa **Swagger UI** e **ReDoc**, e cada um deles precisa de alguns arquivos JavaScript e CSS. + +Por padrão, esses arquivos são fornecidos por um CDN. + +Mas é possível personalizá-los, você pode definir um CDN específico ou providenciar os arquivos você mesmo. + +## CDN Personalizado para JavaScript e CSS + +Vamos supor que você deseja usar um CDN diferente, por exemplo, você deseja usar `https://unpkg.com/`. + +Isso pode ser útil se, por exemplo, você mora em um país que restringe algumas URLs. + +### Desativar a documentação automática + +O primeiro passo é desativar a documentação automática, pois por padrão, ela usa o CDN padrão. + +Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: + +```Python hl_lines="8" +{!../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +### Incluir a documentação personalizada + +Agora você pode criar as *operações de rota* para a documentação personalizada. + +Você pode reutilizar as funções internas do FastAPI para criar as páginas HTML para a documentação e passar os argumentos necessários: + +* `openapi_url`: a URL onde a página HTML para a documentação pode obter o esquema OpenAPI para a sua API. Você pode usar aqui o atributo `app.openapi_url`. +* `title`: o título da sua API. +* `oauth2_redirect_url`: você pode usar `app.swagger_ui_oauth2_redirect_url` aqui para usar o padrão. +* `swagger_js_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **JavaScript**. Este é o URL do CDN personalizado. +* `swagger_css_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **CSS**. Este é o URL do CDN personalizado. + +E de forma semelhante para o ReDoc... + +```Python hl_lines="2-6 11-19 22-24 27-33" +{!../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +/// tip | Dica + +A *operação de rota* para `swagger_ui_redirect` é um auxiliar para quando você usa OAuth2. + +Se você integrar sua API com um provedor OAuth2, você poderá autenticar e voltar para a documentação da API com as credenciais adquiridas. E interagir com ela usando a autenticação OAuth2 real. + +Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse auxiliar de "redirecionamento". + +/// + +### Criar uma *operação de rota* para testar + +Agora, para poder testar se tudo funciona, crie uma *operação de rota*: + +```Python hl_lines="36-38" +{!../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +### Teste + +Agora, você deve ser capaz de ir para a documentação em http://127.0.0.1:8000/docs, e recarregar a página, ela carregará esses recursos do novo CDN. + +## Hospedagem Própria de JavaScript e CSS para a documentação + +Hospedar o JavaScript e o CSS pode ser útil se, por exemplo, você precisa que seu aplicativo continue funcionando mesmo offline, sem acesso aberto à Internet, ou em uma rede local. + +Aqui você verá como providenciar esses arquivos você mesmo, no mesmo aplicativo FastAPI, e configurar a documentação para usá-los. + +### Estrutura de Arquivos do Projeto + +Vamos supor que a estrutura de arquivos do seu projeto se pareça com isso: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +``` + +Agora crie um diretório para armazenar esses arquivos estáticos. + +Sua nova estrutura de arquivos poderia se parecer com isso: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static/ +``` + +### Baixe os arquivos + +Baixe os arquivos estáticos necessários para a documentação e coloque-os no diretório `static/`. + +Você provavelmente pode clicar com o botão direito em cada link e selecionar uma opção semelhante a `Salvar link como...`. + +**Swagger UI** usa os arquivos: + +* `swagger-ui-bundle.js` +* `swagger-ui.css` + +E o **ReDoc** usa os arquivos: + +* `redoc.standalone.js` + +Depois disso, sua estrutura de arquivos deve se parecer com: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static + ├── redoc.standalone.js + ├── swagger-ui-bundle.js + └── swagger-ui.css +``` + +### Prover os arquivos estáticos + +* Importe `StaticFiles`. +* "Monte" a instância `StaticFiles()` em um caminho específico. + +```Python hl_lines="7 11" +{!../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Teste os arquivos estáticos + +Inicialize seu aplicativo e vá para http://127.0.0.1:8000/static/redoc.standalone.js. + +Você deverá ver um arquivo JavaScript muito longo para o **ReDoc**. + +Esse arquivo pode começar com algo como: + +```JavaScript +/*! + * ReDoc - OpenAPI/Swagger-generated API Reference Documentation + * ------------------------------------------------------------- + * Version: "2.0.0-rc.18" + * Repo: https://github.com/Redocly/redoc + */ +!function(e,t){"object"==typeof exports&&"object"==typeof m + +... +``` + +Isso confirma que você está conseguindo fornecer arquivos estáticos do seu aplicativo e que você colocou os arquivos estáticos para a documentação no local correto. + +Agora, podemos configurar o aplicativo para usar esses arquivos estáticos para a documentação. + +### Desativar a documentação automática para arquivos estáticos + +Da mesma forma que ao usar um CDN personalizado, o primeiro passo é desativar a documentação automática, pois ela usa o CDN padrão. + +Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: + +```Python hl_lines="9" +{!../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Incluir a documentação personalizada para arquivos estáticos + +E da mesma forma que com um CDN personalizado, agora você pode criar as *operações de rota* para a documentação personalizada. + +Novamente, você pode reutilizar as funções internas do FastAPI para criar as páginas HTML para a documentação e passar os argumentos necessários: + +* `openapi_url`: a URL onde a página HTML para a documentação pode obter o esquema OpenAPI para a sua API. Você pode usar aqui o atributo `app.openapi_url`. +* `title`: o título da sua API. +* `oauth2_redirect_url`: Você pode usar `app.swagger_ui_oauth2_redirect_url` aqui para usar o padrão. +* `swagger_js_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **JavaScript**. Este é o URL do CDN personalizado. **Este é o URL que seu aplicativo está fornecendo**. +* `swagger_css_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **CSS**. **Esse é o que seu aplicativo está fornecendo**. + +E de forma semelhante para o ReDoc... + +```Python hl_lines="2-6 14-22 25-27 30-36" +{!../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +/// tip | Dica + +A *operação de rota* para `swagger_ui_redirect` é um auxiliar para quando você usa OAuth2. + +Se você integrar sua API com um provedor OAuth2, você poderá autenticar e voltar para a documentação da API com as credenciais adquiridas. E, então, interagir com ela usando a autenticação OAuth2 real. + +Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse auxiliar de "redirect". + +/// + +### Criar uma *operação de rota* para testar arquivos estáticos + +Agora, para poder testar se tudo funciona, crie uma *operação de rota*: + +```Python hl_lines="39-41" +{!../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Teste a UI de Arquivos Estáticos + +Agora, você deve ser capaz de desconectar o WiFi, ir para a documentação em http://127.0.0.1:8000/docs, e recarregar a página. + +E mesmo sem Internet, você será capaz de ver a documentação da sua API e interagir com ela. diff --git a/docs/pt/docs/how-to/custom-request-and-route.md b/docs/pt/docs/how-to/custom-request-and-route.md new file mode 100644 index 000000000..64325eed9 --- /dev/null +++ b/docs/pt/docs/how-to/custom-request-and-route.md @@ -0,0 +1,121 @@ +# Requisições Personalizadas e Classes da APIRoute + +Em algum casos, você pode querer sobreescrever a lógica usada pelas classes `Request`e `APIRoute`. + +Em particular, isso pode ser uma boa alternativa para uma lógica em um middleware + +Por exemplo, se você quiser ler ou manipular o corpo da requisição antes que ele seja processado pela sua aplicação. + +/// danger | Perigo + +Isso é um recurso "avançado". + +Se você for um iniciante em **FastAPI** você deve considerar pular essa seção. + +/// + +## Casos de Uso + +Alguns casos de uso incluem: + +* Converter requisições não-JSON para JSON (por exemplo, `msgpack`). +* Descomprimir corpos de requisição comprimidos com gzip. +* Registrar automaticamente todos os corpos de requisição. + +## Manipulando codificações de corpo de requisição personalizadas + +Vamos ver como usar uma subclasse personalizada de `Request` para descomprimir requisições gzip. + +E uma subclasse de `APIRoute` para usar essa classe de requisição personalizada. + +### Criar uma classe `GzipRequest` personalizada + +/// tip | Dica + +Isso é um exemplo de brincadeira para demonstrar como funciona, se você precisar de suporte para Gzip, você pode usar o [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} fornecido. + +/// + +Primeiro, criamos uma classe `GzipRequest`, que irá sobrescrever o método `Request.body()` para descomprimir o corpo na presença de um cabeçalho apropriado. + +Se não houver `gzip` no cabeçalho, ele não tentará descomprimir o corpo. + +Dessa forma, a mesma classe de rota pode lidar com requisições comprimidas ou não comprimidas. + +```Python hl_lines="8-15" +{!../../docs_src/custom_request_and_route/tutorial001.py!} +``` + +### Criar uma classe `GzipRoute` personalizada + +Em seguida, criamos uma subclasse personalizada de `fastapi.routing.APIRoute` que fará uso do `GzipRequest`. + +Dessa vez, ele irá sobrescrever o método `APIRoute.get_route_handler()`. + +Esse método retorna uma função. E essa função é o que irá receber uma requisição e retornar uma resposta. + +Aqui nós usamos para criar um `GzipRequest` a partir da requisição original. + +```Python hl_lines="18-26" +{!../../docs_src/custom_request_and_route/tutorial001.py!} +``` + +/// note | Detalhes Técnicos + +Um `Request` também tem um `request.receive`, que é uma função para "receber" o corpo da requisição. + +Um `Request` também tem um `request.receive`, que é uma função para "receber" o corpo da requisição. + +O dicionário `scope` e a função `receive` são ambos parte da especificação ASGI. + +E essas duas coisas, `scope` e `receive`, são o que é necessário para criar uma nova instância de `Request`. + +Para aprender mais sobre o `Request` confira a documentação do Starlette sobre Requests. + +/// + +A única coisa que a função retornada por `GzipRequest.get_route_handler` faz de diferente é converter o `Request` para um `GzipRequest`. + +Fazendo isso, nosso `GzipRequest` irá cuidar de descomprimir os dados (se necessário) antes de passá-los para nossas *operações de rota*. + +Depois disso, toda a lógica de processamento é a mesma. + +Mas por causa das nossas mudanças em `GzipRequest.body`, o corpo da requisição será automaticamente descomprimido quando for carregado pelo **FastAPI** quando necessário. + +## Acessando o corpo da requisição em um manipulador de exceção + +/// tip | Dica + +Para resolver esse mesmo problema, é provavelmente muito mais fácil usar o `body` em um manipulador personalizado para `RequestValidationError` ([Tratando Erros](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). + +Mas esse exemplo ainda é valido e mostra como interagir com os componentes internos. + +/// + +Também podemos usar essa mesma abordagem para acessar o corpo da requisição em um manipulador de exceção. + +Tudo que precisamos fazer é manipular a requisição dentro de um bloco `try`/`except`: + +```Python hl_lines="13 15" +{!../../docs_src/custom_request_and_route/tutorial002.py!} +``` + +Se uma exceção ocorrer, a instância `Request` ainda estará em escopo, então podemos ler e fazer uso do corpo da requisição ao lidar com o erro: + +```Python hl_lines="16-18" +{!../../docs_src/custom_request_and_route/tutorial002.py!} +``` + +## Classe `APIRoute` personalizada em um router + +você também pode definir o parametro `route_class` de uma `APIRouter`; + +```Python hl_lines="26" +{!../../docs_src/custom_request_and_route/tutorial003.py!} +``` + +Nesse exemplo, as *operações de rota* sob o `router` irão usar a classe `TimedRoute` personalizada, e terão um cabeçalho extra `X-Response-Time` na resposta com o tempo que levou para gerar a resposta: + +```Python hl_lines="13-20" +{!../../docs_src/custom_request_and_route/tutorial003.py!} +``` diff --git a/docs/pt/docs/how-to/extending-openapi.md b/docs/pt/docs/how-to/extending-openapi.md new file mode 100644 index 000000000..40917325b --- /dev/null +++ b/docs/pt/docs/how-to/extending-openapi.md @@ -0,0 +1,91 @@ + +# Extendendo o OpenAPI + +Existem alguns casos em que pode ser necessário modificar o esquema OpenAPI gerado. + +Nesta seção, você verá como fazer isso. + +## O processo normal + +O processo normal (padrão) é o seguinte: + +Uma aplicação (instância) do `FastAPI` possui um método `.openapi()` que deve retornar o esquema OpenAPI. + +Como parte da criação do objeto de aplicação, uma *operação de rota* para `/openapi.json` (ou para o que você definir como `openapi_url`) é registrada. + +Ela apenas retorna uma resposta JSON com o resultado do método `.openapi()` da aplicação. + +Por padrão, o que o método `.openapi()` faz é verificar se a propriedade `.openapi_schema` tem conteúdo e retorná-lo. + +Se não tiver, ele gera o conteúdo usando a função utilitária em `fastapi.openapi.utils.get_openapi`. + +E essa função `get_openapi()` recebe como parâmetros: + +* `title`: O título do OpenAPI, exibido na documentação. +* `version`: A versão da sua API, por exemplo, `2.5.0`. +* `openapi_version`: A versão da especificação OpenAPI utilizada. Por padrão, a mais recente: `3.1.0`. +* `summary`: Um resumo curto da API. +* `description`: A descrição da sua API, que pode incluir markdown e será exibida na documentação. +* `routes`: Uma lista de rotas, que são cada uma das *operações de rota* registradas. Elas são obtidas de `app.routes`. + +/// info | Informação + +O parâmetro `summary` está disponível no OpenAPI 3.1.0 e superior, suportado pelo FastAPI 0.99.0 e superior. + +/// + +## Sobrescrevendo os padrões + +Com as informações acima, você pode usar a mesma função utilitária para gerar o esquema OpenAPI e sobrescrever cada parte que precisar. + +Por exemplo, vamos adicionar Extensão OpenAPI do ReDoc para incluir um logo personalizado. + +### **FastAPI** Normal + +Primeiro, escreva toda a sua aplicação **FastAPI** normalmente: + +```Python hl_lines="1 4 7-9" +{!../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Gerar o esquema OpenAPI + +Em seguida, use a mesma função utilitária para gerar o esquema OpenAPI, dentro de uma função `custom_openapi()`: + +```Python hl_lines="2 15-21" +{!../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Modificar o esquema OpenAPI + +Agora, você pode adicionar a extensão do ReDoc, incluindo um `x-logo` personalizado ao "objeto" `info` no esquema OpenAPI: + +```Python hl_lines="22-24" +{!../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Armazenar em cache o esquema OpenAPI + +Você pode usar a propriedade `.openapi_schema` como um "cache" para armazenar o esquema gerado. + +Dessa forma, sua aplicação não precisará gerar o esquema toda vez que um usuário abrir a documentação da sua API. + +Ele será gerado apenas uma vez, e o mesmo esquema armazenado em cache será utilizado nas próximas requisições. + +```Python hl_lines="13-14 25-26" +{!../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Sobrescrever o método + +Agora, você pode substituir o método `.openapi()` pela sua nova função. + +```Python hl_lines="29" +{!../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Verificar + +Uma vez que você acessar http://127.0.0.1:8000/redoc, verá que está usando seu logo personalizado (neste exemplo, o logo do **FastAPI**): + + diff --git a/docs/pt/docs/how-to/general.md b/docs/pt/docs/how-to/general.md new file mode 100644 index 000000000..4f21463b2 --- /dev/null +++ b/docs/pt/docs/how-to/general.md @@ -0,0 +1,39 @@ +# Geral - Como Fazer - Receitas + +Aqui estão vários links para outros locais na documentação, para perguntas gerais ou frequentes + +## Filtro de dados- Segurança + +Para assegurar que você não vai retornar mais dados do que deveria, leia a seção [Tutorial - Response Model - Return Type](../tutorial/response-model.md){.internal-link target=_blank}. + +## Tags de Documentação - OpenAPI +Para adicionar tags às suas *rotas* e agrupá-las na UI da documentação, leia a seção [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}. + +## Resumo e Descrição da documentação - OpenAPI + +Para adicionar um resumo e uma descrição às suas *rotas* e exibi-los na UI da documentação, leia a seção [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank}. + +## Documentação das Descrições de Resposta - OpenAPI + +Para definir a descrição de uma resposta exibida na interface da documentação, leia a seção [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank}. + +## Documentação para Depreciar uma *Operação de Rota* - OpenAPI + +Para depreciar uma *operação de rota* e exibi-la na interface da documentação, leia a seção [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank}. + +## Converter qualquer dado para JSON + + +Para converter qualquer dado para um formato compatível com JSON, leia a seção [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +## OpenAPI Metadata - Docs + +Para adicionar metadados ao seu esquema OpenAPI, incluindo licensa, versão, contato, etc, leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md){.internal-link target=_blank}. + +## OpenAPI com URL customizada + +Para customizar a URL do OpenAPI (ou removê-la), leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}. + +## URLs de documentação do OpenAPI + +Para alterar as URLs usadas ​​para as interfaces de usuário da documentação gerada automaticamente, leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}. diff --git a/docs/pt/docs/how-to/graphql.md b/docs/pt/docs/how-to/graphql.md new file mode 100644 index 000000000..250135e23 --- /dev/null +++ b/docs/pt/docs/how-to/graphql.md @@ -0,0 +1,62 @@ +# GraphQL + +Como o **FastAPI** é baseado no padrão **ASGI**, é muito fácil integrar qualquer biblioteca **GraphQL** também compatível com ASGI. + +Você pode combinar *operações de rota* normais do FastAPI com GraphQL na mesma aplicação. + +/// tip | Dica + +**GraphQL** resolve alguns casos de uso muito específicos. + +Ele tem **vantagens** e **desvantagens** quando comparado a **web APIs** comuns. + +Certifique-se de avaliar se os **benefícios** para o seu caso de uso compensam as **desvantagens**. 🤓 + +/// + +## Bibliotecas GraphQL + +Aqui estão algumas das bibliotecas **GraphQL** que têm suporte **ASGI**. Você pode usá-las com **FastAPI**: + +* Strawberry 🍓 + * Com docs para FastAPI +* Ariadne + * Com docs para FastAPI +* Tartiflette + * Com Tartiflette ASGI para fornecer integração ASGI +* Graphene + * Com starlette-graphene3 + +## GraphQL com Strawberry + +Se você precisar ou quiser trabalhar com **GraphQL**, **Strawberry** é a biblioteca **recomendada** pois tem o design mais próximo ao design do **FastAPI**, ela é toda baseada em **type annotations**. + +Dependendo do seu caso de uso, você pode preferir usar uma biblioteca diferente, mas se você me perguntasse, eu provavelmente sugeriria que você experimentasse o **Strawberry**. + +Aqui está uma pequena prévia de como você poderia integrar Strawberry com FastAPI: + +```Python hl_lines="3 22 25-26" +{!../../docs_src/graphql/tutorial001.py!} +``` + +Você pode aprender mais sobre Strawberry na documentação do Strawberry. + +E também na documentação sobre Strawberry com FastAPI. + +## Antigo `GraphQLApp` do Starlette + +Versões anteriores do Starlette incluiam uma classe `GraphQLApp` para integrar com Graphene. + +Ela foi descontinuada do Starlette, mas se você tem código que a utilizava, você pode facilmente **migrar** para starlette-graphene3, que cobre o mesmo caso de uso e tem uma **interface quase idêntica**. + +/// tip | Dica + +Se você precisa de GraphQL, eu ainda recomendaria que você desse uma olhada no Strawberry, pois ele é baseado em type annotations em vez de classes e tipos personalizados. + +/// + +## Saiba Mais + +Você pode aprender mais sobre **GraphQL** na documentação oficial do GraphQL. + +Você também pode ler mais sobre cada uma das bibliotecas descritas acima em seus links. diff --git a/docs/pt/docs/how-to/index.md b/docs/pt/docs/how-to/index.md new file mode 100644 index 000000000..6747b01c7 --- /dev/null +++ b/docs/pt/docs/how-to/index.md @@ -0,0 +1,13 @@ +# Como Fazer - Exemplos Práticos + +Aqui você encontrará diferentes exemplos práticos ou tutoriais de "como fazer" para vários tópicos. + +A maioria dessas ideias será mais ou menos **independente**, e na maioria dos casos você só precisará estudá-las se elas se aplicarem diretamente ao **seu projeto**. + +Se algo parecer interessante e útil para o seu projeto, vá em frente e dê uma olhada. Caso contrário, você pode simplesmente ignorá-lo. + +/// tip + +Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso. + +/// diff --git a/docs/pt/docs/how-to/separate-openapi-schemas.md b/docs/pt/docs/how-to/separate-openapi-schemas.md new file mode 100644 index 000000000..50d321d4c --- /dev/null +++ b/docs/pt/docs/how-to/separate-openapi-schemas.md @@ -0,0 +1,258 @@ +# Esquemas OpenAPI Separados para Entrada e Saída ou Não + +Ao usar **Pydantic v2**, o OpenAPI gerado é um pouco mais exato e **correto** do que antes. 😎 + +Inclusive, em alguns casos, ele terá até **dois JSON Schemas** no OpenAPI para o mesmo modelo Pydantic, para entrada e saída, dependendo se eles possuem **valores padrão**. + +Vamos ver como isso funciona e como alterar se for necessário. + +## Modelos Pydantic para Entrada e Saída + +Digamos que você tenha um modelo Pydantic com valores padrão, como este: + +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` + +
+ +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` + +
+ +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +
+ +//// + +### Modelo para Entrada + +Se você usar esse modelo como entrada, como aqui: + +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` + +
+ +//// + +//// tab | Python 3.9+ + +```Python hl_lines="16" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` + +
+ +//// + +//// tab | Python 3.8+ + +```Python hl_lines="16" +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +
+ +//// + +... então o campo `description` não será obrigatório. Porque ele tem um valor padrão de `None`. + +### Modelo de Entrada na Documentação + +Você pode confirmar que na documentação, o campo `description` não tem um **asterisco vermelho**, não é marcado como obrigatório: + +
+ +
+ +### Modelo para Saída + +Mas se você usar o mesmo modelo como saída, como aqui: + +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="21" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +//// + +... então, como `description` tem um valor padrão, se você **não retornar nada** para esse campo, ele ainda terá o **valor padrão**. + +### Modelo para Dados de Resposta de Saída + +Se você interagir com a documentação e verificar a resposta, mesmo que o código não tenha adicionado nada em um dos campos `description`, a resposta JSON contém o valor padrão (`null`): + +
+ +
+ +Isso significa que ele **sempre terá um valor**, só que às vezes o valor pode ser `None` (ou `null` em termos de JSON). + +Isso quer dizer que, os clientes que usam sua API não precisam verificar se o valor existe ou não, eles podem **assumir que o campo sempre estará lá**, mas que em alguns casos terá o valor padrão de `None`. + +A maneira de descrever isso no OpenAPI é marcar esse campo como **obrigatório**, porque ele sempre estará lá. + +Por causa disso, o JSON Schema para um modelo pode ser diferente dependendo se ele é usado para **entrada ou saída**: + +* para **entrada**, o `description` **não será obrigatório** +* para **saída**, ele será **obrigatório** (e possivelmente `None`, ou em termos de JSON, `null`) + +### Modelo para Saída na Documentação + +Você pode verificar o modelo de saída na documentação também, ambos `name` e `description` são marcados como **obrigatórios** com um **asterisco vermelho**: + +
+ +
+ +### Modelo para Entrada e Saída na Documentação + +E se você verificar todos os Schemas disponíveis (JSON Schemas) no OpenAPI, verá que há dois, um `Item-Input` e um `Item-Output`. + +Para `Item-Input`, `description` **não é obrigatório**, não tem um asterisco vermelho. + +Mas para `Item-Output`, `description` **é obrigatório**, tem um asterisco vermelho. + +
+ +
+ +Com esse recurso do **Pydantic v2**, sua documentação da API fica mais **precisa**, e se você tiver clientes e SDKs gerados automaticamente, eles serão mais precisos também, proporcionando uma melhor **experiência para desenvolvedores** e consistência. 🎉 + +## Não Separe Schemas + +Agora, há alguns casos em que você pode querer ter o **mesmo esquema para entrada e saída**. + +Provavelmente, o principal caso de uso para isso é se você já tem algum código de cliente/SDK gerado automaticamente e não quer atualizar todo o código de cliente/SDK gerado ainda, você provavelmente vai querer fazer isso em algum momento, mas talvez não agora. + +Nesse caso, você pode desativar esse recurso no **FastAPI**, com o parâmetro `separate_input_output_schemas=False`. + +/// info | Informação + +O suporte para `separate_input_output_schemas` foi adicionado no FastAPI `0.102.0`. 🤓 + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} +``` + +//// + +### Mesmo Esquema para Modelos de Entrada e Saída na Documentação + +E agora haverá um único esquema para entrada e saída para o modelo, apenas `Item`, e `description` **não será obrigatório**: + +
+ +
+ +Esse é o mesmo comportamento do Pydantic v1. 🤓 diff --git a/docs/pt/docs/how-to/testing-database.md b/docs/pt/docs/how-to/testing-database.md new file mode 100644 index 000000000..02f909f24 --- /dev/null +++ b/docs/pt/docs/how-to/testing-database.md @@ -0,0 +1,7 @@ +# Testando a Base de Dados + +Você pode estudar sobre bases de dados, SQL e SQLModel na documentação de SQLModel. 🤓 + +Aqui tem um mini tutorial de como usar SQLModel com FastAPI. ✨ + +Esse tutorial inclui uma sessão sobre testar bases de dados SQL. 😎 diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 05786a0aa..bc23114dc 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ Framework FastAPI, alta performance, fácil de aprender, fácil de codar, pronto para produção

- - Test + + Test - - Coverage + + Coverage Package version @@ -20,11 +26,11 @@ **Documentação**: https://fastapi.tiangolo.com -**Código fonte**: https://github.com/tiangolo/fastapi +**Código fonte**: https://github.com/fastapi/fastapi --- -FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python 3.8 ou superior, baseado nos _type hints_ padrões do Python. +FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python, baseado nos _type hints_ padrões do Python. Os recursos chave são: @@ -60,7 +66,7 @@ Os recursos chave são: "*[...] Estou usando **FastAPI** muito esses dias. [...] Estou na verdade planejando utilizar ele em todos os times de **serviços _Machine Learning_ na Microsoft**. Alguns deles estão sendo integrados no _core_ do produto **Windows** e alguns produtos **Office**.*" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -72,7 +78,7 @@ Os recursos chave são: "*Honestamente, o que você construiu parece super sólido e rebuscado. De muitas formas, eu queria que o **Hug** fosse assim - é realmente inspirador ver alguém que construiu ele.*" -
Timothy Crosley - criador doHug (ref)
+
Timothy Crosley - criador doHug (ref)
--- @@ -100,8 +106,6 @@ Se você estiver construindo uma aplicação Starlette para as partes web. @@ -119,7 +123,7 @@ $ pip install fastapi -Você também precisará de um servidor ASGI para produção, tal como Uvicorn ou Hypercorn. +Você também precisará de um servidor ASGI para produção, tal como Uvicorn ou Hypercorn.
@@ -316,7 +320,7 @@ Você faz com tipos padrão do Python moderno. Você não terá que aprender uma nova sintaxe, métodos ou classes de uma biblioteca específica etc. -Apenas **Python 3.8+** padrão. +Apenas **Python** padrão. Por exemplo, para um `int`: @@ -430,7 +434,7 @@ Para entender mais sobre performance, veja a seção email_validator - para validação de email. +* email-validator - para validação de email. Usados por Starlette: @@ -440,12 +444,12 @@ Usados por Starlette: * itsdangerous - Necessário para suporte a `SessionMiddleware`. * pyyaml - Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI). * graphene - Necessário para suporte a `GraphQLApp`. -* ujson - Necessário se você quer utilizar `UJSONResponse`. Usados por FastAPI / Starlette: * uvicorn - para o servidor que carrega e serve sua aplicação. * orjson - Necessário se você quer utilizar `ORJSONResponse`. +* ujson - Necessário se você quer utilizar `UJSONResponse`. Você pode instalar todas essas dependências com `pip install fastapi[all]`. diff --git a/docs/pt/docs/learn/index.md b/docs/pt/docs/learn/index.md new file mode 100644 index 000000000..b9a7f5972 --- /dev/null +++ b/docs/pt/docs/learn/index.md @@ -0,0 +1,5 @@ +# Aprender + +Nesta parte da documentação encontramos as seções introdutórias e os tutoriais para aprendermos como usar o **FastAPI**. + +Nós poderíamos considerar isto um **livro**, **curso**, a maneira **oficial** e recomendada de aprender o FastAPI. 😎 diff --git a/docs/pt/docs/project-generation.md b/docs/pt/docs/project-generation.md index c98bd069d..e5c935fd2 100644 --- a/docs/pt/docs/project-generation.md +++ b/docs/pt/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: **FastAPI** Python: +* _Backend_ **FastAPI** Python: * **Rápido**: Alta performance, no nível de **NodeJS** e **Go** (graças ao Starlette e Pydantic). * **Intuitivo**: Ótimo suporte de editor. _Auto-Complete_ em todo lugar. Menos tempo _debugando_. * **Fácil**: Projetado para ser fácil de usar e aprender. Menos tempo lendo documentações. diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index 52b2dad8e..90a361f40 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -1,28 +1,28 @@ # Introdução aos tipos Python -**Python 3.6 +** tem suporte para "type hints" opcionais. +O Python possui suporte para "dicas de tipo" ou "type hints" (também chamado de "anotações de tipo" ou "type annotations") -Esses **"type hints"** são uma nova sintaxe (desde Python 3.6+) que permite declarar o tipo de uma variável. +Esses **"type hints"** são uma sintaxe especial que permite declarar o tipo de uma variável. Ao declarar tipos para suas variáveis, editores e ferramentas podem oferecer um melhor suporte. -Este é apenas um **tutorial rápido / atualização** sobre type hints Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI** ... que é realmente muito pouco. +Este é apenas um **tutorial rápido / atualização** sobre type hints do Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI**... que é realmente muito pouco. O **FastAPI** é baseado nesses type hints, eles oferecem muitas vantagens e benefícios. Mas mesmo que você nunca use o **FastAPI**, você se beneficiaria de aprender um pouco sobre eles. -!!! note "Nota" - Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo. +/// note | Nota +Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo. + +/// ## Motivação Vamos começar com um exemplo simples: -```Python -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} A chamada deste programa gera: @@ -33,12 +33,10 @@ John Doe A função faz o seguinte: * Pega um `first_name` e `last_name`. -* Converte a primeira letra de cada uma em maiúsculas com `title ()`. -* Concatena com um espaço no meio. +* Converte a primeira letra de cada uma em maiúsculas com `title()`. +* Concatena com um espaço no meio. -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} ### Edite-o @@ -46,7 +44,7 @@ A função faz o seguinte: Mas agora imagine que você estava escrevendo do zero. -Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos ... +Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos... Mas então você deve chamar "esse método que converte a primeira letra em maiúscula". @@ -80,9 +78,7 @@ para: Esses são os "type hints": -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} Isso não é o mesmo que declarar valores padrão como seria com: @@ -94,37 +90,33 @@ Isso não é o mesmo que declarar valores padrão como seria com: Estamos usando dois pontos (`:`), não é igual a (`=`). -E adicionar type hints normalmente não muda o que acontece do que aconteceria sem elas. +E adicionar type hints normalmente não muda o que acontece do que aconteceria sem eles. Mas agora, imagine que você está novamente no meio da criação dessa função, mas com type hints. -No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl Space` e vê: +No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl+Space` e vê: -Com isso, você pode rolar, vendo as opções, até encontrar o que "toca uma campainha": +Com isso, você pode rolar, vendo as opções, até encontrar o que "soa familiar": ## Mais motivação -Marque esta função, ela já possui type hints: +Verifique esta função, ela já possui type hints: -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} -Como o editor conhece os tipos de variáveis, você não apenas obtém a conclusão, mas também as verificações de erro: +Como o editor conhece os tipos de variáveis, você não obtém apenas o preenchimento automático, mas também as verificações de erro: -Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str (age)`: +Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str(age)`: -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} -## Tipos de declaração +## Declarando Tipos Você acabou de ver o local principal para declarar type hints. Como parâmetros de função. @@ -141,44 +133,83 @@ Você pode usar, por exemplo: * `bool` * `bytes` -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} ### Tipos genéricos com parâmetros de tipo Existem algumas estruturas de dados que podem conter outros valores, como `dict`, `list`, `set` e `tuple`. E os valores internos também podem ter seu próprio tipo. -Para declarar esses tipos e os tipos internos, você pode usar o módulo Python padrão `typing`. +Estes tipos que possuem tipos internos são chamados de tipos "**genéricos**". E é possível declará-los mesmo com os seus tipos internos. + +Para declarar esses tipos e os tipos internos, você pode usar o módulo Python padrão `typing`. Ele existe especificamente para suportar esses type hints. + +#### Versões mais recentes do Python + +A sintaxe utilizando `typing` é **compatível** com todas as versões, desde o Python 3.6 até as últimas, incluindo o Python 3.9, 3.10, etc. + +Conforme o Python evolui, **novas versões** chegam com suporte melhorado para esses type annotations, e em muitos casos, você não precisará nem importar e utilizar o módulo `typing` para declarar os type annotations. + +Se você pode escolher uma versão mais recente do Python para o seu projeto, você poderá aproveitar isso ao seu favor. + +Em todos os documentos existem exemplos compatíveis com cada versão do Python (quando existem diferenças). + +Por exemplo, "**Python 3.6+**" significa que é compatível com o Python 3.6 ou superior (incluindo o 3.7, 3.8, 3.9, 3.10, etc). E "**Python 3.9+**" significa que é compatível com o Python 3.9 ou mais recente (incluindo o 3.10, etc). + +Se você pode utilizar a **versão mais recente do Python**, utilize os exemplos para as últimas versões. Eles terão as **melhores e mais simples sintaxes**, como por exemplo, "**Python 3.10+**". + +#### List -Ele existe especificamente para suportar esses type hints. +Por exemplo, vamos definir uma variável para ser uma `list` de `str`. -#### `List` +//// tab | Python 3.9+ -Por exemplo, vamos definir uma variável para ser uma `lista` de `str`. +Declare uma variável com a mesma sintaxe com dois pontos (`:`) -Em `typing`, importe `List` (com um `L` maiúsculo): +Como tipo, coloque `list`. + +Como a lista é o tipo que contém algum tipo interno, você coloca o tipo dentro de colchetes: + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +De `typing`, importe `List` (com o `L` maiúsculo): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` -Declare a variável com a mesma sintaxe de dois pontos (`:`). +Declare uma variável com a mesma sintaxe com dois pontos (`:`) -Como o tipo, coloque a `List`. +Como tipo, coloque o `List` que você importou de `typing`. -Como a lista é um tipo que contém alguns tipos internos, você os coloca entre colchetes: +Como a lista é o tipo que contém algum tipo interno, você coloca o tipo dentro de colchetes: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "Dica" - Esses tipos internos entre colchetes são chamados de "parâmetros de tipo". +//// + +/// info | Informação + +Estes tipos internos dentro dos colchetes são chamados "parâmetros de tipo" (type parameters). + +Neste caso, `str` é o parâmetro de tipo passado para `List` (ou `list` no Python 3.9 ou superior). - Nesse caso, `str` é o parâmetro de tipo passado para `List`. +/// -Isso significa que: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`". +Isso significa: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`". + +/// tip | Dica + +Se você usa o Python 3.9 ou superior, você não precisa importar `List` de `typing`. Você pode utilizar o mesmo tipo `list` no lugar. + +/// Ao fazer isso, seu editor pode fornecer suporte mesmo durante o processamento de itens da lista: @@ -190,20 +221,32 @@ Observe que a variável `item` é um dos elementos da lista `items`. E, ainda assim, o editor sabe que é um `str` e fornece suporte para isso. -#### `Tuple` e `Set` +#### Tuple e Set Você faria o mesmo para declarar `tuple`s e `set`s: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} ``` +//// + Isso significa que: * A variável `items_t` é uma `tuple` com 3 itens, um `int`, outro `int` e uma `str`. * A variável `items_s` é um `set`, e cada um de seus itens é do tipo `bytes`. -#### `Dict` +#### Dict Para definir um `dict`, você passa 2 parâmetros de tipo, separados por vírgulas. @@ -211,38 +254,181 @@ O primeiro parâmetro de tipo é para as chaves do `dict`. O segundo parâmetro de tipo é para os valores do `dict`: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} ``` +//// + Isso significa que: * A variável `prices` é um dict`: * As chaves deste `dict` são do tipo `str` (digamos, o nome de cada item). * Os valores deste `dict` são do tipo `float` (digamos, o preço de cada item). -#### `Opcional` +#### Union + +Você pode declarar que uma variável pode ser de qualquer um dentre **diversos tipos**. Por exemplo, um `int` ou um `str`. + +No Python 3.6 e superior (incluindo o Python 3.10), você pode utilizar o tipo `Union` de `typing`, e colocar dentro dos colchetes os possíveis tipos aceitáveis. + +No Python 3.10 também existe uma **nova sintaxe** onde você pode colocar os possívels tipos separados por uma barra vertical (`|`). + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +Em ambos os casos, isso significa que `item` poderia ser um `int` ou um `str`. + + +#### Possívelmente `None` + +Você pode declarar que um valor pode ter um tipo, como `str`, mas que ele também pode ser `None`. + +No Python 3.6 e superior (incluindo o Python 3.10) você pode declará-lo importando e utilizando `Optional` do módulo `typing`. + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009.py!} +``` + +O uso de `Optional[str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`. + +`Optional[Something]` é na verdade um atalho para `Union[Something, None]`, eles são equivalentes. + +Isso também significa que no Python 3.10, você pode utilizar `Something | None`: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative -Você também pode usar o `Opcional` para declarar que uma variável tem um tipo, como `str`, mas que é "opcional", o que significa que também pode ser `None`: +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### Utilizando `Union` ou `Optional` + +Se você está utilizando uma versão do Python abaixo da 3.10, aqui vai uma dica do meu ponto de vista bem **subjetivo**: + +* 🚨 Evite utilizar `Optional[SomeType]` +* No lugar, ✨ **use `Union[SomeType, None]`** ✨. + +Ambos são equivalentes, e no final das contas, eles são o mesmo. Mas eu recomendaria o `Union` ao invés de `Optional` porque a palavra **Optional** parece implicar que o valor é opcional, quando na verdade significa "isso pode ser `None`", mesmo que ele não seja opcional e ainda seja obrigatório. + +Eu penso que `Union[SomeType, None]` é mais explícito sobre o que ele significa. + +Isso é apenas sobre palavras e nomes. Mas estas palavras podem afetar como os seus colegas de trabalho pensam sobre o código. + +Por exemplo, vamos pegar esta função: + +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +O paâmetro `name` é definido como `Optional[str]`, mas ele **não é opcional**, você não pode chamar a função sem o parâmetro: + +```Python +say_hi() # Oh, no, this throws an error! 😱 +``` + +O parâmetro `name` **ainda é obrigatório** (não *opicional*) porque ele não possui um valor padrão. Mesmo assim, `name` aceita `None` como valor: + +```Python +say_hi(name=None) # This works, None is valid 🎉 ``` -O uso de `Opcional [str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`. +A boa notícia é, quando você estiver no Python 3.10 você não precisará se preocupar mais com isso, pois você poderá simplesmente utilizar o `|` para definir uniões de tipos: + +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + +E então você não precisará mais se preocupar com nomes como `Optional` e `Union`. 😎 #### Tipos genéricos -Esses tipos que usam parâmetros de tipo entre colchetes, como: +Esses tipos que usam parâmetros de tipo entre colchetes são chamados **tipos genéricos** ou **genéricos**. Por exemplo: + +//// tab | Python 3.10+ + +Você pode utilizar os mesmos tipos internos como genéricos (com colchetes e tipos dentro): + +* `list` +* `tuple` +* `set` +* `dict` + +E o mesmo como no Python 3.8, do módulo `typing`: + +* `Union` +* `Optional` (o mesmo que com o 3.8) +* ...entro outros. + +No Python 3.10, como uma alternativa para a utilização dos genéricos `Union` e `Optional`, você pode usar a barra vertical (`|`) para declarar uniões de tipos. Isso é muito melhor e mais simples. + +//// + +//// tab | Python 3.9+ + +Você pode utilizar os mesmos tipos internos como genéricos (com colchetes e tipos dentro): + +* `list` +* `tuple` +* `set` +* `dict` + +E o mesmo como no Python 3.8, do módulo `typing`: + +* `Union` +* `Optional` +* ...entro outros. + +//// + +//// tab | Python 3.8+ * `List` * `Tuple` * `Set` * `Dict` -* `Opcional` -* ...e outros. +* `Union` +* `Optional` +* ...entro outros. -são chamados **tipos genéricos** ou **genéricos**. +//// ### Classes como tipos @@ -250,23 +436,23 @@ Você também pode declarar uma classe como o tipo de uma variável. Digamos que você tenha uma classe `Person`, com um nome: -```Python hl_lines="1 2 3" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} Então você pode declarar que uma variável é do tipo `Person`: -```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} E então, novamente, você recebe todo o suporte do editor: +Perceba que isso significa que "`one_person` é uma **instância** da classe `Person`". + +Isso não significa que "`one_person` é a **classe** chamada `Person`". + ## Modelos Pydantic - Pydantic é uma biblioteca Python para executar a validação de dados. +O Pydantic é uma biblioteca Python para executar a validação de dados. Você declara a "forma" dos dados como classes com atributos. @@ -278,18 +464,93 @@ E você recebe todo o suporte do editor com esse objeto resultante. Retirado dos documentos oficiais dos Pydantic: +//// tab | Python 3.10+ + ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` -!!! info "Informação" - Para saber mais sobre o Pydantic, verifique seus documentos . +//// + +//// tab | Python 3.9+ -**FastAPI** é todo baseado em Pydantic. +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info | Informação + +Para saber mais sobre o Pydantic, verifique a sua documentação. + +/// + +O **FastAPI** é todo baseado em Pydantic. Você verá muito mais disso na prática no [Tutorial - Guia do usuário](tutorial/index.md){.internal-link target=_blank}. -## Type hints em **FastAPI** +/// tip | Dica + +O Pydantic tem um comportamento especial quando você usa `Optional` ou `Union[Something, None]` sem um valor padrão. Você pode ler mais sobre isso na documentação do Pydantic sobre campos Opcionais Obrigatórios. + +/// + + +## Type Hints com Metadados de Anotações + +O Python possui uma funcionalidade que nos permite incluir **metadados adicionais** nos type hints utilizando `Annotated`. + +//// tab | Python 3.9+ + +No Python 3.9, `Annotated` é parte da biblioteca padrão, então você pode importá-lo de `typing`. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +Em versões abaixo do Python 3.9, você importa `Annotated` de `typing_extensions`. + +Ele já estará instalado com o **FastAPI**. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` + +//// + +O Python em si não faz nada com este `Annotated`. E para editores e outras ferramentas, o tipo ainda é `str`. + +Mas você pode utilizar este espaço dentro do `Annotated` para fornecer ao **FastAPI** metadata adicional sobre como você deseja que a sua aplicação se comporte. + +O importante aqui de se lembrar é que **o primeiro *type parameter*** que você informar ao `Annotated` é o **tipo de fato**. O resto é apenas metadado para outras ferramentas. + +Por hora, você precisa apenas saber que o `Annotated` existe, e que ele é Python padrão. 😎 + +Mais tarde você verá o quão **poderoso** ele pode ser. + +/// tip | Dica + +O fato de que isso é **Python padrão** significa que você ainda obtém a **melhor experiência de desenvolvedor possível** no seu editor, com as ferramentas que você utiliza para analisar e refatorar o seu código, etc. ✨ + +E também que o seu código será muito compatível com diversas outras ferramentas e bibliotecas Python. 🚀 + +/// + + +## Type hints no **FastAPI** O **FastAPI** aproveita esses type hints para fazer várias coisas. @@ -298,18 +559,21 @@ Com o **FastAPI**, você declara parâmetros com type hints e obtém: * **Suporte ao editor**. * **Verificações de tipo**. -... e **FastAPI** usa as mesmas declarações para: +... e o **FastAPI** usa as mesmas declarações para: -* **Definir requisitos**: dos parâmetros do caminho da solicitação, parâmetros da consulta, cabeçalhos, corpos, dependências, etc. +* **Definir requisitos**: dos parâmetros de rota, parâmetros da consulta, cabeçalhos, corpos, dependências, etc. * **Converter dados**: da solicitação para o tipo necessário. * **Validar dados**: provenientes de cada solicitação: - * A geração de **erros automáticos** retornou ao cliente quando os dados são inválidos. -* **Documente** a API usando OpenAPI: + * Gerando **erros automáticos** retornados ao cliente quando os dados são inválidos. +* **Documentar** a API usando OpenAPI: * que é usado pelas interfaces de usuário da documentação interativa automática. Tudo isso pode parecer abstrato. Não se preocupe. Você verá tudo isso em ação no [Tutorial - Guia do usuário](tutorial/index.md){.internal-link target=_blank}. O importante é que, usando tipos padrão de Python, em um único local (em vez de adicionar mais classes, decoradores, etc.), o **FastAPI** fará muito trabalho para você. -!!! info "Informação" - Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` . +/// info | Informação + +Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` . + +/// diff --git a/docs/pt/docs/resources/index.md b/docs/pt/docs/resources/index.md new file mode 100644 index 000000000..6eff8f9e7 --- /dev/null +++ b/docs/pt/docs/resources/index.md @@ -0,0 +1,3 @@ +# Recursos + +Material complementar, links externos, artigos e muito mais. ✈️ diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md index 625fa2b11..6a69ae2af 100644 --- a/docs/pt/docs/tutorial/background-tasks.md +++ b/docs/pt/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Isso inclui, por exemplo: Primeiro, importe `BackgroundTasks` e defina um parâmetro em sua _função de operação de caminho_ com uma declaração de tipo de `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro. @@ -33,17 +31,13 @@ Nesse caso, a função de tarefa gravará em um arquivo (simulando o envio de um E como a operação de gravação não usa `async` e `await`, definimos a função com `def` normal: -```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Adicionar a tarefa em segundo plano Dentro de sua _função de operação de caminho_, passe sua função de tarefa para o objeto _tarefas em segundo plano_ com o método `.add_task()`: -```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` recebe como argumentos: @@ -57,9 +51,7 @@ Usar `BackgroundTasks` também funciona com o sistema de injeção de dependênc O **FastAPI** sabe o que fazer em cada caso e como reutilizar o mesmo objeto, de forma que todas as tarefas em segundo plano sejam mescladas e executadas em segundo plano posteriormente: -```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} -``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} Neste exemplo, as mensagens serão gravadas no arquivo `log.txt` _após_ o envio da resposta. diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..a094005fd --- /dev/null +++ b/docs/pt/docs/tutorial/bigger-applications.md @@ -0,0 +1,556 @@ +# Aplicações Maiores - Múltiplos Arquivos + +Se você está construindo uma aplicação ou uma API web, é raro que você possa colocar tudo em um único arquivo. + +**FastAPI** oferece uma ferramenta conveniente para estruturar sua aplicação, mantendo toda a flexibilidade. + +/// info | Informação + +Se você vem do Flask, isso seria o equivalente aos Blueprints do Flask. + +/// + +## Um exemplo de estrutura de arquivos + +Digamos que você tenha uma estrutura de arquivos como esta: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   ├── dependencies.py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── users.py +│   └── internal +│   ├── __init__.py +│   └── admin.py +``` + +/// tip | Dica + +Existem vários arquivos `__init__.py` presentes em cada diretório ou subdiretório. + +Isso permite a importação de código de um arquivo para outro. + +Por exemplo, no arquivo `app/main.py`, você poderia ter uma linha como: + +``` +from app.routers import items +``` + +/// + +* O diretório `app` contém todo o código da aplicação. Ele possui um arquivo `app/__init__.py` vazio, o que o torna um "pacote Python" (uma coleção de "módulos Python"): `app`. +* Dentro dele, o arquivo `app/main.py` está localizado em um pacote Python (diretório com `__init__.py`). Portanto, ele é um "módulo" desse pacote: `app.main`. +* Existem também um arquivo `app/dependencies.py`, assim como o `app/main.py`, ele é um "módulo": `app.dependencies`. +* Há um subdiretório `app/routers/` com outro arquivo `__init__.py`, então ele é um "subpacote Python": `app.routers`. +* O arquivo `app/routers/items.py` está dentro de um pacote, `app/routers/`, portanto, é um "submódulo": `app.routers.items`. +* O mesmo com `app/routers/users.py`, ele é outro submódulo: `app.routers.users`. +* Há também um subdiretório `app/internal/` com outro arquivo `__init__.py`, então ele é outro "subpacote Python":`app.internal`. +* E o arquivo `app/internal/admin.py` é outro submódulo: `app.internal.admin`. + + + +A mesma estrutura de arquivos com comentários: + +``` +. +├── app # "app" é um pacote Python +│   ├── __init__.py # este arquivo torna "app" um "pacote Python" +│   ├── main.py # "main" módulo, e.g. import app.main +│   ├── dependencies.py # "dependencies" módulo, e.g. import app.dependencies +│   └── routers # "routers" é um "subpacote Python" +│   │ ├── __init__.py # torna "routers" um "subpacote Python" +│   │ ├── items.py # "items" submódulo, e.g. import app.routers.items +│   │ └── users.py # "users" submódulo, e.g. import app.routers.users +│   └── internal # "internal" é um "subpacote Python" +│   ├── __init__.py # torna "internal" um "subpacote Python" +│   └── admin.py # "admin" submódulo, e.g. import app.internal.admin +``` + +## `APIRouter` + +Vamos supor que o arquivo dedicado a lidar apenas com usuários seja o submódulo em `/app/routers/users.py`. + +Você quer manter as *operações de rota* relacionadas aos seus usuários separadas do restante do código, para mantê-lo organizado. + +Mas ele ainda faz parte da mesma aplicação/web API **FastAPI** (faz parte do mesmo "pacote Python"). + +Você pode criar as *operações de rotas* para esse módulo usando o `APIRouter`. + +### Importar `APIRouter` + +você o importa e cria uma "instância" da mesma maneira que faria com a classe `FastAPI`: + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### *Operações de Rota* com `APIRouter` + +E então você o utiliza para declarar suas *operações de rota*. + +Utilize-o da mesma maneira que utilizaria a classe `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Você pode pensar em `APIRouter` como uma classe "mini `FastAPI`". + +Todas as mesmas opções são suportadas. + +Todos os mesmos `parameters`, `responses`, `dependencies`, `tags`, etc. + +/// tip | Dica + +Neste exemplo, a variável é chamada de `router`, mas você pode nomeá-la como quiser. + +/// + +Vamos incluir este `APIRouter` na aplicação principal `FastAPI`, mas primeiro, vamos verificar as dependências e outro `APIRouter`. + +## Dependências + +Vemos que precisaremos de algumas dependências usadas em vários lugares da aplicação. + +Então, as colocamos em seu próprio módulo de `dependencies` (`app/dependencies.py`). + +Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` personalizado: + +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated` se possível. + +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | Dica + +Estamos usando um cabeçalho inventado para simplificar este exemplo. + +Mas em casos reais, você obterá melhores resultados usando os [Utilitários de Segurança](security/index.md){.internal-link target=_blank} integrados. + +/// + +## Outro módulo com `APIRouter` + +Digamos que você também tenha os endpoints dedicados a manipular "itens" do seu aplicativo no módulo em `app/routers/items.py`. + +Você tem *operações de rota* para: + +* `/items/` +* `/items/{item_id}` + +É tudo a mesma estrutura de `app/routers/users.py`. + +Mas queremos ser mais inteligentes e simplificar um pouco o código. + +Sabemos que todas as *operações de rota* neste módulo têm o mesmo: + +* Path `prefix`: `/items`. +* `tags`: (apenas uma tag: `items`). +* Extra `responses`. +* `dependências`: todas elas precisam da dependência `X-Token` que criamos. + +Então, em vez de adicionar tudo isso a cada *operação de rota*, podemos adicioná-lo ao `APIRouter`. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Como o caminho de cada *operação de rota* deve começar com `/`, como em: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +...o prefixo não deve incluir um `/` final. + +Então, o prefixo neste caso é `/items`. + +Também podemos adicionar uma lista de `tags` e `responses` extras que serão aplicadas a todas as *operações de rota* incluídas neste roteador. + +E podemos adicionar uma lista de `dependencies` que serão adicionadas a todas as *operações de rota* no roteador e serão executadas/resolvidas para cada solicitação feita a elas. + +/// tip | Dica + +Observe que, assim como [dependências em *decoradores de operação de rota*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, nenhum valor será passado para sua *função de operação de rota*. + +/// + +O resultado final é que os caminhos dos itens agora são: + +* `/items/` +* `/items/{item_id}` + +...como pretendíamos. + +* Elas serão marcadas com uma lista de tags que contêm uma única string `"items"`. + * Essas "tags" são especialmente úteis para os sistemas de documentação interativa automática (usando OpenAPI). +* Todas elas incluirão as `responses` predefinidas. +* Todas essas *operações de rota* terão a lista de `dependencies` avaliada/executada antes delas. + * Se você também declarar dependências em uma *operação de rota* específica, **elas também serão executadas**. + * As dependências do roteador são executadas primeiro, depois as [`dependencies` no decorador](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} e, em seguida, as dependências de parâmetros normais. + * Você também pode adicionar [dependências de `Segurança` com `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. + +/// tip | Dica + +Ter `dependências` no `APIRouter` pode ser usado, por exemplo, para exigir autenticação para um grupo inteiro de *operações de rota*. Mesmo que as dependências não sejam adicionadas individualmente a cada uma delas. + +/// + +/// check + +Os parâmetros `prefix`, `tags`, `responses` e `dependencies` são (como em muitos outros casos) apenas um recurso do **FastAPI** para ajudar a evitar duplicação de código. + +/// + +### Importar as dependências + +Este código reside no módulo `app.routers.items`, o arquivo `app/routers/items.py`. + +E precisamos obter a função de dependência do módulo `app.dependencies`, o arquivo `app/dependencies.py`. + +Então usamos uma importação relativa com `..` para as dependências: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Como funcionam as importações relativas + +/// tip | Dica + +Se você sabe perfeitamente como funcionam as importações, continue para a próxima seção abaixo. + +/// + +Um único ponto `.`, como em: + +```Python +from .dependencies import get_token_header +``` + +significaria: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) vive (o diretório `app/routers/`)... +* encontre o módulo `dependencies` (um arquivo imaginário em `app/routers/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Mas esse arquivo não existe, nossas dependências estão em um arquivo em `app/dependencies.py`. + +Lembre-se de como nossa estrutura app/file se parece: + + + +--- + +Os dois pontos `..`, como em: + +```Python +from ..dependencies import get_token_header +``` + +significa: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) reside (o diretório `app/routers/`)... +* vá para o pacote pai (o diretório `app/`)... +* e lá, encontre o módulo `dependencies` (o arquivo em `app/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Isso funciona corretamente! 🎉 + +--- + +Da mesma forma, se tivéssemos usado três pontos `...`, como em: + +```Python +from ...dependencies import get_token_header +``` + +isso significaria: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) vive (o diretório `app/routers/`)... +* vá para o pacote pai (o diretório `app/`)... +* então vá para o pai daquele pacote (não há pacote pai, `app` é o nível superior 😱)... +* e lá, encontre o módulo `dependencies` (o arquivo em `app/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Isso se referiria a algum pacote acima de `app/`, com seu próprio arquivo `__init__.py`, etc. Mas não temos isso. Então, isso geraria um erro em nosso exemplo. 🚨 + +Mas agora você sabe como funciona, então você pode usar importações relativas em seus próprios aplicativos, não importa o quão complexos eles sejam. 🤓 + +### Adicione algumas `tags`, `respostas` e `dependências` personalizadas + +Não estamos adicionando o prefixo `/items` nem `tags=["items"]` a cada *operação de rota* porque os adicionamos ao `APIRouter`. + +Mas ainda podemos adicionar _mais_ `tags` que serão aplicadas a uma *operação de rota* específica, e também algumas `respostas` extras específicas para essa *operação de rota*: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +/// tip | Dica + +Esta última operação de caminho terá a combinação de tags: `["items", "custom"]`. + +E também terá ambas as respostas na documentação, uma para `404` e uma para `403`. + +/// + +## O principal `FastAPI` + +Agora, vamos ver o módulo em `app/main.py`. + +Aqui é onde você importa e usa a classe `FastAPI`. + +Este será o arquivo principal em seu aplicativo que une tudo. + +E como a maior parte de sua lógica agora viverá em seu próprio módulo específico, o arquivo principal será bem simples. + +### Importar `FastAPI` + +Você importa e cria uma classe `FastAPI` normalmente. + +E podemos até declarar [dependências globais](dependencies/global-dependencies.md){.internal-link target=_blank} que serão combinadas com as dependências para cada `APIRouter`: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Importe o `APIRouter` + +Agora importamos os outros submódulos que possuem `APIRouter`s: + +```Python hl_lines="4-5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Como os arquivos `app/routers/users.py` e `app/routers/items.py` são submódulos que fazem parte do mesmo pacote Python `app`, podemos usar um único ponto `.` para importá-los usando "importações relativas". + +### Como funciona a importação + +A seção: + +```Python +from .routers import items, users +``` + +significa: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/main.py`) reside (o diretório `app/`)... +* procure o subpacote `routers` (o diretório em `app/routers/`)... +* e dele, importe o submódulo `items` (o arquivo em `app/routers/items.py`) e `users` (o arquivo em `app/routers/users.py`)... + +O módulo `items` terá uma variável `router` (`items.router`). Esta é a mesma que criamos no arquivo `app/routers/items.py`, é um objeto `APIRouter`. + +E então fazemos o mesmo para o módulo `users`. + +Também poderíamos importá-los como: + +```Python +from app.routers import items, users +``` + +/// info | Informação + +A primeira versão é uma "importação relativa": + +```Python +from .routers import items, users +``` + +A segunda versão é uma "importação absoluta": + +```Python +from app.routers import items, users +``` + +Para saber mais sobre pacotes e módulos Python, leia a documentação oficial do Python sobre módulos. + +/// + +### Evite colisões de nomes + +Estamos importando o submódulo `items` diretamente, em vez de importar apenas sua variável `router`. + +Isso ocorre porque também temos outra variável chamada `router` no submódulo `users`. + +Se tivéssemos importado um após o outro, como: + +```Python +from .routers.items import router +from .routers.users import router +``` + +o `router` de `users` sobrescreveria o de `items` e não poderíamos usá-los ao mesmo tempo. + +Então, para poder usar ambos no mesmo arquivo, importamos os submódulos diretamente: + +```Python hl_lines="5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Incluir o `APIRouter`s para `usuários` e `itens` + +Agora, vamos incluir os `roteadores` dos submódulos `usuários` e `itens`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +/// info | Informação + +`users.router` contém o `APIRouter` dentro do arquivo `app/routers/users.py`. + +E `items.router` contém o `APIRouter` dentro do arquivo `app/routers/items.py`. + +/// + +Com `app.include_router()` podemos adicionar cada `APIRouter` ao aplicativo principal `FastAPI`. + +Ele incluirá todas as rotas daquele roteador como parte dele. + +/// note | Detalhe Técnico + +Na verdade, ele criará internamente uma *operação de rota* para cada *operação de rota* que foi declarada no `APIRouter`. + +Então, nos bastidores, ele realmente funcionará como se tudo fosse o mesmo aplicativo único. + +/// + +/// check + +Você não precisa se preocupar com desempenho ao incluir roteadores. + +Isso levará microssegundos e só acontecerá na inicialização. + +Então não afetará o desempenho. ⚡ + +/// + +### Incluir um `APIRouter` com um `prefix` personalizado, `tags`, `responses` e `dependencies` + +Agora, vamos imaginar que sua organização lhe deu o arquivo `app/internal/admin.py`. + +Ele contém um `APIRouter` com algumas *operações de rota* de administração que sua organização compartilha entre vários projetos. + +Para este exemplo, será super simples. Mas digamos que, como ele é compartilhado com outros projetos na organização, não podemos modificá-lo e adicionar um `prefix`, `dependencies`, `tags`, etc. diretamente ao `APIRouter`: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Mas ainda queremos definir um `prefixo` personalizado ao incluir o `APIRouter` para que todas as suas *operações de rota* comecem com `/admin`, queremos protegê-lo com as `dependências` que já temos para este projeto e queremos incluir `tags` e `responses`. + +Podemos declarar tudo isso sem precisar modificar o `APIRouter` original passando esses parâmetros para `app.include_router()`: + +```Python hl_lines="14-17" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Dessa forma, o `APIRouter` original permanecerá inalterado, para que possamos compartilhar o mesmo arquivo `app/internal/admin.py` com outros projetos na organização. + +O resultado é que em nosso aplicativo, cada uma das *operações de rota* do módulo `admin` terá: + +* O prefixo `/admin`. +* A tag `admin`. +* A dependência `get_token_header`. +* A resposta `418`. 🍵 + +Mas isso afetará apenas o `APIRouter` em nosso aplicativo, e não em nenhum outro código que o utilize. + +Assim, por exemplo, outros projetos poderiam usar o mesmo `APIRouter` com um método de autenticação diferente. + +### Incluir uma *operação de rota* + +Também podemos adicionar *operações de rota* diretamente ao aplicativo `FastAPI`. + +Aqui fazemos isso... só para mostrar que podemos 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +e funcionará corretamente, junto com todas as outras *operações de rota* adicionadas com `app.include_router()`. + +/// info | Detalhes Técnicos + +**Observação**: este é um detalhe muito técnico que você provavelmente pode **simplesmente pular**. + +--- + +Os `APIRouter`s não são "montados", eles não são isolados do resto do aplicativo. + +Isso ocorre porque queremos incluir suas *operações de rota* no esquema OpenAPI e nas interfaces de usuário. + +Como não podemos simplesmente isolá-los e "montá-los" independentemente do resto, as *operações de rota* são "clonadas" (recriadas), não incluídas diretamente. + +/// + +## Verifique a documentação automática da API + +Agora, execute `uvicorn`, usando o módulo `app.main` e a variável `app`: + +
+ +```console +$ uvicorn app.main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +E abra os documentos em http://127.0.0.1:8000/docs. + +Você verá a documentação automática da API, incluindo os caminhos de todos os submódulos, usando os caminhos (e prefixos) corretos e as tags corretas: + + + +## Incluir o mesmo roteador várias vezes com `prefixos` diferentes + +Você também pode usar `.include_router()` várias vezes com o *mesmo* roteador usando prefixos diferentes. + +Isso pode ser útil, por exemplo, para expor a mesma API sob prefixos diferentes, por exemplo, `/api/v1` e `/api/latest`. + +Esse é um uso avançado que você pode não precisar, mas está lá caso precise. + +## Incluir um `APIRouter` em outro + +Da mesma forma que você pode incluir um `APIRouter` em um aplicativo `FastAPI`, você pode incluir um `APIRouter` em outro `APIRouter` usando: + +```Python +router.include_router(other_router) +``` + +Certifique-se de fazer isso antes de incluir `router` no aplicativo `FastAPI`, para que as *operações de rota* de `other_router` também sejam incluídas. diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md index 8f3313ae9..ac0b85ab5 100644 --- a/docs/pt/docs/tutorial/body-fields.md +++ b/docs/pt/docs/tutorial/body-fields.md @@ -7,33 +7,42 @@ Da mesma forma que você pode declarar validações adicionais e metadados nos p Primeiro, você tem que importá-lo: ```Python hl_lines="4" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` -!!! warning "Aviso" - Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc). +/// warning | Aviso + +Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc). + +/// ## Declare atributos do modelo Você pode então utilizar `Field` com atributos do modelo: ```Python hl_lines="11-14" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` `Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc. -!!! note "Detalhes técnicos" - Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic. +/// note | Detalhes técnicos + +Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic. + +E `Field` do Pydantic retorna uma instância de `FieldInfo` também. + +`Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`. + +Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais. - E `Field` do Pydantic retorna uma instância de `FieldInfo` também. +/// - `Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`. +/// tip | Dica - Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais. +Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`. -!!! tip "Dica" - Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`. +/// ## Adicione informações extras diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index 0eaa9664c..ad4931b11 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -8,20 +8,27 @@ Primeiro, é claro, você pode misturar `Path`, `Query` e declarações de parâ E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +```Python hl_lines="17-19" +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../docs_src/body_multiple_params/tutorial001.py!} +``` - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +//// -!!! nota - Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão. +/// note | Nota + +Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão. + +/// ## Múltiplos parâmetros de corpo @@ -38,17 +45,21 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic). @@ -69,9 +80,11 @@ Então, ele usará o nome dos parâmetros como chaves (nome dos campos) no corpo } ``` -!!! nota - Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`. +/// note | Nota +Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`. + +/// O **FastAPI** fará a conversão automática a partir da requisição, assim esse parâmetro `item` receberá seu respectivo conteúdo e o mesmo ocorrerá com `user`. @@ -87,17 +100,21 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`: -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../docs_src/body_multiple_params/tutorial003.py!} +``` -=== "Python 3.10+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | Python 3.10+ + +```Python hl_lines="20" +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` + +//// Neste caso, o **FastAPI** esperará um corpo como: @@ -137,20 +154,27 @@ q: str | None = None Por exemplo: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="26" +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="26" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../docs_src/body_multiple_params/tutorial004.py!} +``` + +//// -=== "Python 3.8+" +/// info | Informação - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +`Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois. -!!! info "Informação" - `Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois. +/// ## Declare um único parâmetro de corpo indicando sua chave @@ -166,17 +190,21 @@ item: Item = Body(embed=True) como em: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="15" +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` + +//// - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17" +{!> ../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// Neste caso o **FastAPI** esperará um corpo como: diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index e039b09b2..bbe72a744 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -7,7 +7,7 @@ Com o **FastAPI**, você pode definir, validar, documentar e usar modelos profun Você pode definir um atributo como um subtipo. Por exemplo, uma `list` do Python: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial001.py!} +{!../../docs_src/body_nested_models/tutorial001.py!} ``` Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos elementos desta lista. @@ -21,7 +21,7 @@ Mas o Python tem uma maneira específica de declarar listas com tipos internos o Primeiramente, importe `List` do módulo `typing` que já vem por padrão no Python: ```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ### Declare a `List` com um parâmetro de tipo @@ -45,7 +45,7 @@ Portanto, em nosso exemplo, podemos fazer com que `tags` sejam especificamente u ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ## Tipo "set" @@ -59,7 +59,7 @@ Então podemos importar `Set` e declarar `tags` como um `set` de `str`s: ```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} +{!../../docs_src/body_nested_models/tutorial003.py!} ``` Com isso, mesmo que você receba uma requisição contendo dados duplicados, ela será convertida em um conjunto de itens exclusivos. @@ -83,7 +83,7 @@ Tudo isso, aninhado arbitrariamente. Por exemplo, nós podemos definir um modelo `Image`: ```Python hl_lines="9-11" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` ### Use o sub-modelo como um tipo @@ -91,7 +91,7 @@ Por exemplo, nós podemos definir um modelo `Image`: E então podemos usa-lo como o tipo de um atributo: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` Isso significa que o **FastAPI** vai esperar um corpo similar à: @@ -126,7 +126,7 @@ Para ver todas as opções possíveis, cheque a documentação para osHTTP `PUT`. + +Você pode usar `jsonable_encoder` para converter os dados de entrada em dados que podem ser armazenados como JSON (por exemplo, com um banco de dados NoSQL). Por exemplo, convertendo `datetime` em `str`. + +//// tab | Python 3.10+ + +```Python hl_lines="28-33" +{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001.py!} +``` + +//// + +`PUT` é usado para receber dados que devem substituir os dados existentes. + +### Aviso sobre a substituição + +Isso significa que, se você quiser atualizar o item `bar` usando `PUT` com um corpo contendo: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +Como ele não inclui o atributo já armazenado `"tax": 20.2`, o modelo de entrada assumiria o valor padrão de `"tax": 10.5`. + +E os dados seriam salvos com esse "novo" `tax` de `10.5`. + +## Atualizações parciais com `PATCH` + +Você também pode usar a operação HTTP `PATCH` para *atualizar* parcialmente os dados. + +Isso significa que você pode enviar apenas os dados que deseja atualizar, deixando o restante intacto. + +/// note | Nota + +`PATCH` é menos comumente usado e conhecido do que `PUT`. + +E muitas equipes usam apenas `PUT`, mesmo para atualizações parciais. + +Você é **livre** para usá-los como preferir, **FastAPI** não impõe restrições. + +Mas este guia te dá uma ideia de como eles são destinados a serem usados. + +/// + +### Usando o parâmetro `exclude_unset` do Pydantic + +Se você quiser receber atualizações parciais, é muito útil usar o parâmetro `exclude_unset` no método `.model_dump()` do modelo do Pydantic. + +Como `item.model_dump(exclude_unset=True)`. + +/// info | Informação + +No Pydantic v1, o método que era chamado `.dict()` e foi depreciado (mas ainda suportado) no Pydantic v2. Agora, deve-se usar o método `.model_dump()`. + +Os exemplos aqui usam `.dict()` para compatibilidade com o Pydantic v1, mas você deve usar `.model_dump()` a partir do Pydantic v2. + +/// + +Isso gera um `dict` com apenas os dados definidos ao criar o modelo `item`, excluindo os valores padrão. + +Então, você pode usar isso para gerar um `dict` com apenas os dados definidos (enviados na solicitação), omitindo valores padrão: + +//// tab | Python 3.10+ + +```Python hl_lines="32" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// + +### Usando o parâmetro `update` do Pydantic + +Agora, você pode criar uma cópia do modelo existente usando `.model_copy()`, e passar o parâmetro `update` com um `dict` contendo os dados para atualizar. + +/// info | Informação + +No Pydantic v1, o método era chamado `.copy()`, ele foi depreciado (mas ainda suportado) no Pydantic v2, e renomeado para `.model_copy()`. + +Os exemplos aqui usam `.copy()` para compatibilidade com o Pydantic v1, mas você deve usar `.model_copy()` com o Pydantic v2. + +/// + +Como `stored_item_model.model_copy(update=update_data)`: + +//// tab | Python 3.10+ + +```Python hl_lines="33" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// + +### Recapitulando as atualizações parciais + +Resumindo, para aplicar atualizações parciais você pode: + +* (Opcionalmente) usar `PATCH` em vez de `PUT`. +* Recuperar os dados armazenados. +* Colocar esses dados em um modelo do Pydantic. +* Gerar um `dict` sem valores padrão a partir do modelo de entrada (usando `exclude_unset`). + * Dessa forma, você pode atualizar apenas os valores definidos pelo usuário, em vez de substituir os valores já armazenados com valores padrão em seu modelo. +* Criar uma cópia do modelo armazenado, atualizando seus atributos com as atualizações parciais recebidas (usando o parâmetro `update`). +* Converter o modelo copiado em algo que possa ser armazenado no seu banco de dados (por exemplo, usando o `jsonable_encoder`). + * Isso é comparável ao uso do método `.model_dump()`, mas garante (e converte) os valores para tipos de dados que possam ser convertidos em JSON, por exemplo, `datetime` para `str`. +* Salvar os dados no seu banco de dados. +* Retornar o modelo atualizado. + +//// tab | Python 3.10+ + +```Python hl_lines="28-35" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// + +/// tip | Dica + +Você pode realmente usar essa mesma técnica com uma operação HTTP `PUT`. + +Mas o exemplo aqui usa `PATCH` porque foi criado para esses casos de uso. + +/// + +/// note | Nota + +Observe que o modelo de entrada ainda é validado. + +Portanto, se você quiser receber atualizações parciais que possam omitir todos os atributos, precisará ter um modelo com todos os atributos marcados como opcionais (com valores padrão ou `None`). + +Para distinguir os modelos com todos os valores opcionais para **atualizações** e modelos com valores obrigatórios para **criação**, você pode usar as ideias descritas em [Modelos Adicionais](extra-models.md){.internal-link target=_blank}. + +/// diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index 5901b8414..f3a1fda75 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -8,19 +8,22 @@ Sua API quase sempre irá enviar um corpo na **resposta**. Mas os clientes não Para declarar um corpo da **requisição**, você utiliza os modelos do Pydantic com todos os seus poderes e benefícios. -!!! info "Informação" - Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. +/// info | Informação - Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos. +Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. - Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição. +Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos. + +Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição. + +/// ## Importe o `BaseModel` do Pydantic Primeiro, você precisa importar `BaseModel` do `pydantic`: ```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ## Crie seu modelo de dados @@ -30,7 +33,7 @@ Então você declara seu modelo de dados como uma classe que herda `BaseModel`. Utilize os tipos Python padrão para todos os atributos: ```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` Assim como quando declaramos parâmetros de consulta, quando um atributo do modelo possui um valor padrão, ele se torna opcional. Caso contrário, se torna obrigatório. Use `None` para torná-lo opcional. @@ -60,7 +63,7 @@ Por exemplo, o modelo acima declara um JSON "`object`" (ou `dict` no Python) com Para adicionar o corpo na *função de operação de rota*, declare-o da mesma maneira que você declarou parâmetros de rota e consulta: ```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ...E declare o tipo como o modelo que você criou, `Item`. @@ -110,23 +113,26 @@ Mas você terá o mesmo suporte do editor no -!!! tip "Dica" - Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm . +/// tip | Dica + +Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm . - Melhora o suporte do editor para seus modelos Pydantic com:: +Melhora o suporte do editor para seus modelos Pydantic com:: - * completação automática - * verificação de tipos - * refatoração - * buscas - * inspeções +* completação automática +* verificação de tipos +* refatoração +* buscas +* inspeções + +/// ## Use o modelo Dentro da função, você pode acessar todos os atributos do objeto do modelo diretamente: ```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} +{!../../docs_src/body/tutorial002.py!} ``` ## Corpo da requisição + parâmetros de rota @@ -136,7 +142,7 @@ Você pode declarar parâmetros de rota e corpo da requisição ao mesmo tempo. O **FastAPI** irá reconhecer que os parâmetros da função que combinam com parâmetros de rota devem ser **retirados da rota**, e parâmetros da função que são declarados como modelos Pydantic sejam **retirados do corpo da requisição**. ```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} +{!../../docs_src/body/tutorial003.py!} ``` ## Corpo da requisição + parâmetros de rota + parâmetros de consulta @@ -146,7 +152,7 @@ Você também pode declarar parâmetros de **corpo**, **rota** e **consulta**, a O **FastAPI** irá reconhecer cada um deles e retirar a informação do local correto. ```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} +{!../../docs_src/body/tutorial004.py!} ``` Os parâmetros da função serão reconhecidos conforme abaixo: @@ -155,11 +161,14 @@ Os parâmetros da função serão reconhecidos conforme abaixo: * Se o parâmetro é de um **tipo único** (como `int`, `float`, `str`, `bool`, etc) será interpretado como um parâmetro de **consulta**. * Se o parâmetro é declarado como um **modelo Pydantic**, será interpretado como o **corpo** da requisição. -!!! note "Observação" - O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. +/// note | Observação + +O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. + +O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros. - O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros. +/// ## Sem o Pydantic -Se você não quer utilizar os modelos Pydantic, você também pode utilizar o parâmetro **Body**. Veja a documentação para [Body - Parâmetros múltiplos: Valores singulares no body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. +Se você não quer utilizar os modelos Pydantic, você também pode utilizar o parâmetro **Body**. Veja a documentação para [Body - Parâmetros múltiplos: Valores singulares no body](body-multiple-params.md#valores-singulares-no-corpo){.internal-link target=_blank}. diff --git a/docs/pt/docs/tutorial/cookie-param-models.md b/docs/pt/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..671e0d74f --- /dev/null +++ b/docs/pt/docs/tutorial/cookie-param-models.md @@ -0,0 +1,156 @@ +# Modelos de Parâmetros de Cookie + +Se você possui um grupo de **cookies** que estão relacionados, você pode criar um **modelo Pydantic** para declará-los. 🍪 + +Isso lhe permitiria **reutilizar o modelo** em **diversos lugares** e também declarar validações e metadata para todos os parâmetros de uma vez. 😎 + +/// note | Nota + +Isso é suportado desde a versão `0.115.0` do FastAPI. 🤓 + +/// + +/// tip | Dica + +Essa mesma técnica se aplica para `Query`, `Cookie`, e `Header`. 😎 + +/// + +## Cookies com Modelos Pydantic + +Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, e depois declare o parâmetro como um `Cookie`: + +//// tab | Python 3.10+ + +```Python hl_lines="9-12 16" +{!> ../../docs_src/cookie_param_models/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9-12 16" +{!> ../../docs_src/cookie_param_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10-13 17" +{!> ../../docs_src/cookie_param_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="7-10 14" +{!> ../../docs_src/cookie_param_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9-12 16" +{!> ../../docs_src/cookie_param_models/tutorial001.py!} +``` + +//// + +O **FastAPI** irá **extrair** os dados para **cada campo** dos **cookies** recebidos na requisição e lhe fornecer o modelo Pydantic que você definiu. + +## Verifique os Documentos + +Você pode ver os cookies definidos na IU dos documentos em `/docs`: + +
+ +
+ +/// info | Informação + +Tenha em mente que, como os **navegadores lidam com cookies** de maneira especial e por baixo dos panos, eles **não** permitem facilmente que o **JavaScript** lidem com eles. + +Se você for na **IU de documentos da API** em `/docs` você poderá ver a **documentação** para cookies das suas *operações de rotas*. + +Mas mesmo que você **adicionar os dados** e clicar em "Executar", pelo motivo da IU dos documentos trabalharem com **JavaScript**, os cookies não serão enviados, e você verá uma mensagem de **erro** como se você não tivesse escrito nenhum dado. + +/// + +## Proibir Cookies Adicionais + +Em alguns casos especiais (provavelmente não muito comuns), você pode querer **restringir** os cookies que você deseja receber. + +Agora a sua API possui o poder de contrar o seu próprio consentimento de cookie. 🤪🍪 + + + Você pode utilizar a configuração do modelo Pydantic para `proibir` qualquer campo `extra`. + + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../docs_src/cookie_param_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/cookie_param_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/cookie_param_models/tutorial002.py!} +``` + +//// + +Se o cliente tentar enviar alguns **cookies extras**, eles receberão um retorno de **erro**. + +Coitados dos banners de cookies com todo o seu esforço para obter o seu consentimento para a API rejeitá-lo. 🍪 + +Por exemplo, se o cliente tentar enviar um cookie `santa_tracker` com o valor de `good-list-please`, o cliente receberá uma resposta de **erro** informando que o cookie `santa_tracker` is not allowed: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## Resumo + +Você consegue utilizar **modelos Pydantic** para declarar **cookies** no **FastAPI**. 😎 diff --git a/docs/pt/docs/tutorial/cookie-params.md b/docs/pt/docs/tutorial/cookie-params.md index 1a60e3571..50bec8cf7 100644 --- a/docs/pt/docs/tutorial/cookie-params.md +++ b/docs/pt/docs/tutorial/cookie-params.md @@ -6,27 +6,130 @@ Você pode definir parâmetros de Cookie da mesma maneira que define paramêtros Primeiro importe `Cookie`: +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + ```Python hl_lines="3" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="1" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + ## Declare parâmetros de `Cookie` Então declare os paramêtros de cookie usando a mesma estrutura que em `Path` e `Query`. -O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação: +Você pode definir o valor padrão, assim como todas as validações extras ou parâmetros de anotação: + + +//// tab | Python 3.10+ ```Python hl_lines="9" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` -!!! note "Detalhes Técnicos" - `Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`. +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +/// note | Detalhes Técnicos + +`Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`. + +Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. + +/// + +/// info | Informação - Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. +Para declarar cookies, você precisa usar `Cookie`, pois caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. -!!! info "Informação" - Para declarar cookies, você precisa usar `Cookie`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md new file mode 100644 index 000000000..326101bd2 --- /dev/null +++ b/docs/pt/docs/tutorial/cors.md @@ -0,0 +1,87 @@ +# CORS (Cross-Origin Resource Sharing) + +CORS ou "Cross-Origin Resource Sharing" refere-se às situações em que um frontend rodando em um navegador possui um código JavaScript que se comunica com um backend, e o backend está em uma "origem" diferente do frontend. + +## Origem + +Uma origem é a combinação de protocolo (`http`, `https`), domínio (`myapp.com`, `localhost`, `localhost.tiangolo.com`), e porta (`80`, `443`, `8080`). + +Então, todos estes são origens diferentes: + +* `http://localhost` +* `https://localhost` +* `http://localhost:8080` + +Mesmo se todos estiverem em `localhost`, eles usam diferentes protocolos e portas, portanto, são "origens" diferentes. + +## Passos + +Então, digamos que você tenha um frontend rodando no seu navegador em `http://localhost:8080`, e seu JavaScript esteja tentando se comunicar com um backend rodando em http://localhost (como não especificamos uma porta, o navegador assumirá a porta padrão `80`). + +Portanto, o navegador irá enviar uma requisição HTTP `OPTIONS` ao backend, e se o backend enviar os cabeçalhos apropriados autorizando a comunicação a partir de uma origem diferente (`http://localhost:8080`) então o navegador deixará o JavaScript no frontend enviar sua requisição para o backend. + +Para conseguir isso, o backend deve ter uma lista de "origens permitidas". + +Neste caso, ele terá que incluir `http://localhost:8080` para o frontend funcionar corretamente. + +## Curingas + +É possível declarar uma lista com `"*"` (um "curinga") para dizer que tudo está permitido. + +Mas isso só permitirá certos tipos de comunicação, excluindo tudo que envolva credenciais: cookies, cabeçalhos de autorização como aqueles usados ​​com Bearer Tokens, etc. + +Então, para que tudo funcione corretamente, é melhor especificar explicitamente as origens permitidas. + +## Usar `CORSMiddleware` + +Você pode configurá-lo em sua aplicação **FastAPI** usando o `CORSMiddleware`. + +* Importe `CORSMiddleware`. +* Crie uma lista de origens permitidas (como strings). +* Adicione-a como um "middleware" à sua aplicação **FastAPI**. + +Você também pode especificar se o seu backend permite: + +* Credenciais (Cabeçalhos de autorização, Cookies, etc). +* Métodos HTTP específicos (`POST`, `PUT`) ou todos eles com o curinga `"*"`. +* Cabeçalhos HTTP específicos ou todos eles com o curinga `"*"`. + +```Python hl_lines="2 6-11 13-19" +{!../../docs_src/cors/tutorial001.py!} +``` + +Os parâmetros padrão usados ​​pela implementação `CORSMiddleware` são restritivos por padrão, então você precisará habilitar explicitamente as origens, métodos ou cabeçalhos específicos para que os navegadores tenham permissão para usá-los em um contexto de domínios diferentes. + +Os seguintes argumentos são suportados: + +* `allow_origins` - Uma lista de origens que devem ter permissão para fazer requisições de origem cruzada. Por exemplo, `['https://example.org', 'https://www.example.org']`. Você pode usar `['*']` para permitir qualquer origem. +* `allow_origin_regex` - Uma string regex para corresponder às origens que devem ter permissão para fazer requisições de origem cruzada. Por exemplo, `'https://.*\.example\.org'`. +* `allow_methods` - Uma lista de métodos HTTP que devem ser permitidos para requisições de origem cruzada. O padrão é `['GET']`. Você pode usar `['*']` para permitir todos os métodos padrão. +* `allow_headers` - Uma lista de cabeçalhos de solicitação HTTP que devem ter suporte para requisições de origem cruzada. O padrão é `[]`. Você pode usar `['*']` para permitir todos os cabeçalhos. Os cabeçalhos `Accept`, `Accept-Language`, `Content-Language` e `Content-Type` são sempre permitidos para requisições CORS simples. +* `allow_credentials` - Indica que os cookies devem ser suportados para requisições de origem cruzada. O padrão é `False`. Além disso, `allow_origins` não pode ser definido como `['*']` para que as credenciais sejam permitidas, as origens devem ser especificadas. +* `expose_headers` - Indica quaisquer cabeçalhos de resposta que devem ser disponibilizados ao navegador. O padrão é `[]`. +* `max_age` - Define um tempo máximo em segundos para os navegadores armazenarem em cache as respostas CORS. O padrão é `600`. + +O middleware responde a dois tipos específicos de solicitação HTTP... + +### Requisições CORS pré-voo (preflight) + +Estas são quaisquer solicitações `OPTIONS` com cabeçalhos `Origin` e `Access-Control-Request-Method`. + +Nesse caso, o middleware interceptará a solicitação recebida e responderá com cabeçalhos CORS apropriados e uma resposta `200` ou `400` para fins informativos. + +### Requisições Simples + +Qualquer solicitação com um cabeçalho `Origin`. Neste caso, o middleware passará a solicitação normalmente, mas incluirá cabeçalhos CORS apropriados na resposta. + +## Mais informações + +Para mais informações CORS, acesse Mozilla CORS documentation. + +/// note | Detalhes técnicos + +Você também pode usar `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vêm diretamente da Starlette. + +/// diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md new file mode 100644 index 000000000..fca162988 --- /dev/null +++ b/docs/pt/docs/tutorial/debugging.md @@ -0,0 +1,115 @@ +# Depuração + +Você pode conectar o depurador no seu editor, por exemplo, com o Visual Studio Code ou PyCharm. + +## Chamar `uvicorn` + +Em seu aplicativo FastAPI, importe e execute `uvicorn` diretamente: + +```Python hl_lines="1 15" +{!../../docs_src/debugging/tutorial001.py!} +``` + +### Sobre `__name__ == "__main__"` + +O objetivo principal de `__name__ == "__main__"` é ter algum código que seja executado quando seu arquivo for chamado com: + +
+ +```console +$ python myapp.py +``` + +
+ +mas não é chamado quando outro arquivo o importa, como em: + +```Python +from myapp import app +``` + +#### Mais detalhes + +Digamos que seu arquivo se chama `myapp.py`. + +Se você executá-lo com: + +
+ +```console +$ python myapp.py +``` + +
+ +então a variável interna `__name__` no seu arquivo, criada automaticamente pelo Python, terá como valor a string `"__main__"`. + +Então, a seção: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +vai executar. + +--- + +Isso não acontecerá se você importar esse módulo (arquivo). + +Então, se você tiver outro arquivo `importer.py` com: + +```Python +from myapp import app + +# Mais um pouco de código +``` + +nesse caso, a variável criada automaticamente dentro de `myapp.py` não terá a variável `__name__` com o valor `"__main__"`. + +Então, a linha: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +não será executada. + +/// info | Informação + +Para mais informações, consulte a documentação oficial do Python. + +/// + +## Execute seu código com seu depurador + +Como você está executando o servidor Uvicorn diretamente do seu código, você pode chamar seu programa Python (seu aplicativo FastAPI) diretamente do depurador. + +--- + +Por exemplo, no Visual Studio Code, você pode: + +* Ir para o painel "Debug". +* "Add configuration...". +* Selecionar "Python" +* Executar o depurador com a opção "`Python: Current File (Integrated Terminal)`". + +Em seguida, ele iniciará o servidor com seu código **FastAPI**, parará em seus pontos de interrupção, etc. + +Veja como pode parecer: + + + +--- + +Se você usar o Pycharm, você pode: + +* Abrir o menu "Executar". +* Selecionar a opção "Depurar...". +* Então um menu de contexto aparece. +* Selecionar o arquivo para depurar (neste caso, `main.py`). + +Em seguida, ele iniciará o servidor com seu código **FastAPI**, parará em seus pontos de interrupção, etc. + +Veja como pode parecer: + + diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..fcf71d08c --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,638 @@ +# Classes como Dependências + +Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos melhorar o exemplo anterior. + +## `dict` do exemplo anterior + +No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"): + +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// + +Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*. + +E sabemos que editores de texto não têm como oferecer muitas funcionalidades (como sugestões automáticas) para objetos do tipo `dict`, por que não há como eles saberem o tipo das chaves e dos valores. + +Podemos fazer melhor... + +## O que caracteriza uma dependência + +Até agora você apenas viu dependências declaradas como funções. + +Mas essa não é a única forma de declarar dependências (mesmo que provavelmente seja a mais comum). + +O fator principal para uma dependência é que ela deve ser "chamável" + +Um objeto "chamável" em Python é qualquer coisa que o Python possa "chamar" como uma função + +Então se você tiver um objeto `alguma_coisa` (que pode *não* ser uma função) que você possa "chamar" (executá-lo) dessa maneira: + +```Python +something() +``` + +ou + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +Então esse objeto é um "chamável". + +## Classes como dependências + +Você deve ter percebido que para criar um instância de uma classe em Python, a mesma sintaxe é utilizada. + +Por exemplo: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +Nesse caso, `fluffy` é uma instância da classe `Cat`. + +E para criar `fluffy`, você está "chamando" `Cat`. + +Então, uma classe Python também é "chamável". + +Então, no **FastAPI**, você pode utilizar uma classe Python como uma dependência. + +O que o FastAPI realmente verifica, é se a dependência é algo chamável (função, classe, ou outra coisa) e os parâmetros que foram definidos. + +Se você passar algo "chamável" como uma dependência do **FastAPI**, o framework irá analisar os parâmetros desse "chamável" e processá-los da mesma forma que os parâmetros de uma *função de operação de rota*. Incluindo as sub-dependências. + +Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro. Da mesma forma que uma *função de operação de rota* sem parâmetros. + +Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`: + +//// tab | Python 3.10+ + +```Python hl_lines="11-15" +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11-15" +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12-16" +{!> ../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="9-13" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11-15" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` + +//// + +Observe o método `__init__` usado para criar uma instância da classe: + +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="13" +{!> ../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` + +//// + +...ele possui os mesmos parâmetros que nosso `common_parameters` anterior: + +//// tab | Python 3.10+ + +```Python hl_lines="8" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="6" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// + +Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência. + +Em ambos os casos teremos: + +* Um parâmetro de consulta `q` opcional do tipo `str`. +* Um parâmetro de consulta `skip` do tipo `int`, com valor padrão `0`. +* Um parâmetro de consulta `limit` do tipo `int`, com valor padrão `100`. + +Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc nos dois casos. + +## Utilizando + +Agora você pode declarar sua dependência utilizando essa classe. + +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` + +//// + +O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função. + +## Anotações de Tipo vs `Depends` + +Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +O último `CommonQueryParams`, em: + +```Python +... Depends(CommonQueryParams) +``` + +...é o que o **FastAPI** irá realmente usar para saber qual é a dependência. + +É a partir dele que o FastAPI irá extrair os parâmetros passados e será o que o FastAPI irá realmente chamar. + +--- + +Nesse caso, o primeiro `CommonQueryParams`, em: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams ... +``` + +//// + +...não tem nenhum signficado especial para o **FastAPI**. O FastAPI não irá utilizá-lo para conversão dos dados, validação, etc (já que ele utiliza `Depends(CommonQueryParams)` para isso). + +Na verdade você poderia escrever apenas: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// + +...como em: + +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../docs_src/dependencies/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial003.py!} +``` + +//// + +Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`. + + + +## Pegando um Atalho + +Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +O **FastAPI** nos fornece um atalho para esses casos, onde a dependência é *especificamente* uma classe que o **FastAPI** irá "chamar" para criar uma instância da própria classe. + +Para esses casos específicos, você pode fazer o seguinte: + +Em vez de escrever: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +...escreva: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// + +Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` sem nenhum parâmetro, em vez de ter que escrever a classe *novamente* dentro de `Depends(CommonQueryParams)`. + +O mesmo exemplo ficaria então dessa forma: + +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../docs_src/dependencies/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial004.py!} +``` + +//// + +...e o **FastAPI** saberá o que fazer. + +/// tip | Dica + +Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso. + +É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código. + +/// diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..89c34855e --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,183 @@ +# Dependências em decoradores de operações de rota + +Em alguns casos você não precisa necessariamente retornar o valor de uma dependência dentro de uma *função de operação de rota*. + +Ou a dependência não retorna nenhum valor. + +Mas você ainda precisa que ela seja executada/resolvida. + +Para esses casos, em vez de declarar um parâmetro em uma *função de operação de rota* com `Depends`, você pode adicionar um argumento `dependencies` do tipo `list` ao decorador da operação de rota. + +## Adicionando `dependencies` ao decorador da operação de rota + +O *decorador da operação de rota* recebe um argumento opcional `dependencies`. + +Ele deve ser uma lista de `Depends()`: + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// + +Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*. + +/// tip | Dica + +Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros. + +Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas. + +Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário. + +/// + +/// info | Informação + +Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`. + +Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}. + +/// + +## Erros das dependências e valores de retorno + +Você pode utilizar as mesmas *funções* de dependências que você usaria normalmente. + +### Requisitos de Dependências + +Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências: + +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7 12" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="6 11" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// + +### Levantando exceções + +Essas dependências podem levantar exceções, da mesma forma que dependências comuns: + +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="8 13" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// + +### Valores de retorno + +E elas também podem ou não retornar valores, eles não serão utilizados. + +Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada: + +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | Dica + + + +/// + + Utilize a versão com `Annotated` se possível + +```Python hl_lines="9 14" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// + +## Dependências para um grupo de *operações de rota* + +Mais a frente, quando você ler sobre como estruturar aplicações maiores ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possivelmente com múltiplos arquivos, você aprenderá a declarar um único parâmetro `dependencies` para um grupo de *operações de rota*. + +## Dependências globais + +No próximo passo veremos como adicionar dependências para uma aplicação `FastAPI` inteira, para que ela seja aplicada em toda *operação de rota*. diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..90c1e02e0 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,425 @@ +# Dependências com yield + +O FastAPI possui suporte para dependências que realizam alguns passos extras ao finalizar. + +Para fazer isso, utilize `yield` em vez de `return`, e escreva os passos extras (código) depois. + +/// tip | Dica + +Garanta que `yield` é utilizado apenas uma vez. + +/// + +/// note | Detalhes Técnicos + +Qualquer função que possa ser utilizada com: + +* `@contextlib.contextmanager` ou +* `@contextlib.asynccontextmanager` + +pode ser utilizada como uma dependência do **FastAPI**. + +Na realidade, o FastAPI utiliza esses dois decoradores internamente. + +/// + +## Uma dependência de banco de dados com `yield` + +Por exemplo, você poderia utilizar isso para criar uma sessão do banco de dados, e fechá-la após terminar sua operação. + +Apenas o código anterior a declaração com `yield` e o código contendo essa declaração são executados antes de criar uma resposta. + +```Python hl_lines="2-4" +{!../../docs_src/dependencies/tutorial007.py!} +``` + +O valor gerado (yielded) é o que é injetado nas *operações de rota* e outras dependências. + +```Python hl_lines="4" +{!../../docs_src/dependencies/tutorial007.py!} +``` + +O código após o `yield` é executado após a resposta ser entregue: + +```Python hl_lines="5-6" +{!../../docs_src/dependencies/tutorial007.py!} +``` + +/// tip | Dica + +Você pode usar funções assíncronas (`async`) ou funções comuns. + +O **FastAPI** saberá o que fazer com cada uma, da mesma forma que as dependências comuns. + +/// + +## Uma dependência com `yield` e `try` + +Se você utilizar um bloco `try` em uma dependência com `yield`, você irá capturar qualquer exceção que for lançada enquanto a dependência é utilizada. + +Por exemplo, se algum código em um certo momento no meio da operação, em outra dependência ou em uma *operação de rota*, fizer um "rollback" de uma transação de banco de dados ou causar qualquer outro erro, você irá capturar a exceção em sua dependência. + +Então, você pode procurar por essa exceção específica dentro da dependência com `except AlgumaExcecao`. + +Da mesma forma, você pode utilizar `finally` para garantir que os passos de saída são executados, com ou sem exceções. + +```python hl_lines="3 5" +{!../../docs_src/dependencies/tutorial007.py!} +``` + +## Subdependências com `yield` + +Você pode ter subdependências e "árvores" de subdependências de qualquer tamanho e forma, e qualquer uma ou todas elas podem utilizar `yield`. + +O **FastAPI** garantirá que o "código de saída" em cada dependência com `yield` é executado na ordem correta. + +Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` depender de `dependency_a`: + +//// tab | python 3.9+ + +```python hl_lines="6 14 22" +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// + +//// tab | python 3.8+ + +```python hl_lines="5 13 21" +{!> ../../docs_src/dependencies/tutorial008_an.py!} +``` + +//// + +//// tab | python 3.8+ non-annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```python hl_lines="4 12 20" +{!> ../../docs_src/dependencies/tutorial008.py!} +``` + +//// + +E todas elas podem utilizar `yield`. + +Neste caso, `dependency_c` precisa que o valor de `dependency_b` (nomeada de `dep_b` aqui) continue disponível para executar seu código de saída. + +E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeada de `dep_a`) continue disponível para executar seu código de saída. + +//// tab | python 3.9+ + +```python hl_lines="18-19 26-27" +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// + +//// tab | python 3.8+ + +```python hl_lines="17-18 25-26" +{!> ../../docs_src/dependencies/tutorial008_an.py!} +``` + +//// + +//// tab | python 3.8+ non-annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```python hl_lines="16-17 24-25" +{!> ../../docs_src/dependencies/tutorial008.py!} +``` + +//// + +Da mesma forma, você pode ter algumas dependências com `yield` e outras com `return` e ter uma relação de dependência entre algumas dos dois tipos. + +E você poderia ter uma única dependência que precisa de diversas outras dependências com `yield`, etc. + +Você pode ter qualquer combinação de dependências que você quiser. + +O **FastAPI** se encarrega de executá-las na ordem certa. + +/// note | Detalhes Técnicos + +Tudo isso funciona graças aos gerenciadores de contexto do Python. + +O **FastAPI** utiliza eles internamente para alcançar isso. + +/// + +## Dependências com `yield` e `httpexception` + +Você viu que dependências podem ser utilizadas com `yield` e podem incluir blocos `try` para capturar exceções. + +Da mesma forma, você pode lançar uma `httpexception` ou algo parecido no código de saída, após o `yield` + +/// tip | Dica + +Essa é uma técnica relativamente avançada, e na maioria dos casos você não precisa dela totalmente, já que você pode lançar exceções (incluindo `httpexception`) dentro do resto do código da sua aplicação, por exemplo, em uma *função de operação de rota*. + +Mas ela existe para ser utilizada caso você precise. 🤓 + +/// + +//// tab | python 3.9+ + +```python hl_lines="18-22 31" +{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} +``` + +//// + +//// tab | python 3.8+ + +```python hl_lines="17-21 30" +{!> ../../docs_src/dependencies/tutorial008b_an.py!} +``` + +//// + +//// tab | python 3.8+ non-annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```python hl_lines="16-20 29" +{!> ../../docs_src/dependencies/tutorial008b.py!} +``` + +//// + +Uma alternativa que você pode utilizar para capturar exceções (e possivelmente lançar outra HTTPException) é criar um [Manipulador de Exceções Customizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}. + +## Dependências com `yield` e `except` + +Se você capturar uma exceção com `except` em uma dependência que utilize `yield` e ela não for levantada novamente (ou uma nova exceção for levantada), o FastAPI não será capaz de identifcar que houve uma exceção, da mesma forma que aconteceria com Python puro: + +//// tab | Python 3.9+ + +```Python hl_lines="15-16" +{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="14-15" +{!> ../../docs_src/dependencies/tutorial008c_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-annotated + +/// tip | dica + +utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="13-14" +{!> ../../docs_src/dependencies/tutorial008c.py!} +``` + +//// + +Neste caso, o cliente irá ver uma resposta *HTTP 500 Internal Server Error* como deveria acontecer, já que não estamos levantando nenhuma `HTTPException` ou coisa parecida, mas o servidor **não terá nenhum log** ou qualquer outra indicação de qual foi o erro. 😱 + +### Sempre levante (`raise`) exceções em Dependências com `yield` e `except` + +Se você capturar uma exceção em uma dependência com `yield`, a menos que você esteja levantando outra `HTTPException` ou coisa parecida, você deveria relançar a exceção original. + +Você pode relançar a mesma exceção utilizando `raise`: + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial008d_an.py!} +``` + +//// + +//// tab | python 3.8+ non-annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="15" +{!> ../../docs_src/dependencies/tutorial008d.py!} +``` + +//// + +Agora o cliente irá receber a mesma resposta *HTTP 500 Internal Server Error*, mas o servidor terá nosso `InternalError` personalizado nos logs. 😎 + +## Execução de dependências com `yield` + +A sequência de execução é mais ou menos como esse diagrama. O tempo passa do topo para baixo. E cada coluna é uma das partes interagindo ou executando código. + +```mermaid +sequenceDiagram + +participant client as Cliente +participant handler as Manipulador de exceções +participant dep as Dep com yield +participant operation as Operação de Rota +participant tasks as Tarefas de Background + + Note over client,operation: pode lançar exceções, incluindo HTTPException + client ->> dep: Iniciar requisição + Note over dep: Executar código até o yield + opt lançar Exceção + dep -->> handler: lançar Exceção + handler -->> client: resposta de erro HTTP + end + dep ->> operation: Executar dependência, e.g. sessão de BD + opt raise + operation -->> dep: Lançar exceção (e.g. HTTPException) + opt handle + dep -->> dep: Pode capturar exceções, lançar uma nova HTTPException, lançar outras exceções + end + handler -->> client: resposta de erro HTTP + end + + operation ->> client: Retornar resposta ao cliente + Note over client,operation: Resposta já foi enviada, e não pode ser modificada + opt Tarefas + operation -->> tasks: Enviar tarefas de background + end + opt Lançar outra exceção + tasks -->> tasks: Manipula exceções no código da tarefa de background + end +``` + +/// info | Informação + +Apenas **uma resposta** será enviada para o cliente. Ela pode ser uma das respostas de erro, ou então a resposta da *operação de rota*. + +Após uma dessas respostas ser enviada, nenhuma outra resposta pode ser enviada + +/// + +/// tip | Dica + +Esse diagrama mostra `HttpException`, mas você pode levantar qualquer outra exceção que você capture em uma dependência com `yield` ou um [Manipulador de exceções personalizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}. + +Se você lançar qualquer exceção, ela será passada para as dependências com yield, inlcuindo a `HTTPException`. Na maioria dos casos você vai querer relançar essa mesma exceção ou uma nova a partir da dependência com `yield` para garantir que ela seja tratada adequadamente. + +/// + +## Dependências com `yield`, `HTTPException`, `except` e Tarefas de Background + +/// warning | Aviso + +Você provavelmente não precisa desses detalhes técnicos, você pode pular essa seção e continuar na próxima seção abaixo. + +Esses detalhes são úteis principalmente se você estiver usando uma versão do FastAPI anterior à 0.106.0 e utilizando recursos de dependências com `yield` em tarefas de background. + +/// + +### Dependências com `yield` e `except`, Detalhes Técnicos + +Antes do FastAPI 0.110.0, se você utilizasse uma dependência com `yield`, e então capturasse uma dependência com `except` nessa dependência, caso a exceção não fosse relançada, ela era automaticamente lançada para qualquer manipulador de exceções ou o manipulador de erros interno do servidor. + +Isso foi modificado na versão 0.110.0 para consertar o consumo de memória não controlado das exceções relançadas automaticamente sem um manipulador (erros internos do servidor), e para manter o comportamento consistente com o código Python tradicional. + +### Tarefas de Background e Dependências com `yield`, Detalhes Técnicos + +Antes do FastAPI 0.106.0, levantar exceções após um `yield` não era possível, o código de saída nas dependências com `yield` era executado *após* a resposta ser enviada, então os [Manipuladores de Exceções](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank} já teriam executado. + +Isso foi implementado dessa forma principalmente para permitir que os mesmos objetos fornecidos ("yielded") pelas dependências dentro de tarefas de background fossem reutilizados, por que o código de saída era executado antes das tarefas de background serem finalizadas. + +Ainda assim, como isso exigiria esperar que a resposta navegasse pela rede enquanto mantia ativo um recurso desnecessário na dependência com yield (por exemplo, uma conexão com banco de dados), isso mudou na versão 0.106.0 do FastAPI. + +/// tip | Dica + +Adicionalmente, uma tarefa de background é, normalmente, um conjunto de lógicas independentes que devem ser manipuladas separadamente, com seus próprios recursos (e.g. sua própria conexão com banco de dados). + +Então, dessa forma você provavelmente terá um código mais limpo. + +/// + +Se você costumava depender desse comportamento, agora você precisa criar os recursos para uma tarefa de background dentro dela mesma, e usar internamente apenas dados que não dependam de recursos de dependências com `yield`. + +Por exemplo, em vez de utilizar a mesma sessão do banco de dados, você criaria uma nova sessão dentro da tarefa de background, e você obteria os objetos do banco de dados utilizando essa nova sessão. E então, em vez de passar o objeto obtido do banco de dados como um parâmetro para a função da tarefa de background, você passaria o ID desse objeto e buscaria ele novamente dentro da função da tarefa de background. + +## Gerenciadores de contexto + +### O que são gerenciadores de contexto + +"Gerenciadores de Contexto" são qualquer um dos objetos Python que podem ser utilizados com a declaração `with`. + +Por exemplo, você pode utilizar `with` para ler um arquivo: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Por baixo dos panos, o código `open("./somefile.txt")` cria um objeto que é chamado de "Gerenciador de Contexto". + +Quando o bloco `with` finaliza, ele se certifica de fechar o arquivo, mesmo que tenha ocorrido alguma exceção. + +Quando você cria uma dependência com `yield`, o **FastAPI** irá criar um gerenciador de contexto internamente para ela, e combiná-lo com algumas outras ferramentas relacionadas. + +### Utilizando gerenciadores de contexto em dependências com `yield` + +/// warning | Aviso + +Isso é uma ideia mais ou menos "avançada". + +Se você está apenas iniciando com o **FastAPI** você pode querer pular isso por enquanto. + +/// + +Em python, você pode criar Gerenciadores de Contexto ao criar uma classe com dois métodos: `__enter__()` e `__exit__()`. + +Você também pode usá-los dentro de dependências com `yield` do **FastAPI** ao utilizar `with` ou `async with` dentro da função da dependência: + +```Python hl_lines="1-9 13" +{!../../docs_src/dependencies/tutorial010.py!} +``` + +/// tip | Dica + +Outra forma de criar um gerenciador de contexto é utilizando: + +* `@contextlib.contextmanager` ou + +* `@contextlib.asynccontextmanager` + +Para decorar uma função com um único `yield`. + +Isso é o que o **FastAPI** usa internamente para dependências com `yield`. + +Mas você não precisa usar esses decoradores para as dependências do FastAPI (e você não deveria). + +O FastAPI irá fazer isso para você internamente. + +/// diff --git a/docs/pt/docs/tutorial/dependencies/global-dependencies.md b/docs/pt/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 000000000..b0723d224 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,43 @@ +# Dependências Globais + +Para alguns tipos de aplicação específicos você pode querer adicionar dependências para toda a aplicação. + +De forma semelhante a [adicionar dependências (`dependencies`) em *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, você pode adicioná-las à aplicação `FastAPI`. + +Nesse caso, elas serão aplicadas a todas as *operações de rota* da aplicação: + +//// tab | Python 3.9+ + +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial012_an.py!} +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="15" +{!> ../../docs_src/dependencies/tutorial012.py!} +``` + +//// + +E todos os conceitos apresentados na sessão sobre [adicionar dependências em *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} ainda se aplicam, mas nesse caso, para todas as *operações de rota* da aplicação. + +## Dependências para conjuntos de *operações de rota* + +Mais para a frente, quando você ler sobre como estruturar aplicações maiores ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possivelmente com múltiplos arquivos, você irá aprender a declarar um único parâmetro `dependencies` para um conjunto de *operações de rota*. diff --git a/docs/pt/docs/tutorial/dependencies/index.md b/docs/pt/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..0f411ff1e --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/index.md @@ -0,0 +1,422 @@ +# Dependências + +O **FastAPI** possui um poderoso, mas intuitivo sistema de **Injeção de Dependência**. + +Esse sistema foi pensado para ser fácil de usar, e permitir que qualquer desenvolvedor possa integrar facilmente outros componentes ao **FastAPI**. + +## O que é "Injeção de Dependência" + +**"Injeção de Dependência"** no mundo da programação significa, que existe uma maneira de declarar no seu código (nesse caso, suas *funções de operação de rota*) para declarar as coisas que ele precisa para funcionar e que serão utilizadas: "dependências". + +Então, esse sistema (nesse caso o **FastAPI**) se encarrega de fazer o que for preciso para fornecer essas dependências para o código ("injetando" as dependências). + +Isso é bastante útil quando você precisa: + +* Definir uma lógica compartilhada (mesmo formato de código repetidamente). +* Compartilhar conexões com banco de dados. +* Aplicar regras de segurança, autenticação, papéis de usuários, etc. +* E muitas outras coisas... + +Tudo isso, enquanto minimizamos a repetição de código. + +## Primeiros passos + +Vamos ver um exemplo simples. Tão simples que não será muito útil, por enquanto. + +Mas dessa forma podemos focar em como o sistema de **Injeção de Dependência** funciona. + +### Criando uma dependência, ou "injetável" + +Primeiro vamos focar na dependência. + +Ela é apenas uma função que pode receber os mesmos parâmetros de uma *função de operação de rota*: + +//// tab | Python 3.10+ + +```Python hl_lines="8-9" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9-12" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="6-7" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="8-11" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// + +E pronto. + +**2 linhas**. + +E com a mesma forma e estrutura de todas as suas *funções de operação de rota*. + +Você pode pensar nela como uma *função de operação de rota* sem o "decorador" (sem a linha `@app.get("/some-path")`). + +E com qualquer retorno que você desejar. + +Neste caso, a dependência espera por: + +* Um parâmetro de consulta opcional `q` do tipo `str`. +* Um parâmetro de consulta opcional `skip` do tipo `int`, e igual a `0` por padrão. +* Um parâmetro de consulta opcional `limit` do tipo `int`, e igual a `100` por padrão. + +E então retorna um `dict` contendo esses valores. + +/// info | Informação + +FastAPI passou a suportar a notação `Annotated` (e começou a recomendá-la) na versão 0.95.0. + +Se você utiliza uma versão anterior, ocorrerão erros ao tentar utilizar `Annotated`. + +Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#atualizando-as-versoes-do-fastapi){.internal-link target=_blank} para pelo menos 0.95.1 antes de usar `Annotated`. + +/// + +### Importando `Depends` + +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="1" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// + +### Declarando a dependência, no "dependente" + +Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua *função de operação de rota*, utilize `Depends` com um novo parâmetro: + +//// tab | Python 3.10+ + +```Python hl_lines="13 18" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="15 20" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="16 21" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11 16" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="15 20" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// + +Ainda que `Depends` seja utilizado nos parâmetros da função da mesma forma que `Body`, `Query`, etc, `Depends` funciona de uma forma um pouco diferente. + +Você fornece um único parâmetro para `Depends`. + +Esse parâmetro deve ser algo como uma função. + +Você **não chama a função** diretamente (não adicione os parênteses no final), apenas a passe como parâmetro de `Depends()`. + +E essa função vai receber os parâmetros da mesma forma que uma *função de operação de rota*. + +/// tip | Dica + +Você verá quais outras "coisas", além de funções, podem ser usadas como dependências no próximo capítulo. + +/// + +Sempre que uma nova requisição for realizada, o **FastAPI** se encarrega de: + +* Chamar sua dependência ("injetável") com os parâmetros corretos. +* Obter o resultado da função. +* Atribuir esse resultado para o parâmetro em sua *função de operação de rota*. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +Assim, você escreve um código compartilhado apenas uma vez e o **FastAPI** se encarrega de chamá-lo em suas *operações de rota*. + +/// check | Checando + +Perceba que você não precisa criar uma classe especial e enviar a dependência para algum outro lugar em que o **FastAPI** a "registre" ou realize qualquer operação similar. + +Você apenas envia para `Depends` e o **FastAPI** sabe como fazer o resto. + +/// + +## Compartilhando dependências `Annotated` + +Nos exemplos acima, você pode ver que existe uma pequena **duplicação de código**. + +Quando você precisa utilizar a dependência `common_parameters()`, você precisa escrever o parâmetro inteiro com uma anotação de tipo e `Depends()`: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` em uma variável e utilizá-la em múltiplos locais: + +//// tab | Python 3.10+ + +```Python hl_lines="12 16 21" +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="14 18 23" +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="15 19 24" +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} +``` + +//// + +/// tip | Dica + +Isso é apenas Python padrão, essa funcionalidade é chamada de "type alias", e na verdade não é específica ao **FastAPI**. + +Mas como o **FastAPI** se baseia em convenções do Python, incluindo `Annotated`, você pode incluir esse truque no seu código. 😎 + +/// + +As dependências continuarão funcionando como esperado, e a **melhor parte** é que a **informação sobre o tipo é preservada**, o que signfica que seu editor de texto ainda irá incluir **preenchimento automático**, **visualização de erros**, etc. O mesmo vale para ferramentas como `mypy`. + +Isso é especialmente útil para uma **base de código grande** onde **as mesmas dependências** são utilizadas repetidamente em **muitas *operações de rota***. + +## `Async` ou não, eis a questão + +Como as dependências também serão chamadas pelo **FastAPI** (da mesma forma que *funções de operação de rota*), as mesmas regras se aplicam ao definir suas funções. + +Você pode utilizar `async def` ou apenas `def`. + +E você pode declarar dependências utilizando `async def` dentro de *funções de operação de rota* definidas com `def`, ou declarar dependências com `def` e utilizar dentro de *funções de operação de rota* definidas com `async def`, etc. + +Não faz diferença. O **FastAPI** sabe o que fazer. + +/// note | Nota + +Caso você não conheça, veja em [Async: *"Com Pressa?"*](../../async.md#com-pressa){.internal-link target=_blank} a sessão acerca de `async` e `await` na documentação. + +/// + +## Integrando com OpenAPI + +Todas as declarações de requisições, validações e requisitos para suas dependências (e sub-dependências) serão integradas em um mesmo esquema OpenAPI. + +Então, a documentação interativa também terá toda a informação sobre essas dependências: + + + +## Caso de Uso Simples + +Se você parar para ver, *funções de operação de rota* são declaradas para serem usadas sempre que uma *rota* e uma *operação* se encaixam, e então o **FastAPI** se encarrega de chamar a função correspondente com os argumentos corretos, extraindo os dados da requisição. + +Na verdade, todos (ou a maioria) dos frameworks web funcionam da mesma forma. + +Você nunca chama essas funções diretamente. Elas são chamadas pelo framework utilizado (nesse caso, **FastAPI**). + +Com o Sistema de Injeção de Dependência, você também pode informar ao **FastAPI** que sua *função de operação de rota* também "depende" em algo a mais que deve ser executado antes de sua *função de operação de rota*, e o **FastAPI** se encarrega de executar e "injetar" os resultados. + +Outros termos comuns para essa mesma ideia de "injeção de dependência" são: + +* recursos +* provedores +* serviços +* injetáveis +* componentes + +## Plug-ins em **FastAPI** + +Integrações e "plug-ins" podem ser construídos com o sistema de **Injeção de Dependência**. Mas na verdade, **não há necessidade de criar "plug-ins"**, já que utilizando dependências é possível declarar um número infinito de integrações e interações que se tornam disponíveis para as suas *funções de operação de rota*. + +E as dependências pode ser criadas de uma forma bastante simples e intuitiva que permite que você importe apenas os pacotes Python que forem necessários, e integrá-los com as funções de sua API em algumas linhas de código, *literalmente*. + +Você verá exemplos disso nos próximos capítulos, acerca de bancos de dados relacionais e NoSQL, segurança, etc. + +## Compatibilidade do **FastAPI** + +A simplicidade do sistema de injeção de dependência do **FastAPI** faz ele compatível com: + +* todos os bancos de dados relacionais +* bancos de dados NoSQL +* pacotes externos +* APIs externas +* sistemas de autenticação e autorização +* istemas de monitoramento de uso para APIs +* sistemas de injeção de dados de resposta +* etc. + +## Simples e Poderoso + +Mesmo que o sistema hierárquico de injeção de dependência seja simples de definir e utilizar, ele ainda é bastante poderoso. + +Você pode definir dependências que por sua vez definem suas próprias dependências. + +No fim, uma árvore hierárquica de dependências é criadas, e o sistema de **Injeção de Dependência** toma conta de resolver todas essas dependências (e as sub-dependências delas) para você, e provê (injeta) os resultados em cada passo. + +Por exemplo, vamos supor que você possua 4 endpoints na sua API (*operações de rota*): + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +Você poderia adicionar diferentes requisitos de permissão para cada um deles utilizando apenas dependências e sub-dependências: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Integração com **OpenAPI** + +Todas essas dependências, ao declarar os requisitos para suas *operações de rota*, também adicionam parâmetros, validações, etc. + +O **FastAPI** se encarrega de adicionar tudo isso ao esquema OpenAPI, para que seja mostrado nos sistemas de documentação interativa. diff --git a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..4c0f42dbb --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,255 @@ +# Subdependências + +Você pode criar dependências que possuem **subdependências**. + +Elas podem ter o nível de **profundidade** que você achar necessário. + +O **FastAPI** se encarrega de resolver essas dependências. + +## Primeira dependência "injetável" + +Você pode criar uma primeira dependência (injetável) dessa forma: + +//// tab | Python 3.10+ + +```Python hl_lines="8-9" +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-9" +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9-10" +{!> ../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="6-7" +{!> ../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="8-9" +{!> ../../docs_src/dependencies/tutorial005.py!} +``` + +//// + +Esse código declara um parâmetro de consulta opcional, `q`, com o tipo `str`, e então retorna esse parâmetro. + +Isso é bastante simples (e não muito útil), mas irá nos ajudar a focar em como as subdependências funcionam. + +## Segunda dependência, "injetável" e "dependente" + +Então, você pode criar uma outra função para uma dependência (um "injetável") que ao mesmo tempo declara sua própria dependência (o que faz dela um "dependente" também): + +//// tab | Python 3.10+ + +```Python hl_lines="13" +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11" +{!> ../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="13" +{!> ../../docs_src/dependencies/tutorial005.py!} +``` + +//// + +Vamos focar nos parâmetros declarados: + +* Mesmo que essa função seja uma dependência ("injetável") por si mesma, ela também declara uma outra dependência (ela "depende" de outra coisa). + * Ela depende do `query_extractor`, e atribui o valor retornado pela função ao parâmetro `q`. +* Ela também declara um cookie opcional `last_query`, do tipo `str`. + * Se o usuário não passou nenhuma consulta `q`, a última consulta é utilizada, que foi salva em um cookie anteriormente. + +## Utilizando a dependência + +Então podemos utilizar a dependência com: + +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="22" +{!> ../../docs_src/dependencies/tutorial005.py!} +``` + +//// + +/// info | Informação + +Perceba que nós estamos declarando apenas uma dependência na *função de operação de rota*, em `query_or_cookie_extractor`. + +Mas o **FastAPI** saberá que precisa solucionar `query_extractor` primeiro, para passar o resultado para `query_or_cookie_extractor` enquanto chama a função. + +/// + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Utilizando a mesma dependência múltiplas vezes + +Se uma de suas dependências é declarada várias vezes para a mesma *operação de rota*, por exemplo, múltiplas dependências com uma mesma subdependência, o **FastAPI** irá chamar essa subdependência uma única vez para cada requisição. + +E o valor retornado é salvo em um "cache" e repassado para todos os "dependentes" que precisam dele em uma requisição específica, em vez de chamar a dependência múltiplas vezes para uma mesma requisição. + +Em um cenário avançado onde você precise que a dependência seja calculada em cada passo (possivelmente várias vezes) de uma requisição em vez de utilizar o valor em "cache", você pode definir o parâmetro `use_cache=False` em `Depends`: + +//// tab | Python 3.8+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// + +## Recapitulando + +Com exceção de todas as palavras complicadas usadas aqui, o sistema de **Injeção de Dependência** é bastante simples. + +Consiste apenas de funções que parecem idênticas a *funções de operação de rota*. + +Mas ainda assim, é bastante poderoso, e permite que você declare grafos (árvores) de dependências com uma profundidade arbitrária. + +/// tip | Dica + +Tudo isso pode não parecer muito útil com esses exemplos. + +Mas você verá o quão útil isso é nos capítulos sobre **segurança**. + +E você também verá a quantidade de código que você não precisara escrever. + +/// diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md index b9bfbf63b..d89c71fc8 100644 --- a/docs/pt/docs/tutorial/encoder.md +++ b/docs/pt/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ Você pode usar a função `jsonable_encoder` para resolver isso. A função recebe um objeto, como um modelo Pydantic e retorna uma versão compatível com JSON: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../docs_src/encoder/tutorial001.py!} +``` + +//// Neste exemplo, ele converteria o modelo Pydantic em um `dict`, e o `datetime` em um `str`. @@ -38,5 +42,8 @@ O resultado de chamar a função é algo que pode ser codificado com o padrão d A função não retorna um grande `str` contendo os dados no formato JSON (como uma string). Mas sim, retorna uma estrutura de dados padrão do Python (por exemplo, um `dict`) com valores e subvalores compatíveis com JSON. -!!! nota - `jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários. +/// note | Nota + +`jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários. + +/// diff --git a/docs/pt/docs/tutorial/extra-data-types.md b/docs/pt/docs/tutorial/extra-data-types.md index 5d50d8942..78f7ac694 100644 --- a/docs/pt/docs/tutorial/extra-data-types.md +++ b/docs/pt/docs/tutorial/extra-data-types.md @@ -56,11 +56,11 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: Aqui está um exemplo de *operação de rota* com parâmetros utilizando-se de alguns dos tipos acima. ```Python hl_lines="1 3 12-16" -{!../../../docs_src/extra_data_types/tutorial001.py!} +{!../../docs_src/extra_data_types/tutorial001.py!} ``` Note que os parâmetros dentro da função tem seu tipo de dados natural, e você pode, por exemplo, realizar manipulações normais de data, como: ```Python hl_lines="18-19" -{!../../../docs_src/extra_data_types/tutorial001.py!} +{!../../docs_src/extra_data_types/tutorial001.py!} ``` diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md index 3b1f6ee54..03227f2bb 100644 --- a/docs/pt/docs/tutorial/extra-models.md +++ b/docs/pt/docs/tutorial/extra-models.md @@ -8,26 +8,33 @@ Isso é especialmente o caso para modelos de usuários, porque: * O **modelo de saída** não deve ter uma senha. * O **modelo de banco de dados** provavelmente precisaria ter uma senha criptografada. -!!! danger - Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois. +/// danger - Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois. + +Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. + +/// ## Múltiplos modelos Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos de senha e os lugares onde são usados: -=== "Python 3.8 and above" +//// tab | Python 3.8 and above - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../docs_src/extra_models/tutorial001.py!} +``` -=== "Python 3.10 and above" +//// - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// tab | Python 3.10 and above + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// ### Sobre `**user_in.dict()` @@ -139,8 +146,11 @@ UserInDB( ) ``` -!!! warning - As funções adicionais de suporte são apenas para demonstração de um fluxo possível dos dados, mas é claro que elas não fornecem segurança real. +/// warning + +As funções adicionais de suporte são apenas para demonstração de um fluxo possível dos dados, mas é claro que elas não fornecem segurança real. + +/// ## Reduzir duplicação @@ -158,17 +168,21 @@ Toda conversão de dados, validação, documentação, etc. ainda funcionará no Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `password` em texto claro, com `hashed_password` e sem senha): -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../docs_src/extra_models/tutorial002.py!} +``` + +//// - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// tab | Python 3.10 and above -=== "Python 3.10 and above" +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../docs_src/extra_models/tutorial002_py310.py!} +``` - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +//// ## `Union` ou `anyOf` @@ -178,20 +192,27 @@ Isso será definido no OpenAPI com `anyOf`. Para fazer isso, use a dica de tipo padrão do Python `typing.Union`: -!!! note - Ao definir um `Union`, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`. +/// note + +Ao definir um `Union`, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`. -=== "Python 3.8 and above" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | Python 3.8 and above -=== "Python 3.10 and above" +```Python hl_lines="1 14-15 18-20 33" +{!> ../../docs_src/extra_models/tutorial003.py!} +``` + +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.10 and above + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// ### `Union` no Python 3.10 @@ -213,17 +234,21 @@ Da mesma forma, você pode declarar respostas de listas de objetos. Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python 3.9 e superior): -=== "Python 3.8 and above" +//// tab | Python 3.8 and above - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +```Python hl_lines="1 20" +{!> ../../docs_src/extra_models/tutorial004.py!} +``` -=== "Python 3.9 and above" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9 and above + +```Python hl_lines="18" +{!> ../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// ## Resposta com `dict` arbitrário @@ -233,17 +258,21 @@ Isso é útil se você não souber os nomes de campo / atributo válidos (que se Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e superior): -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="1 8" +{!> ../../docs_src/extra_models/tutorial005.py!} +``` + +//// - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="6" +{!> ../../docs_src/extra_models/tutorial005_py39.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// ## Em resumo diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md index 9fcdaf91f..f301c18b6 100644 --- a/docs/pt/docs/tutorial/first-steps.md +++ b/docs/pt/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ O arquivo FastAPI mais simples pode se parecer com: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Copie o conteúdo para um arquivo `main.py`. @@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! nota - O comando `uvicorn main:app` se refere a: +/// note | Nota - * `main`: o arquivo `main.py` (o "módulo" Python). - * `app`: o objeto criado no arquivo `main.py` com a linha `app = FastAPI()`. - * `--reload`: faz o servidor reiniciar após mudanças de código. Use apenas para desenvolvimento. +O comando `uvicorn main:app` se refere a: + +* `main`: o arquivo `main.py` (o "módulo" Python). +* `app`: o objeto criado no arquivo `main.py` com a linha `app = FastAPI()`. +* `--reload`: faz o servidor reiniciar após mudanças de código. Use apenas para desenvolvimento. + +/// Na saída, temos: @@ -131,20 +134,23 @@ Você também pode usá-lo para gerar código automaticamente para clientes que ### Passo 1: importe `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` é uma classe Python que fornece todas as funcionalidades para sua API. -!!! nota "Detalhes técnicos" - `FastAPI` é uma classe que herda diretamente de `Starlette`. +/// note | Detalhes técnicos + +`FastAPI` é uma classe que herda diretamente de `Starlette`. - Você pode usar todas as funcionalidades do Starlette com `FastAPI` também. +Você pode usar todas as funcionalidades do Starlette com `FastAPI` também. + +/// ### Passo 2: crie uma "instância" de `FastAPI` ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Aqui, a variável `app` será uma "instância" da classe `FastAPI`. @@ -166,7 +172,7 @@ $ uvicorn main:app --reload Se você criar a sua aplicação como: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` E colocar em um arquivo `main.py`, você iria chamar o `uvicorn` assim: @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Informação" - Uma "rota" também é comumente chamada de "endpoint". +/// info | Informação + +Uma "rota" também é comumente chamada de "endpoint". + +/// Ao construir uma API, a "rota" é a principal forma de separar "preocupações" e "recursos". @@ -242,7 +251,7 @@ Vamos chamá-los de "**operações**" também. #### Defina um *decorador de rota* ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` O `@app.get("/")` diz ao **FastAPI** que a função logo abaixo é responsável por tratar as requisições que vão para: @@ -250,16 +259,19 @@ O `@app.get("/")` diz ao **FastAPI** que a função logo abaixo é responsável * a rota `/` * usando o operador get -!!! info "`@decorador`" - Essa sintaxe `@alguma_coisa` em Python é chamada de "decorador". +/// info | `@decorador` - Você o coloca em cima de uma função. Como um chapéu decorativo (acho que é daí que vem o termo). +Essa sintaxe `@alguma_coisa` em Python é chamada de "decorador". - Um "decorador" pega a função abaixo e faz algo com ela. +Você o coloca em cima de uma função. Como um chapéu decorativo (acho que é daí que vem o termo). - Em nosso caso, este decorador informa ao **FastAPI** que a função abaixo corresponde a **rota** `/` com uma **operação** `get`. +Um "decorador" pega a função abaixo e faz algo com ela. - É o "**decorador de rota**". +Em nosso caso, este decorador informa ao **FastAPI** que a função abaixo corresponde a **rota** `/` com uma **operação** `get`. + +É o "**decorador de rota**". + +/// Você também pode usar as outras operações: @@ -274,14 +286,17 @@ E os mais exóticos: * `@app.patch()` * `@app.trace()` -!!! tip "Dica" - Você está livre para usar cada operação (método HTTP) como desejar. +/// tip | Dica + +Você está livre para usar cada operação (método HTTP) como desejar. - O **FastAPI** não impõe nenhum significado específico. +O **FastAPI** não impõe nenhum significado específico. - As informações aqui são apresentadas como uma orientação, não uma exigência. +As informações aqui são apresentadas como uma orientação, não uma exigência. - Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`. +Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`. + +/// ### Passo 4: defina uma **função de rota** @@ -292,7 +307,7 @@ Esta é a nossa "**função de rota**": * **função**: é a função abaixo do "decorador" (abaixo do `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Esta é uma função Python. @@ -306,16 +321,19 @@ Neste caso, é uma função `assíncrona`. Você também pode defini-la como uma função normal em vez de `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` -!!! nota - Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#com-pressa){.internal-link target=_blank}. +/// note | Nota + +Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#com-pressa){.internal-link target=_blank}. + +/// ### Passo 5: retorne o conteúdo ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Você pode retornar um `dict`, `list` e valores singulares como `str`, `int`, etc. diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md index d9f3d6782..0d0abbd25 100644 --- a/docs/pt/docs/tutorial/handling-errors.md +++ b/docs/pt/docs/tutorial/handling-errors.md @@ -27,7 +27,7 @@ Para retornar ao cliente *responses* HTTP com erros, use o `HTTPException`. ### Import `HTTPException` ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### Lance o `HTTPException` no seu código. @@ -43,7 +43,7 @@ O benefício de lançar uma exceção em vez de retornar um valor ficará mais e Neste exemplo, quando o cliente pede, na requisição, por um item cujo ID não existe, a exceção com o status code `404` é lançada: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### A response resultante @@ -66,12 +66,14 @@ Mas se o cliente faz uma requisição para `http://example.com/items/bar` (ou se } ``` -!!! tip "Dica" - Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`. +/// tip | Dica - Você pode passar um `dict` ou um `list`, etc. - Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON. +Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`. +Você pode passar um `dict` ou um `list`, etc. +Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON. + +/// ## Adicione headers customizados @@ -82,7 +84,7 @@ Você provavelmente não precisará utilizar esses headers diretamente no seu c Mas caso você precise, para um cenário mais complexo, você pode adicionar headers customizados: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` ## Instalando manipuladores de exceções customizados @@ -94,7 +96,7 @@ Digamos que você tenha uma exceção customizada `UnicornException` que você ( Nesse cenário, se você precisa manipular essa exceção de modo global com o FastAPI, você pode adicionar um manipulador de exceção customizada com `@app.exception_handler()`. ```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` Nesse cenário, se você fizer uma requisição para `/unicorns/yolo`, a *operação de caminho* vai lançar (`raise`) o `UnicornException`. @@ -107,10 +109,13 @@ Dessa forma você receberá um erro "limpo", com o HTTP status code `418` e um J {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "Detalhes Técnicos" - Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. +/// note | Detalhes Técnicos + +Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. + +**FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`. - **FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`. +/// ## Sobrescreva o manipulador padrão de exceções @@ -127,7 +132,7 @@ Quando a requisição contém dados inválidos, **FastAPI** internamente lança Para sobrescrevê-lo, importe o `RequestValidationError` e use-o com o `@app.exception_handler(RequestValidationError)` para decorar o manipulador de exceções. ```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` Se você for ao `/items/foo`, em vez de receber o JSON padrão com o erro: @@ -157,8 +162,11 @@ path -> item_id ### `RequestValidationError` vs `ValidationError` -!!! warning "Aviso" - Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento. +/// warning | Aviso + +Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento. + +/// `RequestValidationError` é uma subclasse do `ValidationError` existente no Pydantic. @@ -175,14 +183,16 @@ Do mesmo modo, você pode sobreescrever o `HTTPException`. Por exemplo, você pode querer retornar uma *response* em *plain text* ao invés de um JSON para os seguintes erros: ```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "Detalhes Técnicos" - Você pode usar `from starlette.responses import PlainTextResponse`. +/// note | Detalhes Técnicos + +Você pode usar `from starlette.responses import PlainTextResponse`. - **FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. +**FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. +/// ### Use o body do `RequestValidationError`. @@ -245,7 +255,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException Se você quer usar a exceção em conjunto com o mesmo manipulador de exceção *default* do **FastAPI**, você pode importar e re-usar esses manipuladores de exceção do `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` Nesse exemplo você apenas imprime (`print`) o erro com uma mensagem expressiva. Mesmo assim, dá para pegar a ideia. Você pode usar a exceção e então apenas re-usar o manipulador de exceção *default*. diff --git a/docs/pt/docs/tutorial/header-param-models.md b/docs/pt/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..a42f77a2d --- /dev/null +++ b/docs/pt/docs/tutorial/header-param-models.md @@ -0,0 +1,184 @@ +# Modelos de Parâmetros do Cabeçalho + +Se você possui um grupo de **parâmetros de cabeçalho** relacionados, você pode criar um **modelo do Pydantic** para declará-los. + +Isso vai lhe permitir **reusar o modelo** em **múltiplos lugares** e também declarar validações e metadadados para todos os parâmetros de uma vez. 😎 + +/// note | Nota + +Isso é possível desde a versão `0.115.0` do FastAPI. 🤓 + +/// + +## Parâmetros do Cabeçalho com um Modelo Pydantic + +Declare os **parâmetros de cabeçalho** que você precisa em um **modelo do Pydantic**, e então declare o parâmetro como `Header`: + +//// tab | Python 3.10+ + +```Python hl_lines="9-14 18" +{!> ../../docs_src/header_param_models/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9-14 18" +{!> ../../docs_src/header_param_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10-15 19" +{!> ../../docs_src/header_param_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7-12 16" +{!> ../../docs_src/header_param_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="9-14 18" +{!> ../../docs_src/header_param_models/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7-12 16" +{!> ../../docs_src/header_param_models/tutorial001_py310.py!} +``` + +//// + +O **FastAPI** irá **extrair** os dados de **cada campo** a partir dos **cabeçalhos** da requisição e te retornará o modelo do Pydantic que você definiu. + +### Checando a documentação + +Você pode ver os headers necessários na interface gráfica da documentação em `/docs`: + +
+ +
+ +### Proibindo Cabeçalhos adicionais + +Em alguns casos de uso especiais (provavelmente não muito comuns), você pode querer **restringir** os cabeçalhos que você quer receber. + +Você pode usar a configuração dos modelos do Pydantic para proibir (`forbid`) quaisquer campos `extra`: + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/header_param_models/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../docs_src/header_param_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/header_param_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="8" +{!> ../../docs_src/header_param_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/header_param_models/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/header_param_models/tutorial002.py!} +``` + +//// + +Se um cliente tentar enviar alguns **cabeçalhos extra**, eles irão receber uma resposta de **erro**. + +Por exemplo, se o cliente tentar enviar um cabeçalho `tool` com o valor `plumbus`, ele irá receber uma resposta de **erro** informando que o parâmetro do cabeçalho `tool` não é permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## Resumo + +Você pode utilizar **modelos do Pydantic** para declarar **cabeçalhos** no **FastAPI**. 😎 diff --git a/docs/pt/docs/tutorial/header-params.md b/docs/pt/docs/tutorial/header-params.md index 4bdfb7e9c..ac61d0305 100644 --- a/docs/pt/docs/tutorial/header-params.md +++ b/docs/pt/docs/tutorial/header-params.md @@ -6,17 +6,21 @@ Você pode definir parâmetros de Cabeçalho da mesma maneira que define paramê Primeiro importe `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../docs_src/header_params/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +//// ## Declare parâmetros de `Header` @@ -24,25 +28,35 @@ Então declare os paramêtros de cabeçalho usando a mesma estrutura que em `Pat O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial001.py!} +``` + +//// + +/// note | Detalhes Técnicos - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +`Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`. -=== "Python 3.8+" +Mas lembre-se que quando você importa `Query`, `Path`, `Header`, e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +/// -!!! note "Detalhes Técnicos" - `Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`. +/// info - Mas lembre-se que quando você importa `Query`, `Path`, `Header`, e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. +Para declarar headers, você precisa usar `Header`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. -!!! info - Para declarar headers, você precisa usar `Header`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. +/// ## Conversão automática @@ -60,20 +74,27 @@ Portanto, você pode usar `user_agent` como faria normalmente no código Python, Se por algum motivo você precisar desabilitar a conversão automática de sublinhados para hífens, defina o parâmetro `convert_underscores` de `Header` para `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../docs_src/header_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/header_params/tutorial002.py!} +``` + +//// -=== "Python 3.8+" +/// warning | Aviso - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +Antes de definir `convert_underscores` como `False`, lembre-se de que alguns proxies e servidores HTTP não permitem o uso de cabeçalhos com sublinhados. -!!! warning "Aviso" - Antes de definir `convert_underscores` como `False`, lembre-se de que alguns proxies e servidores HTTP não permitem o uso de cabeçalhos com sublinhados. +/// ## Cabeçalhos duplicados @@ -85,23 +106,29 @@ Você receberá todos os valores do cabeçalho duplicado como uma `list` Python. Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de uma vez, você pode escrever: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/header_params/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// Se você se comunicar com essa *operação de caminho* enviando dois cabeçalhos HTTP como: diff --git a/docs/pt/docs/tutorial/index.md b/docs/pt/docs/tutorial/index.md index 5fc0485a0..4e6293bb0 100644 --- a/docs/pt/docs/tutorial/index.md +++ b/docs/pt/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...isso também inclui o `uvicorn`, que você pode usar como o servidor que rodará seu código. -!!! nota - Você também pode instalar parte por parte. +/// note | Nota - Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção: +Você também pode instalar parte por parte. - ``` - pip install fastapi - ``` +Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção: - Também instale o `uvicorn` para funcionar como servidor: +``` +pip install fastapi +``` + +Também instale o `uvicorn` para funcionar como servidor: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +E o mesmo para cada dependência opcional que você quiser usar. - E o mesmo para cada dependência opcional que você quiser usar. +/// ## Guia Avançado de Usuário diff --git a/docs/pt/docs/tutorial/metadata.md b/docs/pt/docs/tutorial/metadata.md new file mode 100644 index 000000000..5db2882b9 --- /dev/null +++ b/docs/pt/docs/tutorial/metadata.md @@ -0,0 +1,132 @@ +# Metadados e Urls de Documentos + +Você pode personalizar várias configurações de metadados na sua aplicação **FastAPI**. + +## Metadados para API + +Você pode definir os seguintes campos que são usados na especificação OpenAPI e nas interfaces automáticas de documentação da API: + +| Parâmetro | Tipo | Descrição | +|------------|------|-------------| +| `title` | `str` | O título da API. | +| `summary` | `str` | Um breve resumo da API. Disponível desde OpenAPI 3.1.0, FastAPI 0.99.0. | +| `description` | `str` | Uma breve descrição da API. Pode usar Markdown. | +| `version` | `string` | A versão da API. Esta é a versão da sua aplicação, não do OpenAPI. Por exemplo, `2.5.0`. | +| `terms_of_service` | `str` | Uma URL para os Termos de Serviço da API. Se fornecido, deve ser uma URL. | +| `contact` | `dict` | As informações de contato da API exposta. Pode conter vários campos.
Campos de contact
ParâmetroTipoDescrição
namestrO nome identificador da pessoa/organização de contato.
urlstrA URL que aponta para as informações de contato. DEVE estar no formato de uma URL.
emailstrO endereço de e-mail da pessoa/organização de contato. DEVE estar no formato de um endereço de e-mail.
| +| `license_info` | `dict` | As informações de licença para a API exposta. Ela pode conter vários campos.
Campos de license_info
ParâmetroTipoDescrição
namestrOBRIGATÓRIO (se um license_info for definido). O nome da licença usada para a API.
identifierstrUma expressão de licença SPDX para a API. O campo identifier é mutuamente exclusivo do campo url. Disponível desde OpenAPI 3.1.0, FastAPI 0.99.0.
urlstrUma URL para a licença usada para a API. DEVE estar no formato de uma URL.
| + +Você pode defini-los da seguinte maneira: + +```Python hl_lines="3-16 19-32" +{!../../docs_src/metadata/tutorial001.py!} +``` + +/// tip | Dica + +Você pode escrever Markdown no campo `description` e ele será renderizado na saída. + +/// + +Com essa configuração, a documentação automática da API se pareceria com: + + + +## Identificador de Licença + +Desde o OpenAPI 3.1.0 e FastAPI 0.99.0, você também pode definir o license_info com um identifier em vez de uma url. + +Por exemplo: + +```Python hl_lines="31" +{!../../docs_src/metadata/tutorial001_1.py!} +``` + +## Metadados para tags + +Você também pode adicionar metadados adicionais para as diferentes tags usadas para agrupar suas operações de rota com o parâmetro `openapi_tags`. + +Ele recebe uma lista contendo um dicionário para cada tag. + +Cada dicionário pode conter: + +* `name` (**obrigatório**): uma `str` com o mesmo nome da tag que você usa no parâmetro `tags` nas suas *operações de rota* e `APIRouter`s. +* `description`: uma `str` com uma breve descrição da tag. Pode conter Markdown e será exibido na interface de documentação. +* `externalDocs`: um `dict` descrevendo a documentação externa com: + * `description`: uma `str` com uma breve descrição da documentação externa. + * `url` (**obrigatório**): uma `str` com a URL da documentação externa. + +### Criar Metadados para tags + +Vamos tentar isso em um exemplo com tags para `users` e `items`. + +Crie metadados para suas tags e passe-os para o parâmetro `openapi_tags`: + +```Python hl_lines="3-16 18" +{!../../docs_src/metadata/tutorial004.py!} +``` + +Observe que você pode usar Markdown dentro das descrições. Por exemplo, "login" será exibido em negrito (**login**) e "fancy" será exibido em itálico (_fancy_). + +/// tip | Dica + +Você não precisa adicionar metadados para todas as tags que você usa. + +/// + +### Use suas tags + +Use o parâmetro `tags` com suas *operações de rota* (e `APIRouter`s) para atribuí-los a diferentes tags: + +```Python hl_lines="21 26" +{!../../docs_src/metadata/tutorial004.py!} +``` + +/// info | Informação + +Leia mais sobre tags em [Configuração de Operação de Caminho](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// + +### Cheque os documentos + +Agora, se você verificar a documentação, ela exibirá todos os metadados adicionais: + + + +### Ordem das tags + +A ordem de cada dicionário de metadados de tag também define a ordem exibida na interface de documentação. + +Por exemplo, embora `users` apareça após `items` em ordem alfabética, ele é exibido antes deles, porque adicionamos seus metadados como o primeiro dicionário na lista. + +## URL da OpenAPI + +Por padrão, o esquema OpenAPI é servido em `/openapi.json`. + +Mas você pode configurá-lo com o parâmetro `openapi_url`. + +Por exemplo, para defini-lo para ser servido em `/api/v1/openapi.json`: + +```Python hl_lines="3" +{!../../docs_src/metadata/tutorial002.py!} +``` + +Se você quiser desativar completamente o esquema OpenAPI, pode definir `openapi_url=None`, o que também desativará as interfaces de documentação que o utilizam. + +## URLs da Documentação + +Você pode configurar as duas interfaces de documentação incluídas: + +* **Swagger UI**: acessível em `/docs`. + * Você pode definir sua URL com o parâmetro `docs_url`. + * Você pode desativá-la definindo `docs_url=None`. +* **ReDoc**: acessível em `/redoc`. + * Você pode definir sua URL com o parâmetro `redoc_url`. + * Você pode desativá-la definindo `redoc_url=None`. + +Por exemplo, para definir o Swagger UI para ser servido em `/documentation` e desativar o ReDoc: + +```Python hl_lines="3" +{!../../docs_src/metadata/tutorial003.py!} +``` diff --git a/docs/pt/docs/tutorial/middleware.md b/docs/pt/docs/tutorial/middleware.md new file mode 100644 index 000000000..d1b798356 --- /dev/null +++ b/docs/pt/docs/tutorial/middleware.md @@ -0,0 +1,70 @@ +# Middleware + +Você pode adicionar middleware à suas aplicações **FastAPI**. + +Um "middleware" é uma função que manipula cada **requisição** antes de ser processada por qualquer *operação de rota* específica. E também cada **resposta** antes de retorná-la. + +* Ele pega cada **requisição** que chega ao seu aplicativo. +* Ele pode então fazer algo com essa **requisição** ou executar qualquer código necessário. +* Então ele passa a **requisição** para ser processada pelo resto do aplicativo (por alguma *operação de rota*). +* Ele então pega a **resposta** gerada pelo aplicativo (por alguma *operação de rota*). +* Ele pode fazer algo com essa **resposta** ou executar qualquer código necessário. +* Então ele retorna a **resposta**. + +/// note | Detalhes técnicos + +Se você tiver dependências com `yield`, o código de saída será executado *depois* do middleware. + +Se houver alguma tarefa em segundo plano (documentada posteriormente), ela será executada *depois* de todo o middleware. + +/// + +## Criar um middleware + +Para criar um middleware, use o decorador `@app.middleware("http")` logo acima de uma função. + +A função middleware recebe: + +* A `request`. +* Uma função `call_next` que receberá o `request` como um parâmetro. + * Esta função passará a `request` para a *operação de rota* correspondente. + * Então ela retorna a `response` gerada pela *operação de rota* correspondente. +* Você pode então modificar ainda mais o `response` antes de retorná-lo. + +```Python hl_lines="8-9 11 14" +{!../../docs_src/middleware/tutorial001.py!} +``` + +/// tip | Dica + +Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados usando o prefixo 'X-'. + +Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em Documentos CORS da Starlette. + +/// + +/// note | Detalhes técnicos + +Você também pode usar `from starlette.requests import Request`. + +**FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. + +/// + +### Antes e depois da `response` + +Você pode adicionar código para ser executado com a `request`, antes que qualquer *operação de rota* o receba. + +E também depois que a `response` é gerada, antes de retorná-la. + +Por exemplo, você pode adicionar um cabeçalho personalizado `X-Process-Time` contendo o tempo em segundos que levou para processar a solicitação e gerar uma resposta: + +```Python hl_lines="10 12-13" +{!../../docs_src/middleware/tutorial001.py!} +``` + +## Outros middlewares + +Mais tarde, você pode ler mais sobre outros middlewares no [Guia do usuário avançado: Middleware avançado](../advanced/middleware.md){.internal-link target=_blank}. + +Você lerá sobre como manipular CORS com um middleware na próxima seção. diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index 13a87240f..5f3cc82fb 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ Existem vários parâmetros que você pode passar para o seu *decorador de operação de rota* para configurá-lo. -!!! warning "Aviso" - Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*. +/// warning | Aviso + +Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*. + +/// ## Código de Status da Resposta @@ -13,52 +16,67 @@ Você pode passar diretamente o código `int`, como `404`. Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`: -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="3 17" +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="3 17" +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | Python 3.10 and above -=== "Python 3.10 and above" +```Python hl_lines="1 15" +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI. -!!! note "Detalhes Técnicos" - Você também poderia usar `from starlette import status`. +/// note | Detalhes Técnicos + +Você também poderia usar `from starlette import status`. + +**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette. - **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette. +/// ## Tags Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`): -=== "Python 3.8 and above" +//// tab | Python 3.8 and above - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// -=== "Python 3.9 and above" +//// tab | Python 3.9 and above - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "Python 3.10 and above" +//// - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +//// tab | Python 3.10 and above + +```Python hl_lines="15 20 25" +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática: @@ -73,30 +91,36 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`. **FastAPI** suporta isso da mesma maneira que com strings simples: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## Resumo e descrição Você pode adicionar um `summary` e uma `description`: -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="20-21" +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="20-21" +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | Python 3.10 and above -=== "Python 3.10 and above" +```Python hl_lines="18-19" +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// ## Descrição do docstring @@ -104,23 +128,29 @@ Como as descrições tendem a ser longas e cobrir várias linhas, você pode dec Você pode escrever Markdown na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring). -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="19-27" +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +//// tab | Python 3.9 and above -=== "Python 3.9 and above" +```Python hl_lines="19-27" +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "Python 3.10 and above" +//// tab | Python 3.10 and above - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +```Python hl_lines="17-25" +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// Ela será usada nas documentações interativas: @@ -131,31 +161,43 @@ Ela será usada nas documentações interativas: Você pode especificar a descrição da resposta com o parâmetro `response_description`: -=== "Python 3.8 and above" +//// tab | Python 3.8 and above + +```Python hl_lines="21" +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} +``` + +//// + +//// tab | Python 3.9 and above + +```Python hl_lines="21" +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.10 and above + +```Python hl_lines="19" +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +//// -=== "Python 3.9 and above" +/// info | Informação - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral. -=== "Python 3.10 and above" +/// - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +/// check -!!! info "Informação" - Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral. +OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta. -!!! check - OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta. +Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida". - Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida". +/// @@ -164,7 +206,7 @@ Você pode especificar a descrição da resposta com o parâmetro `response_desc Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` Ela será claramente marcada como descontinuada nas documentações interativas: diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index eb0d31dc3..3361f86c5 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -6,17 +6,21 @@ Do mesmo modo que você pode declarar mais validações e metadados para parâme Primeiro, importe `Path` de `fastapi`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +//// ## Declare metadados @@ -24,24 +28,31 @@ Você pode declarar todos os parâmetros da mesma maneira que na `Query`. Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` -!!! note "Nota" - Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota. +//// - Então, você deve declará-lo com `...` para marcá-lo como obrigatório. +/// note | Nota - Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório. +Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota. + +Então, você deve declará-lo com `...` para marcá-lo como obrigatório. + +Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório. + +/// ## Ordene os parâmetros de acordo com sua necessidade @@ -60,7 +71,7 @@ Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pel Então, você pode declarar sua função assim: ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## Ordene os parâmetros de a acordo com sua necessidade, truques @@ -72,7 +83,7 @@ Passe `*`, como o primeiro parâmetro da função. O Python não vai fazer nada com esse `*`, mas ele vai saber que a partir dali os parâmetros seguintes deverão ser chamados argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não possuam um valor padrão. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## Validações numéricas: maior que ou igual @@ -82,7 +93,7 @@ Com `Query` e `Path` (e outras que você verá mais tarde) você pode declarar r Aqui, com `ge=1`, `item_id` precisará ser um número inteiro maior que ("`g`reater than") ou igual ("`e`qual") a 1. ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## Validações numéricas: maior que e menor que ou igual @@ -93,7 +104,7 @@ O mesmo se aplica para: * `le`: menor que ou igual (`l`ess than or `e`qual) ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## Validações numéricas: valores do tipo float, maior que e menor que @@ -107,7 +118,7 @@ Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seria. E o mesmo para lt. ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## Recapitulando @@ -121,18 +132,24 @@ E você também pode declarar validações numéricas: * `lt`: menor que (`l`ess `t`han) * `le`: menor que ou igual (`l`ess than or `e`qual) -!!! info "Informação" - `Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`. +/// info | Informação + +`Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`. + +Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu. + +/// + +/// note | Detalhes Técnicos - Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu. +Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções. -!!! note "Detalhes Técnicos" - Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções. +Que quando chamadas, retornam instâncias de classes de mesmo nome. - Que quando chamadas, retornam instâncias de classes de mesmo nome. +Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`. - Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`. +Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos. - Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos. +Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros. - Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros. +/// diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index be2b7f7a4..64f8a0253 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Você pode declarar os "parâmetros" ou "variáveis" com a mesma sintaxe utilizada pelo formato de strings do Python: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` O valor do parâmetro que foi passado à `item_id` será passado para a sua função como o argumento `item_id`. @@ -19,12 +19,17 @@ Então, se você rodar este exemplo e for até dados
@@ -35,7 +40,12 @@ Se você rodar esse exemplo e abrir o seu navegador em "parsing" automático no request . @@ -63,7 +73,12 @@ devido ao parâmetro da rota `item_id` ter um valor `"foo"`, que não é um `int O mesmo erro apareceria se você tivesse fornecido um `float` ao invés de um `int`, como em: http://127.0.0.1:8000/items/4.2 -!!! Verifique +/// check | Verifique + + + +/// + Então, com a mesma declaração de tipo do Python, o **FastAPI** dá pra você validação de dados. Observe que o erro também mostra claramente o ponto exato onde a validação não passou. @@ -76,7 +91,12 @@ Quando você abrir o seu navegador em -!!! check +/// check | Verifique + + + +/// + Novamente, apenas com a mesma declaração de tipo do Python, o **FastAPI** te dá de forma automática e interativa a documentação (integrada com o Swagger UI). Veja que o parâmetro de rota está declarado como sendo um inteiro (int). @@ -110,7 +130,7 @@ E então você pode ter também uma rota `/users/{user_id}` para pegar dados sob Porque as operações de rota são avaliadas em ordem, você precisa ter certeza que a rota para `/users/me` está sendo declarado antes da rota `/users/{user_id}`: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` Caso contrário, a rota para `/users/{user_id}` coincidiria também para `/users/me`, "pensando" que estaria recebendo o parâmetro `user_id` com o valor de `"me"`. @@ -128,13 +148,21 @@ Por herdar de `str` a documentação da API vai ser capaz de saber que os valore Assim, crie atributos de classe com valores fixos, que serão os valores válidos disponíveis. ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! informação - Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4. +/// info | informação + +Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4. + +/// + +/// tip | Dica + + + +/// -!!! dica Se você está se perguntando, "AlexNet", "ResNet", e "LeNet" são apenas nomes de modelos de Machine Learning (aprendizado de máquina). ### Declare um *parâmetro de rota* @@ -142,7 +170,7 @@ Assim, crie atributos de classe com valores fixos, que serão os valores válido Logo, crie um *parâmetro de rota* com anotações de tipo usando a classe enum que você criou (`ModelName`): ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### Revise a documentação @@ -160,7 +188,7 @@ O valor do *parâmetro da rota* será um *membro de enumeration*. Você pode comparar eles com o *membro de enumeration* no enum `ModelName` que você criou: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### Obtenha o *valor de enumerate* @@ -168,10 +196,15 @@ Você pode comparar eles com o *membro de enumeration* no enum `ModelName` que v Você pode ter o valor exato de enumerate (um `str` nesse caso) usando `model_name.value`, ou em geral, `your_enum_member.value`: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! conselho +/// tip | Dica + + + +/// + Você também poderia acessar o valor `"lenet"` com `ModelName.lenet.value` #### Retorne *membros de enumeration* @@ -181,7 +214,7 @@ Você pode retornar *membros de enum* da sua *rota de operação*, em um corpo J Eles serão convertidos para o seus valores correspondentes (strings nesse caso) antes de serem retornados ao cliente: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` No seu cliente você vai obter uma resposta JSON como: @@ -222,10 +255,15 @@ Nesse caso, o nome do parâmetro é `file_path`, e a última parte, `:path`, diz Então, você poderia usar ele com: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` -!!! dica +/// tip | Dica + + + +/// + Você poderia precisar que o parâmetro contivesse `/home/johndoe/myfile.txt`, com uma barra no inicio (`/`). Neste caso, a URL deveria ser: `/files//home/johndoe/myfile.txt`, com barra dupla (`//`) entre `files` e `home`. diff --git a/docs/pt/docs/tutorial/query-param-models.md b/docs/pt/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..854183fb4 --- /dev/null +++ b/docs/pt/docs/tutorial/query-param-models.md @@ -0,0 +1,197 @@ +# Modelos de Parâmetros de Consulta + +Se você possui um grupo de **parâmetros de consultas** que são relacionados, você pode criar um **modelo Pydantic** para declará-los. + +Isso permitiria que você **reutilizasse o modelo** em **diversos lugares**, e também declarasse validações e metadados de todos os parâmetros de uma única vez. 😎 + +/// note | Nota + +Isso é suportado desde o FastAPI versão `0.115.0`. 🤓 + +/// + +## Parâmetros de Consulta com um Modelo Pydantic + +Declare os **parâmetros de consulta** que você precisa em um **modelo Pydantic**, e então declare o parâmetro como `Query`: + +//// tab | Python 3.10+ + +```Python hl_lines="9-13 17" +{!> ../../docs_src/query_param_models/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-12 16" +{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10-14 18" +{!> ../../docs_src/query_param_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9-13 17" +{!> ../../docs_src/query_param_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="8-12 16" +{!> ../../docs_src/query_param_models/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9-13 17" +{!> ../../docs_src/query_param_models/tutorial001_py310.py!} +``` + +//// + +O **FastAPI** **extrairá** os dados para **cada campo** dos **parâmetros de consulta** presentes na requisição, e fornecerá o modelo Pydantic que você definiu. + + +## Verifique os Documentos + +Você pode ver os parâmetros de consulta nos documentos de IU em `/docs`: + +
+ +
+ +## Restrinja Parâmetros de Consulta Extras + +Em alguns casos especiais (provavelmente não muito comuns), você queira **restrinjir** os parâmetros de consulta que deseja receber. + +Você pode usar a configuração do modelo Pydantic para `forbid` (proibir) qualquer campo `extra`: + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/query_param_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/query_param_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/query_param_models/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="11" +{!> ../../docs_src/query_param_models/tutorial002.py!} +``` + +//// + +Caso um cliente tente enviar alguns dados **extras** nos **parâmetros de consulta**, eles receberão um retorno de **erro**. + +Por exemplo, se o cliente tentar enviar um parâmetro de consulta `tool` com o valor `plumbus`, como: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +Eles receberão um retorno de **erro** informando-os que o parâmentro de consulta `tool` não é permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## Resumo + +Você pode utilizar **modelos Pydantic** para declarar **parâmetros de consulta** no **FastAPI**. 😎 + +/// tip | Dica + +Alerta de spoiler: você também pode utilizar modelos Pydantic para declarar cookies e cabeçalhos, mas você irá ler sobre isso mais a frente no tutorial. 🤫 + +/// diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md index 9a9e071db..2fa0eeba0 100644 --- a/docs/pt/docs/tutorial/query-params-str-validations.md +++ b/docs/pt/docs/tutorial/query-params-str-validations.md @@ -5,15 +5,18 @@ O **FastAPI** permite que você declare informações adicionais e validações Vamos utilizar essa aplicação como exemplo: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} +{!../../docs_src/query_params_str_validations/tutorial001.py!} ``` O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório. -!!! note "Observação" - O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. +/// note | Observação - O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros. +O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. + +O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros. + +/// ## Validação adicional @@ -24,7 +27,7 @@ Nós iremos forçar que mesmo o parâmetro `q` seja opcional, sempre que informa Para isso, primeiro importe `Query` de `fastapi`: ```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` ## Use `Query` como o valor padrão @@ -32,7 +35,7 @@ Para isso, primeiro importe `Query` de `fastapi`: Agora utilize-o como valor padrão do seu parâmetro, definindo o parâmetro `max_length` para 50: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` Note que substituímos o valor padrão de `None` para `Query(default=None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro. @@ -51,22 +54,25 @@ q: Union[str, None] = None Mas o declara explicitamente como um parâmetro de consulta. -!!! info "Informação" - Tenha em mente que o FastAPI se preocupa com a parte: +/// info | Informação - ```Python - = None - ``` +Tenha em mente que o FastAPI se preocupa com a parte: - Ou com: +```Python += None +``` - ```Python - = Query(default=None) - ``` +Ou com: - E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório. +```Python += Query(default=None) +``` + +E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório. - O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte. +O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte. + +/// Então, podemos passar mais parâmetros para `Query`. Neste caso, o parâmetro `max_length` que se aplica a textos: @@ -81,7 +87,7 @@ Isso irá validar os dados, mostrar um erro claro quando os dados forem inválid Você também pode incluir um parâmetro `min_length`: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} +{!../../docs_src/query_params_str_validations/tutorial003.py!} ``` ## Adicionando expressões regulares @@ -89,7 +95,7 @@ Você também pode incluir um parâmetro `min_length`: Você pode definir uma expressão regular que combine com um padrão esperado pelo parâmetro: ```Python hl_lines="11" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` Essa expressão regular específica verifica se o valor recebido no parâmetro: @@ -109,11 +115,14 @@ Da mesma maneira que você utiliza `None` como o primeiro argumento para ser uti Vamos dizer que você queira que o parâmetro de consulta `q` tenha um `min_length` de `3`, e um valor padrão de `"fixedquery"`, então declararíamos assim: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note "Observação" - O parâmetro torna-se opcional quando possui um valor padrão. +/// note | Observação + +O parâmetro torna-se opcional quando possui um valor padrão. + +/// ## Torne-o obrigatório @@ -138,11 +147,14 @@ q: Union[str, None] = Query(default=None, min_length=3) Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Query`, você pode utilizar `...` como o primeiro argumento: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` -!!! info "Informação" - Se você nunca viu os `...` antes: é um valor único especial, faz parte do Python e é chamado "Ellipsis". +/// info | Informação + +Se você nunca viu os `...` antes: é um valor único especial, faz parte do Python e é chamado "Ellipsis". + +/// Dessa forma o **FastAPI** saberá que o parâmetro é obrigatório. @@ -153,7 +165,7 @@ Quando você declara explicitamente um parâmetro com `Query` você pode declar Por exemplo, para declarar que o parâmetro `q` pode aparecer diversas vezes na URL, você escreveria: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` Então, com uma URL assim: @@ -175,8 +187,11 @@ Assim, a resposta para essa URL seria: } ``` -!!! tip "Dica" - Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição. +/// tip | Dica + +Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição. + +/// A documentação interativa da API irá atualizar de acordo, permitindo múltiplos valores: @@ -187,7 +202,7 @@ A documentação interativa da API irá atualizar de acordo, permitindo múltipl E você também pode definir uma lista (`list`) de valores padrão caso nenhum seja informado: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` Se você for até: @@ -212,13 +227,16 @@ O valor padrão de `q` será: `["foo", "bar"]` e sua resposta será: Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note "Observação" - Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista. +/// note | Observação - Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não. +Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista. + +Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não. + +/// ## Declarando mais metadados @@ -226,21 +244,24 @@ Você pode adicionar mais informações sobre o parâmetro. Essa informações serão inclusas no esquema do OpenAPI e utilizado pela documentação interativa e ferramentas externas. -!!! note "Observação" - Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI. +/// note | Observação + +Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI. + +Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento. - Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento. +/// Você pode adicionar um `title`: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` E uma `description`: ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## Apelidos (alias) de parâmetros @@ -262,7 +283,7 @@ Mas ainda você precisa que o nome seja exatamente `item-query`... Então você pode declarar um `alias`, e esse apelido (alias) que será utilizado para encontrar o valor do parâmetro: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## Parâmetros descontinuados @@ -274,7 +295,7 @@ Você tem que deixá-lo ativo por um tempo, já que existem clientes o utilizand Então você passa o parâmetro `deprecated=True` para `Query`: ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` Na documentação aparecerá assim: diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index 08bb99dbc..89b951de6 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta". ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`. @@ -63,39 +63,49 @@ Os valores dos parâmetros na sua função serão: Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão. -!!! check "Verificar" - Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. +/// check | Verificar + +Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. +/// ## Conversão dos tipos de parâmetros de consulta Você também pode declarar tipos `bool`, e eles serão convertidos: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/query_params/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// Nesse caso, se você for para: @@ -137,17 +147,21 @@ E você não precisa declarar eles em nenhuma ordem específica. Eles serão detectados pelo nome: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +```Python hl_lines="6 8" +{!> ../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +```Python hl_lines="8 10" +{!> ../../docs_src/query_params/tutorial004.py!} +``` + +//// ## Parâmetros de consulta obrigatórios @@ -158,7 +172,7 @@ Caso você não queira adicionar um valor específico mas queira apenas torná-l Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão. ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`. @@ -203,17 +217,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="8" +{!> ../../docs_src/query_params/tutorial006_py310.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../docs_src/query_params/tutorial006.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// Nesse caso, existem 3 parâmetros de consulta: @@ -221,5 +239,8 @@ Nesse caso, existem 3 parâmetros de consulta: * `skip`, um `int` com o valor padrão `0`. * `limit`, um `int` opcional. -!!! tip "Dica" - Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. +/// tip | Dica + +Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#valores-predefinidos){.internal-link target=_blank}. + +/// diff --git a/docs/pt/docs/tutorial/request-files.md b/docs/pt/docs/tutorial/request-files.md new file mode 100644 index 000000000..c22c1c513 --- /dev/null +++ b/docs/pt/docs/tutorial/request-files.md @@ -0,0 +1,176 @@ +# Arquivos de Requisição + +Você pode definir arquivos para serem enviados pelo cliente usando `File`. + +/// info | Informação + +Para receber arquivos enviados, primeiro instale o `python-multipart`. + +Garanta que você criou um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, o ativou e então o instalou, por exemplo: + +```console +$ pip install python-multipart +``` + +Isso é necessário, visto que os arquivos enviados são enviados como "dados de formulário". + +/// + +## Importe `File` + +Importe `File` e `UploadFile` de `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## Definir Parâmetros `File` + +Crie parâmetros de arquivo da mesma forma que você faria para `Body` ou `Form`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info | Informação + +`File` é uma classe que herda diretamente de `Form`. + +Mas lembre-se que quando você importa `Query`, `Path`, `File` e outros de `fastapi`, eles são, na verdade, funções que retornam classes especiais. + +/// + +/// tip | Dica + +Para declarar corpos de arquivos, você precisa usar `File`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). + +/// + +Os arquivos serão enviados como "dados de formulário". + +Se você declarar o tipo do parâmetro da função da sua *operação de rota* como `bytes`, o **FastAPI** lerá o arquivo para você e você receberá o conteúdo como `bytes`. + +Mantenha em mente que isso significa que todo o conteúdo será armazenado na memória. Isso funcionará bem para arquivos pequenos. + +Mas há muitos casos em que você pode se beneficiar do uso de `UploadFile`. + +## Parâmetros de Arquivo com `UploadFile` + +Defina um parâmetro de arquivo com um tipo de `UploadFile`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +Utilizar `UploadFile` tem várias vantagens sobre `bytes`: + +* Você não precisa utilizar o `File()` no valor padrão do parâmetro. +* Ele utiliza um arquivo "spooled": + * Um arquivo armazenado na memória até um limite máximo de tamanho, e após passar esse limite, ele será armazenado no disco. +* Isso significa que funcionará bem para arquivos grandes como imagens, vídeos, binários grandes, etc., sem consumir toda a memória. +* Você pode receber metadados do arquivo enviado. +* Ele tem uma file-like interface `assíncrona`. +* Ele expõe um objeto python `SpooledTemporaryFile` que você pode passar diretamente para outras bibliotecas que esperam um objeto semelhante a um arquivo("file-like"). + +### `UploadFile` + +`UploadFile` tem os seguintes atributos: + +* `filename`: Uma `str` com o nome do arquivo original que foi enviado (por exemplo, `myimage.jpg`). +* `content_type`: Uma `str` com o tipo de conteúdo (tipo MIME / tipo de mídia) (por exemplo, `image/jpeg`). +* `file`: Um `SpooledTemporaryFile` (um file-like objeto). Este é o objeto de arquivo Python que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto semelhante a um arquivo("file-like"). + +`UploadFile` tem os seguintes métodos `assíncronos`. Todos eles chamam os métodos de arquivo correspondentes por baixo dos panos (usando o `SpooledTemporaryFile` interno). + +* `write(data)`: Escreve `data` (`str` ou `bytes`) no arquivo. +* `read(size)`: Lê `size` (`int`) bytes/caracteres do arquivo. +* `seek(offset)`: Vai para o byte na posição `offset` (`int`) no arquivo. + * Por exemplo, `await myfile.seek(0)` irá para o início do arquivo. + * Isso é especialmente útil se você executar `await myfile.read()` uma vez e precisar ler o conteúdo novamente. +* `close()`: Fecha o arquivo. + +Como todos esses métodos são métodos `assíncronos`, você precisa "aguardar" por eles. + +Por exemplo, dentro de uma função de *operação de rota* `assíncrona`, você pode obter o conteúdo com: + +```Python +contents = await myfile.read() +``` + +Se você estiver dentro de uma função de *operação de rota* normal `def`, você pode acessar o `UploadFile.file` diretamente, por exemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalhes Técnicos do `async` + +Quando você usa os métodos `async`, o **FastAPI** executa os métodos de arquivo em um threadpool e aguarda por eles. + +/// + +/// note | Detalhes Técnicos do Starlette + +O `UploadFile` do ***FastAPI** herda diretamente do `UploadFile` do **Starlette** , mas adiciona algumas partes necessárias para torná-lo compatível com o **Pydantic** e as outras partes do FastAPI. + +/// + +## O que é "Form Data" + +O jeito que os formulários HTML (`
`) enviam os dados para o servidor normalmente usa uma codificação "especial" para esses dados, a qual é diferente do JSON. + +**FastAPI** se certificará de ler esses dados do lugar certo, ao invés de JSON. + +/// note | Detalhes Técnicos + +Dados de formulários normalmente são codificados usando o "media type" (tipo de mídia) `application/x-www-form-urlencoded` quando não incluem arquivos. + +Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Se você usar `File`, o **FastAPI** saberá que tem que pegar os arquivos da parte correta do corpo da requisição. + +Se você quiser ler mais sobre essas codificações e campos de formulário, vá para a MDN web docs para POST. + +/// + +/// warning | Aviso + +Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body` que você espera receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. + +Isso não é uma limitação do **FastAPI**, é parte do protocolo HTTP. + +/// + +## Upload de Arquivo Opcional + +Você pode tornar um arquivo opcional usando anotações de tipo padrão e definindo um valor padrão de `None`: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` com Metadados Adicionais + +Você também pode usar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Uploads de Múltiplos Arquivos + +É possível realizar o upload de vários arquivos ao mesmo tempo. + +Eles serão associados ao mesmo "campo de formulário" enviado usando "dados de formulário". + +Para usar isso, declare uma lista de `bytes` ou `UploadFile`: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Você receberá, tal como declarado, uma `list` de `bytes` ou `UploadFile`. + +/// note | Detalhes Técnicos + +Você pode também pode usar `from starlette.responses import HTMLResponse`. + +**FastAPI** providencia o mesmo `starlette.responses` que `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette. + +/// + +### Uploads de Múltiplos Arquivos com Metadados Adicionais + +Da mesma forma de antes, você pode usar `File()` para definir parâmetros adicionais, mesmo para `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Recapitulando + +Utilize `File`, `bytes` e `UploadFile` para declarar arquivos a serem enviados na requisição, enviados como dados de formulário. diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..7128a0ae2 --- /dev/null +++ b/docs/pt/docs/tutorial/request-form-models.md @@ -0,0 +1,134 @@ +# Modelos de Formulários + +Você pode utilizar **Modelos Pydantic** para declarar **campos de formulários** no FastAPI. + +/// info | Informação + +Para utilizar formulários, instale primeiramente o `python-multipart`. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo, e então instalar. Por exemplo: + +```console +$ pip install python-multipart +``` + +/// + +/// note | Nota + +Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓 + +/// + +## Modelos Pydantic para Formulários + +Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja receber como **campos de formulários**, e então declarar o parâmetro como um `Form`: + +//// tab | Python 3.9+ + +```Python hl_lines="9-11 15" +{!> ../../docs_src/request_form_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8-10 14" +{!> ../../docs_src/request_form_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="7-9 13" +{!> ../../docs_src/request_form_models/tutorial001.py!} +``` + +//// + +O **FastAPI** irá **extrair** as informações para **cada campo** dos **dados do formulário** na requisição e dar para você o modelo Pydantic que você definiu. + +## Confira os Documentos + +Você pode verificar na UI de documentação em `/docs`: + +
+ +
+ +## Proibir Campos Extras de Formulários + +Em alguns casos de uso especiais (provavelmente não muito comum), você pode desejar **restringir** os campos do formulário para aceitar apenas os declarados no modelo Pydantic. E **proibir** qualquer campo **extra**. + +/// note | Nota + +Isso é suportado deste a versão `0.114.0` do FastAPI. 🤓 + +/// + +Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualquer campo `extra`: + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../docs_src/request_form_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/request_form_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/request_form_models/tutorial002.py!} +``` + +//// + +Caso um cliente tente enviar informações adicionais, ele receberá um retorno de **erro**. + +Por exemplo, se o cliente tentar enviar os campos de formulário: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +Ele receberá um retorno de erro informando-o que o campo `extra` não é permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## Resumo + +Você pode utilizar modelos Pydantic para declarar campos de formulários no FastAPI. 😎 diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 22954761b..77c099eb3 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -2,16 +2,18 @@ Você pode definir arquivos e campos de formulário ao mesmo tempo usando `File` e `Form`. -!!! info "Informação" - Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`. +/// info | Informação - Por exemplo: `pip install python-multipart`. +Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`. +Por exemplo: `pip install python-multipart`. + +/// ## Importe `File` e `Form` ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## Defina parâmetros de `File` e `Form` @@ -19,17 +21,20 @@ Você pode definir arquivos e campos de formulário ao mesmo tempo usando `File` Crie parâmetros de arquivo e formulário da mesma forma que você faria para `Body` ou `Query`: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` Os arquivos e campos de formulário serão carregados como dados de formulário e você receberá os arquivos e campos de formulário. E você pode declarar alguns dos arquivos como `bytes` e alguns como `UploadFile`. -!!! warning "Aviso" - Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. +/// warning | Aviso + +Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. + +Isso não é uma limitação do **FastAPI** , é parte do protocolo HTTP. - Isso não é uma limitação do **FastAPI** , é parte do protocolo HTTP. +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index 0eb67391b..367fca072 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -2,17 +2,20 @@ Quando você precisar receber campos de formulário ao invés de JSON, você pode usar `Form`. -!!! info "Informação" - Para usar formulários, primeiro instale `python-multipart`. +/// info | Informação - Ex: `pip install python-multipart`. +Para usar formulários, primeiro instale `python-multipart`. + +Ex: `pip install python-multipart`. + +/// ## Importe `Form` Importe `Form` de `fastapi`: ```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` ## Declare parâmetros de `Form` @@ -20,7 +23,7 @@ Importe `Form` de `fastapi`: Crie parâmetros de formulário da mesma forma que você faria para `Body` ou `Query`: ```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` Por exemplo, em uma das maneiras que a especificação OAuth2 pode ser usada (chamada "fluxo de senha"), é necessário enviar um `username` e uma `password` como campos do formulário. @@ -29,11 +32,17 @@ A spec exige que os campos sejam exatamente Com `Form` você pode declarar os mesmos metadados e validação que com `Body` (e `Query`, `Path`, `Cookie`). -!!! info "Informação" - `Form` é uma classe que herda diretamente de `Body`. +/// info | Informação + +`Form` é uma classe que herda diretamente de `Body`. + +/// + +/// tip | Dica -!!! tip "Dica" - Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). +Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). + +/// ## Sobre "Campos de formulário" @@ -41,17 +50,23 @@ A forma como os formulários HTML (`
`) enviam os dados para o servi O **FastAPI** fará a leitura desses dados no lugar certo em vez de JSON. -!!! note "Detalhes técnicos" - Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`. +/// note | Detalhes técnicos + +Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`. + + Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Você lerá sobre como lidar com arquivos no próximo capítulo. + +Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST. + +/// - Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Você lerá sobre como lidar com arquivos no próximo capítulo. +/// warning | Aviso - Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST. +Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`. -!!! warning "Aviso" - Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`. +Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP. - Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP. +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md new file mode 100644 index 000000000..39bfe284a --- /dev/null +++ b/docs/pt/docs/tutorial/request_files.md @@ -0,0 +1,418 @@ +# Arquivos de Requisição + +Você pode definir arquivos para serem enviados para o cliente utilizando `File`. + +/// info + +Para receber arquivos compartilhados, primeiro instale `python-multipart`. + +E.g. `pip install python-multipart`. + +Isso se deve por que arquivos enviados são enviados como "dados de formulário". + +/// + +## Importe `File` + +Importe `File` e `UploadFile` do `fastapi`: + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1" +{!> ../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="1" +{!> ../../docs_src/request_files/tutorial001.py!} +``` + +//// + +## Defina os parâmetros de `File` + +Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`: + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/request_files/tutorial001.py!} +``` + +//// + +/// info | Informação + +`File` é uma classe que herda diretamente de `Form`. + +Mas lembre-se que quando você importa `Query`,`Path`, `File`, entre outros, do `fastapi`, essas são na verdade funções que retornam classes especiais. + +/// + +/// tip | Dica + +Para declarar o corpo de arquivos, você precisa utilizar `File`, do contrário os parâmetros seriam interpretados como parâmetros de consulta ou corpo (JSON) da requisição. + +/// + +Os arquivos serão enviados como "form data". + +Se você declarar o tipo do seu parâmetro na sua *função de operação de rota* como `bytes`, o **FastAPI** irá ler o arquivo para você e você receberá o conteúdo como `bytes`. + +Lembre-se que isso significa que o conteúdo inteiro será armazenado em memória. Isso funciona bem para arquivos pequenos. + +Mas existem vários casos em que você pode se beneficiar ao usar `UploadFile`. + +## Parâmetros de arquivo com `UploadFile` + +Defina um parâmetro de arquivo com o tipo `UploadFile` + +//// tab | Python 3.9+ + +```Python hl_lines="14" +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="13" +{!> ../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="12" +{!> ../../docs_src/request_files/tutorial001.py!} +``` + +//// + +Utilizando `UploadFile` tem várias vantagens sobre `bytes`: + +* Você não precisa utilizar `File()` como o valor padrão do parâmetro. +* A classe utiliza um arquivo em "spool": + * Um arquivo guardado em memória até um tamanho máximo, depois desse limite ele é guardado em disco. +* Isso significa que a classe funciona bem com arquivos grandes como imagens, vídeos, binários extensos, etc. Sem consumir toda a memória. +* Você pode obter metadados do arquivo enviado. +* Ela possui uma interface semelhante a arquivos `async`. +* Ela expõe um objeto python `SpooledTemporaryFile` que você pode repassar para bibliotecas que esperam um objeto com comportamento de arquivo. + +### `UploadFile` + +`UploadFile` tem os seguintes atributos: + +* `filename`: Uma string (`str`) com o nome original do arquivo enviado (e.g. `myimage.jpg`). +* `content-type`: Uma `str` com o tipo do conteúdo (tipo MIME / media) (e.g. `image/jpeg`). +* `file`: Um objeto do tipo `SpooledTemporaryFile` (um objeto file-like). O arquivo propriamente dito que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto "file-like". + +`UploadFile` tem os seguintes métodos `async`. Todos eles chamam os métodos de arquivos por baixo dos panos (usando o objeto `SpooledTemporaryFile` interno). + +* `write(data)`: escreve dados (`data`) em `str` ou `bytes` no arquivo. +* `read(size)`: Lê um número de bytes/caracteres de acordo com a quantidade `size` (`int`). +* `seek(offset)`: Navega para o byte na posição `offset` (`int`) do arquivo. + * E.g., `await myfile.seek(0)` navegaria para o ínicio do arquivo. + * Isso é especialmente útil se você executar `await myfile.read()` uma vez e depois precisar ler os conteúdos do arquivo de novo. +* `close()`: Fecha o arquivo. + +Como todos esses métodos são assíncronos (`async`) você precisa esperar ("await") por eles. + +Por exemplo, dentro de uma *função de operação de rota* assíncrona você pode obter os conteúdos com: + +```Python +contents = await myfile.read() +``` + +Se você estiver dentro de uma *função de operação de rota* definida normalmente com `def`, você pode acessar `UploadFile.file` diretamente, por exemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalhes técnicos do `async` + +Quando você utiliza métodos assíncronos, o **FastAPI** executa os métodos do arquivo em uma threadpool e espera por eles. + +/// + +/// note | Detalhes técnicos do Starlette + +O `UploadFile` do **FastAPI** herda diretamente do `UploadFile` do **Starlette**, mas adiciona algumas funcionalidades necessárias para ser compatível com o **Pydantic** + +/// + +## O que é "Form Data" + +A forma como formulários HTML(`
`) enviam dados para o servidor normalmente utilizam uma codificação "especial" para esses dados, que é diferente do JSON. + +O **FastAPI** garante que os dados serão lidos da forma correta, em vez do JSON. + +/// note | Detalhes Técnicos + +Dados vindos de formulários geralmente tem a codificação com o "media type" `application/x-www-form-urlencoded` quando estes não incluem arquivos. + +Mas quando os dados incluem arquivos, eles são codificados como `multipart/form-data`. Se você utilizar `File`, **FastAPI** saberá que deve receber os arquivos da parte correta do corpo da requisição. + +Se você quer ler mais sobre essas codificações e campos de formulário, veja a documentação online da MDN sobre POST . + +/// + +/// warning | Aviso + +Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body`que seriam recebidos como JSON junto desses parâmetros, por que a codificação do corpo da requisição será `multipart/form-data` em vez de `application/json`. + +Isso não é uma limitação do **FastAPI**, é uma parte do protocolo HTTP. + +/// + +## Arquivo de upload opcional + +Você pode definir um arquivo como opcional utilizando as anotações de tipo padrão e definindo o valor padrão como `None`: + +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 18" +{!> ../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated`, se possível + +/// + +```Python hl_lines="7 15" +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated`, se possível + +/// + +```Python hl_lines="9 17" +{!> ../../docs_src/request_files/tutorial001_02.py!} +``` + +//// + +## `UploadFile` com Metadados Adicionais + +Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: + +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 14" +{!> ../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="7 13" +{!> ../../docs_src/request_files/tutorial001_03.py!} +``` + +//// + +## Envio de Múltiplos Arquivos + +É possível enviar múltiplos arquivos ao mesmo tmepo. + +Ele ficam associados ao mesmo "campo do formulário" enviado com "form data". + +Para usar isso, declare uma lista de `bytes` ou `UploadFile`: + +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11 16" +{!> ../../docs_src/request_files/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="8 13" +{!> ../../docs_src/request_files/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="10 15" +{!> ../../docs_src/request_files/tutorial002.py!} +``` + +//// + +Você irá receber, como delcarado uma lista (`list`) de `bytes` ou `UploadFile`s, + +/// note | Detalhes Técnicos + +Você também poderia utilizar `from starlette.responses import HTMLResponse`. + +O **FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como um facilitador para você, desenvolvedor. Mas a maior parte das respostas vem diretamente do Starlette. + +/// + +### Enviando Múltiplos Arquivos com Metadados Adicionais + +E da mesma forma que antes, você pode utilizar `File()` para definir parâmetros adicionais, até mesmo para `UploadFile`: + +//// tab | Python 3.9+ + +```Python hl_lines="11 18-20" +{!> ../../docs_src/request_files/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12 19-21" +{!> ../../docs_src/request_files/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="9 16" +{!> ../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11 18" +{!> ../../docs_src/request_files/tutorial003.py!} +``` + +//// + +## Recapitulando + +Use `File`, `bytes` e `UploadFile` para declarar arquivos que serão enviados na requisição, enviados como dados do formulário. diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md index 2df17d4ea..2c8924925 100644 --- a/docs/pt/docs/tutorial/response-status-code.md +++ b/docs/pt/docs/tutorial/response-status-code.md @@ -9,16 +9,22 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p * etc. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "Nota" - Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo. +/// note | Nota + +Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo. + +/// O parâmetro `status_code` recebe um número com o código de status HTTP. -!!! info "Informação" - `status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`. +/// info | Informação + +`status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`. + +/// Dessa forma: @@ -27,15 +33,21 @@ Dessa forma: -!!! note "Nota" - Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo. +/// note | Nota + +Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo. + +O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta. - O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta. +/// ## Sobre os códigos de status HTTP -!!! note "Nota" - Se você já sabe o que são códigos de status HTTP, pule para a próxima seção. +/// note | Nota + +Se você já sabe o que são códigos de status HTTP, pule para a próxima seção. + +/// Em HTTP, você envia um código de status numérico de 3 dígitos como parte da resposta. @@ -55,15 +67,18 @@ Resumidamente: * Para erros genéricos do cliente, você pode usar apenas `400`. * `500` e acima são para erros do servidor. Você quase nunca os usa diretamente. Quando algo der errado em alguma parte do código do seu aplicativo ou servidor, ele retornará automaticamente um desses códigos de status. -!!! tip "Dica" - Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP. +/// tip | Dica + +Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP. + +/// ## Atalho para lembrar os nomes Vamos ver o exemplo anterior novamente: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` é o código de status para "Criado". @@ -73,18 +88,20 @@ Mas você não precisa memorizar o que cada um desses códigos significa. Você pode usar as variáveis de conveniência de `fastapi.status`. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o autocomplete do editor para encontrá-los: -!!! note "Detalhes técnicos" - Você também pode usar `from starlette import status`. +/// note | Detalhes técnicos + +Você também pode usar `from starlette import status`. - **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. +**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. +/// ## Alterando o padrão diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md index d04dc1a26..dd95d4c7d 100644 --- a/docs/pt/docs/tutorial/schema-extra-example.md +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -9,15 +9,18 @@ Aqui estão várias formas de se fazer isso. Você pode declarar um `example` para um modelo Pydantic usando `Config` e `schema_extra`, conforme descrito em Documentação do Pydantic: Schema customization: ```Python hl_lines="15-23" -{!../../../docs_src/schema_extra_example/tutorial001.py!} +{!../../docs_src/schema_extra_example/tutorial001.py!} ``` Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. -!!! tip "Dica" - Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada. +/// tip | Dica - Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc. +Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada. + +Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc. + +/// ## `Field` de argumentos adicionais @@ -26,11 +29,14 @@ Ao usar `Field ()` com modelos Pydantic, você também pode declarar informaçõ Você pode usar isso para adicionar um `example` para cada campo: ```Python hl_lines="4 10-13" -{!../../../docs_src/schema_extra_example/tutorial002.py!} +{!../../docs_src/schema_extra_example/tutorial002.py!} ``` -!!! warning "Atenção" - Lembre-se de que esses argumentos extras passados ​​não adicionarão nenhuma validação, apenas informações extras, para fins de documentação. +/// warning | Atenção + +Lembre-se de que esses argumentos extras passados ​​não adicionarão nenhuma validação, apenas informações extras, para fins de documentação. + +/// ## `example` e `examples` no OpenAPI @@ -51,7 +57,7 @@ você também pode declarar um dado `example` ou um grupo de `examples` com info Aqui nós passamos um `example` dos dados esperados por `Body()`: ```Python hl_lines="21-26" -{!../../../docs_src/schema_extra_example/tutorial003.py!} +{!../../docs_src/schema_extra_example/tutorial003.py!} ``` ### Exemplo na UI da documentação @@ -74,7 +80,7 @@ Cada `dict` de exemplo específico em `examples` pode conter: * `externalValue`: alternativa ao `value`, uma URL apontando para o exemplo. Embora isso possa não ser suportado por tantas ferramentas quanto `value`. ```Python hl_lines="22-48" -{!../../../docs_src/schema_extra_example/tutorial004.py!} +{!../../docs_src/schema_extra_example/tutorial004.py!} ``` ### Exemplos na UI da documentação @@ -85,10 +91,13 @@ Com `examples` adicionado a `Body()`, os `/docs` vão ficar assim: ## Detalhes técnicos -!!! warning "Atenção" - Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**. +/// warning | Atenção + +Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**. + +Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular. - Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular. +/// Quando você adiciona um exemplo dentro de um modelo Pydantic, usando `schema_extra` ou` Field(example="something") `esse exemplo é adicionado ao **JSON Schema** para esse modelo Pydantic. diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index 395621d3b..02871c90a 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -20,12 +20,17 @@ Vamos primeiro usar o código e ver como funciona, e depois voltaremos para ente Copie o exemplo em um arquivo `main.py`: ```Python -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ## Execute-o -!!! informação +/// info | informação + + + +/// + Primeiro, instale `python-multipart`. Ex: `pip install python-multipart`. @@ -52,7 +57,12 @@ Você verá algo deste tipo: -!!! marque o "botão de Autorizar!" +/// check | Botão de Autorizar! + + + +/// + Você já tem um novo "botão de autorizar!". E seu *path operation* tem um pequeno cadeado no canto superior direito que você pode clicar. @@ -61,7 +71,12 @@ E se você clicar, você terá um pequeno formulário de autorização para digi -!!! nota +/// note | Nota + + + +/// + Não importa o que você digita no formulário, não vai funcionar ainda. Mas nós vamos chegar lá. Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda sua API. @@ -104,7 +119,12 @@ Então, vamos rever de um ponto de vista simplificado: Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`. -!!! informação +/// info | informação + + + +/// + Um token "bearer" não é a única opção. Mas é a melhor no nosso caso. @@ -116,10 +136,15 @@ Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passamos pelo parâmetro `tokenUrl` Esse parâmetro contém a URL que o client (o frontend rodando no browser do usuário) vai usar para mandar o `username` e `senha` para obter um token. ```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` -!!! dica +/// tip | Dica + + + +/// + Esse `tokenUrl="token"` se refere a uma URL relativa que nós não criamos ainda. Como é uma URL relativa, é equivalente a `./token`. Porque estamos usando uma URL relativa, se sua API estava localizada em `https://example.com/`, então irá referir-se à `https://example.com/token`. Mas se sua API estava localizada em `https://example.com/api/v1/`, então irá referir-se à `https://example.com/api/v1/token`. @@ -130,7 +155,12 @@ Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL Em breve também criaremos o atual path operation. -!!! informação +/// info | informação + + + +/// + Se você é um "Pythonista" muito rigoroso, você pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`. Isso ocorre porque está utilizando o mesmo nome que está nas especificações do OpenAPI. Então, se você precisa investigar mais sobre qualquer um desses esquemas de segurança, você pode simplesmente copiar e colar para encontrar mais informações sobre isso. @@ -150,14 +180,19 @@ Então, pode ser usado com `Depends`. Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`. ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation* A **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema da OpenAPI (e na documentação da API automática). -!!! informação "Detalhes técnicos" +/// info | Detalhes técnicos + + + +/// + **FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada na dependência) para definir o esquema de segurança na OpenAPI porque herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.Securitybase`. Todos os utilitários de segurança que se integram com OpenAPI (e na documentação da API automática) herdam de `SecurityBase`, é assim que **FastAPI** pode saber como integrá-los no OpenAPI. diff --git a/docs/pt/docs/tutorial/security/index.md b/docs/pt/docs/tutorial/security/index.md index f94a8ab62..b4440ec04 100644 --- a/docs/pt/docs/tutorial/security/index.md +++ b/docs/pt/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ Não é muito popular ou usado nos dias atuais. OAuth2 não especifica como criptografar a comunicação, ele espera que você tenha sua aplicação em um servidor HTTPS. -!!! tip "Dica" - Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt. +/// tip | Dica +Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt. + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI define os seguintes esquemas de segurança: * Essa descoberta automática é o que é definido na especificação OpenID Connect. -!!! tip "Dica" - Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil. +/// tip | Dica + +Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil. + +O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você. - O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você. +/// ## **FastAPI** utilitários diff --git a/docs/pt/docs/tutorial/security/simple-oauth2.md b/docs/pt/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..4e55f8c25 --- /dev/null +++ b/docs/pt/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,539 @@ +# Simples OAuth2 com senha e Bearer + +Agora vamos construir a partir do capítulo anterior e adicionar as partes que faltam para ter um fluxo de segurança completo. + +## Pegue o `username` (nome de usuário) e `password` (senha) + +É utilizado o utils de segurança da **FastAPI** para obter o `username` e a `password`. + +OAuth2 especifica que ao usar o "password flow" (fluxo de senha), que estamos usando, o cliente/usuário deve enviar os campos `username` e `password` como dados do formulário. + +E a especificação diz que os campos devem ser nomeados assim. Portanto, `user-name` ou `email` não funcionariam. + +Mas não se preocupe, você pode mostrá-lo como quiser aos usuários finais no frontend. + +E seus modelos de banco de dados podem usar qualquer outro nome que você desejar. + +Mas para a *operação de rota* de login, precisamos usar esses nomes para serem compatíveis com a especificação (e poder, por exemplo, usar o sistema integrado de documentação da API). + +A especificação também afirma que o `username` e a `password` devem ser enviados como dados de formulário (portanto, não há JSON aqui). + +### `scope` + +A especificação também diz que o cliente pode enviar outro campo de formulário "`scope`" (Escopo). + +O nome do campo do formulário é `scope` (no singular), mas na verdade é uma longa string com "escopos" separados por espaços. + +Cada “scope” é apenas uma string (sem espaços). + +Normalmente são usados para declarar permissões de segurança específicas, por exemplo: + +* `users:read` ou `users:write` são exemplos comuns. +* `instagram_basic` é usado pelo Facebook e Instagram. +* `https://www.googleapis.com/auth/drive` é usado pelo Google. + +/// info | Informação + +No OAuth2, um "scope" é apenas uma string que declara uma permissão específica necessária. + +Não importa se tem outros caracteres como `:` ou se é uma URL. + +Esses detalhes são específicos da implementação. + +Para OAuth2 são apenas strings. + +/// + +## Código para conseguir o `username` e a `password` + +Agora vamos usar os utilitários fornecidos pelo **FastAPI** para lidar com isso. + +### `OAuth2PasswordRequestForm` + +Primeiro, importe `OAuth2PasswordRequestForm` e use-o como uma dependência com `Depends` na *operação de rota* para `/token`: + +//// tab | Python 3.10+ + +```Python hl_lines="4 78" +{!> ../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 78" +{!> ../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 79" +{!> ../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="2 74" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="4 76" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +`OAuth2PasswordRequestForm` é uma dependência de classe que declara um corpo de formulário com: + +* O `username`. +* A `password`. +* Um campo `scope` opcional como uma string grande, composta de strings separadas por espaços. +* Um `grant_type` (tipo de concessão) opcional. + +/// tip | Dica + +A especificação OAuth2 na verdade *requer* um campo `grant_type` com um valor fixo de `password`, mas `OAuth2PasswordRequestForm` não o impõe. + +Se você precisar aplicá-lo, use `OAuth2PasswordRequestFormStrict` em vez de `OAuth2PasswordRequestForm`. + +/// + +* Um `client_id` opcional (não precisamos dele em nosso exemplo). +* Um `client_secret` opcional (não precisamos dele em nosso exemplo). + +/// info | Informação + +O `OAuth2PasswordRequestForm` não é uma classe especial para **FastAPI** como é `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` faz com que **FastAPI** saiba que é um esquema de segurança. Portanto, é adicionado dessa forma ao OpenAPI. + +Mas `OAuth2PasswordRequestForm` é apenas uma dependência de classe que você mesmo poderia ter escrito ou poderia ter declarado os parâmetros do `Form` (formulário) diretamente. + +Mas como é um caso de uso comum, ele é fornecido diretamente pelo **FastAPI**, apenas para facilitar. + +/// + +### Use os dados do formulário + +/// tip | Dica + +A instância da classe de dependência `OAuth2PasswordRequestForm` não terá um atributo `scope` com a string longa separada por espaços, em vez disso, terá um atributo `scopes` com a lista real de strings para cada escopo enviado. + +Não estamos usando `scopes` neste exemplo, mas a funcionalidade está disponível se você precisar. + +/// + +Agora, obtenha os dados do usuário do banco de dados (falso), usando o `username` do campo do formulário. + +Se não existir tal usuário, retornaremos um erro dizendo "Incorrect username or password" (Nome de usuário ou senha incorretos). + +Para o erro, usamos a exceção `HTTPException`: + +//// tab | Python 3.10+ + +```Python hl_lines="3 79-81" +{!> ../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3 79-81" +{!> ../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3 80-82" +{!> ../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="1 75-77" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="3 77-79" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +### Confira a password (senha) + +Neste ponto temos os dados do usuário do nosso banco de dados, mas não verificamos a senha. + +Vamos colocar esses dados primeiro no modelo `UserInDB` do Pydantic. + +Você nunca deve salvar senhas em texto simples, portanto, usaremos o sistema de hashing de senhas (falsas). + +Se as senhas não corresponderem, retornaremos o mesmo erro. + +#### Hashing de senha + +"Hashing" significa: converter algum conteúdo (uma senha neste caso) em uma sequência de bytes (apenas uma string) que parece algo sem sentido. + +Sempre que você passa exatamente o mesmo conteúdo (exatamente a mesma senha), você obtém exatamente a mesma sequência aleatória de caracteres. + +Mas você não pode converter a sequência aleatória de caracteres de volta para a senha. + +##### Porque usar hashing de senha + +Se o seu banco de dados for roubado, o ladrão não terá as senhas em texto simples dos seus usuários, apenas os hashes. + +Assim, o ladrão não poderá tentar usar essas mesmas senhas em outro sistema (como muitos usuários usam a mesma senha em todos os lugares, isso seria perigoso). + +//// tab | Python 3.10+ + +```Python hl_lines="82-85" +{!> ../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="82-85" +{!> ../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="83-86" +{!> ../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="78-81" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="80-83" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +#### Sobre `**user_dict` + +`UserInDB(**user_dict)` significa: + +*Passe as keys (chaves) e values (valores) de `user_dict` diretamente como argumentos de valor-chave, equivalente a:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// info | Informação + +Para uma explicação mais completa de `**user_dict`, verifique [a documentação para **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}. + +/// + +## Retorne o token + +A resposta do endpoint `token` deve ser um objeto JSON. + +Deve ter um `token_type`. No nosso caso, como estamos usando tokens "Bearer", o tipo de token deve ser "`bearer`". + +E deve ter um `access_token`, com uma string contendo nosso token de acesso. + +Para este exemplo simples, seremos completamente inseguros e retornaremos o mesmo `username` do token. + +/// tip | Dica + +No próximo capítulo, você verá uma implementação realmente segura, com hash de senha e tokens JWT. + +Mas, por enquanto, vamos nos concentrar nos detalhes específicos de que precisamos. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="87" +{!> ../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="87" +{!> ../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="88" +{!> ../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="83" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="85" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +/// tip | Dica + +Pela especificação, você deve retornar um JSON com um `access_token` e um `token_type`, o mesmo que neste exemplo. + +Isso é algo que você mesmo deve fazer em seu código e certifique-se de usar essas chaves JSON. + +É quase a única coisa que você deve se lembrar de fazer corretamente, para estar em conformidade com as especificações. + +De resto, **FastAPI** cuida disso para você. + +/// + +## Atualize as dependências + +Agora vamos atualizar nossas dependências. + +Queremos obter o `user_user` *somente* se este usuário estiver ativo. + +Portanto, criamos uma dependência adicional `get_current_active_user` que por sua vez usa `get_current_user` como dependência. + +Ambas as dependências retornarão apenas um erro HTTP se o usuário não existir ou se estiver inativo. + +Portanto, em nosso endpoint, só obteremos um usuário se o usuário existir, tiver sido autenticado corretamente e estiver ativo: + +//// tab | Python 3.10+ + +```Python hl_lines="58-66 69-74 94" +{!> ../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="58-66 69-74 94" +{!> ../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="59-67 70-75 95" +{!> ../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="56-64 67-70 88" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="58-66 69-72 90" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +/// info | Informação + +O cabeçalho adicional `WWW-Authenticate` com valor `Bearer` que estamos retornando aqui também faz parte da especificação. + +Qualquer código de status HTTP (erro) 401 "UNAUTHORIZED" também deve retornar um cabeçalho `WWW-Authenticate`. + +No caso de tokens ao portador (nosso caso), o valor desse cabeçalho deve ser `Bearer`. + +Na verdade, você pode pular esse cabeçalho extra e ainda funcionaria. + +Mas é fornecido aqui para estar em conformidade com as especificações. + +Além disso, pode haver ferramentas que esperam e usam isso (agora ou no futuro) e que podem ser úteis para você ou seus usuários, agora ou no futuro. + +Esse é o benefício dos padrões... + +/// + +## Veja em ação + +Abra o docs interativo: http://127.0.0.1:8000/docs. + +### Autenticação + +Clique no botão "Authorize". + +Use as credenciais: + +User: `johndoe` + +Password: `secret` + + + +Após autenticar no sistema, você verá assim: + + + +### Obtenha seus próprios dados de usuário + +Agora use a operação `GET` com o caminho `/users/me`. + +Você obterá os dados do seu usuário, como: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +Se você clicar no ícone de cadeado, sair e tentar a mesma operação novamente, receberá um erro HTTP 401 de: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Usuário inativo + +Agora tente com um usuário inativo, autentique-se com: + +User: `alice` + +Password: `secret2` + +E tente usar a operação `GET` com o caminho `/users/me`. + +Você receberá um erro "Usuário inativo", como: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Recaptulando + +Agora você tem as ferramentas para implementar um sistema de segurança completo baseado em `username` e `password` para sua API. + +Usando essas ferramentas, você pode tornar o sistema de segurança compatível com qualquer banco de dados e com qualquer usuário ou modelo de dados. + +O único detalhe que falta é que ainda não é realmente "seguro". + +No próximo capítulo você verá como usar uma biblioteca de hashing de senha segura e tokens JWT. diff --git a/docs/pt/docs/tutorial/sql-databases.md b/docs/pt/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..3d76a532c --- /dev/null +++ b/docs/pt/docs/tutorial/sql-databases.md @@ -0,0 +1,359 @@ +# Bancos de Dados SQL (Relacionais) + +**FastAPI** não exige que você use um banco de dados SQL (relacional). Mas você pode usar **qualquer banco de dados** que quiser. + +Aqui veremos um exemplo usando SQLModel. + +**SQLModel** é construído sobre SQLAlchemy e Pydantic. Ele foi criado pelo mesmo autor do **FastAPI** para ser o par perfeito para aplicações **FastAPI** que precisam usar **bancos de dados SQL**. + +/// tip | Dica + +Você pode usar qualquer outra biblioteca de banco de dados SQL ou NoSQL que quiser (em alguns casos chamadas de "ORMs"), o FastAPI não obriga você a usar nada. 😎 + +/// + +Como o SQLModel é baseado no SQLAlchemy, você pode facilmente usar **qualquer banco de dados suportado** pelo SQLAlchemy (o que também os torna suportados pelo SQLModel), como: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server, etc. + +Neste exemplo, usaremos **SQLite**, porque ele usa um único arquivo e o Python tem suporte integrado. Assim, você pode copiar este exemplo e executá-lo como está. + +Mais tarde, para sua aplicação em produção, você pode querer usar um servidor de banco de dados como o **PostgreSQL**. + +/// tip | Dica + +Existe um gerador de projetos oficial com **FastAPI** e **PostgreSQL** incluindo um frontend e mais ferramentas: https://github.com/fastapi/full-stack-fastapi-template + +/// + +Este é um tutorial muito simples e curto, se você quiser aprender sobre bancos de dados em geral, sobre SQL ou recursos mais avançados, acesse a documentação do SQLModel. + +## Instalar o `SQLModel` + +Primeiro, certifique-se de criar seu [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e, em seguida, instalar o `sqlmodel`: + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## Criar o App com um Único Modelo + +Vamos criar a primeira versão mais simples do app com um único modelo **SQLModel**. + +Depois, vamos melhorá-lo aumentando a segurança e versatilidade com **múltiplos modelos** abaixo. 🤓 + +### Criar Modelos + +Importe o `SQLModel` e crie um modelo de banco de dados: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +A classe `Hero` é muito semelhante a um modelo Pydantic (na verdade, por baixo dos panos, ela *é um modelo Pydantic*). + +Existem algumas diferenças: + +* `table=True` informa ao SQLModel que este é um *modelo de tabela*, ele deve representar uma **tabela** no banco de dados SQL, não é apenas um *modelo de dados* (como seria qualquer outra classe Pydantic comum). + +* `Field(primary_key=True)` informa ao SQLModel que o `id` é a **chave primária** no banco de dados SQL (você pode aprender mais sobre chaves primárias SQL na documentação do SQLModel). + + Ao ter o tipo como `int | None`, o SQLModel saberá que essa coluna deve ser um `INTEGER` no banco de dados SQL e que ela deve ser `NULLABLE`. + +* `Field(index=True)` informa ao SQLModel que ele deve criar um **índice SQL** para essa coluna, o que permitirá buscas mais rápidas no banco de dados ao ler dados filtrados por essa coluna. + + O SQLModel saberá que algo declarado como `str` será uma coluna SQL do tipo `TEXT` (ou `VARCHAR`, dependendo do banco de dados). + +### Criar um Engine +Um `engine` SQLModel (por baixo dos panos, ele é na verdade um `engine` do SQLAlchemy) é o que **mantém as conexões** com o banco de dados. + +Você teria **um único objeto `engine`** para todo o seu código se conectar ao mesmo banco de dados. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +Usar `check_same_thread=False` permite que o FastAPI use o mesmo banco de dados SQLite em diferentes threads. Isso é necessário, pois **uma única requisição** pode usar **mais de uma thread** (por exemplo, em dependências). + +Não se preocupe, com a forma como o código está estruturado, garantiremos que usamos **uma única *sessão* SQLModel por requisição** mais tarde, isso é realmente o que o `check_same_thread` está tentando conseguir. + +### Criar as Tabelas + +Em seguida, adicionamos uma função que usa `SQLModel.metadata.create_all(engine)` para **criar as tabelas** para todos os *modelos de tabela*. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### Criar uma Dependência de Sessão + +Uma **`Session`** é o que armazena os **objetos na memória** e acompanha as alterações necessárias nos dados, para então **usar o `engine`** para se comunicar com o banco de dados. + +Vamos criar uma **dependência** do FastAPI com `yield` que fornecerá uma nova `Session` para cada requisição. Isso é o que garante que usamos uma única sessão por requisição. 🤓 + +Então, criamos uma dependência `Annotated` chamada `SessionDep` para simplificar o restante do código que usará essa dependência. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### Criar Tabelas de Banco de Dados na Inicialização + +Vamos criar as tabelas do banco de dados quando o aplicativo for iniciado. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +Aqui, criamos as tabelas em um evento de inicialização do aplicativo. + +Para produção, você provavelmente usaria um script de migração que é executado antes de iniciar seu app. 🤓 + +/// tip | Dica + +O SQLModel terá utilitários de migração envolvendo o Alembic, mas por enquanto, você pode usar o Alembic diretamente. + +/// + +### Criar um Hero + +Como cada modelo SQLModel também é um modelo Pydantic, você pode usá-lo nas mesmas **anotações de tipo** que usaria para modelos Pydantic. + +Por exemplo, se você declarar um parâmetro do tipo `Hero`, ele será lido do **corpo JSON**. + +Da mesma forma, você pode declará-lo como o **tipo de retorno** da função, e então o formato dos dados aparecerá na interface de documentação automática da API. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + +
+ +Aqui, usamos a dependência `SessionDep` (uma `Session`) para adicionar o novo `Hero` à instância `Session`, fazer commit das alterações no banco de dados, atualizar os dados no `hero` e então retorná-lo. + +### Ler Heroes + +Podemos **ler** `Hero`s do banco de dados usando um `select()`. Podemos incluir um `limit` e `offset` para paginar os resultados. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### Ler um Único Hero + +Podemos **ler** um único `Hero`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### Deletar um Hero + +Também podemos **deletar** um `Hero`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### Executar o App + +Você pode executar o app: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Então, vá para a interface `/docs`, você verá que o **FastAPI** está usando esses **modelos** para **documentar** a API, e ele também os usará para **serializar** e **validar** os dados. + +
+ +
+ +## Atualizar o App com Múltiplos Modelos + +Agora vamos **refatorar** este app um pouco para aumentar a **segurança** e **versatilidade**. + +Se você verificar o app anterior, na interface você pode ver que, até agora, ele permite que o cliente decida o `id` do `Hero` a ser criado. 😱 + +Não deveríamos deixar isso acontecer, eles poderiam sobrescrever um `id` que já atribuimos na base de dados. Decidir o `id` deve ser feito pelo **backend** ou pelo **banco de dados**, **não pelo cliente**. + +Além disso, criamos um `secret_name` para o hero, mas até agora estamos retornando ele em todos os lugares, isso não é muito **secreto**... 😅 + +Vamos corrigir essas coisas adicionando alguns **modelos extras**. Aqui é onde o SQLModel vai brilhar. ✨ + +### Criar Múltiplos Modelos + +No **SQLModel**, qualquer classe de modelo que tenha `table=True` é um **modelo de tabela**. + +E qualquer classe de modelo que não tenha `table=True` é um **modelo de dados**, esses são na verdade apenas modelos Pydantic (com alguns recursos extras pequenos). 🤓 + +Com o SQLModel, podemos usar a **herança** para **evitar duplicação** de todos os campos em todos os casos. + +#### `HeroBase` - a classe base + +Vamos começar com um modelo `HeroBase` que tem todos os **campos compartilhados** por todos os modelos: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### `Hero` - o *modelo de tabela* + +Em seguida, vamos criar `Hero`, o verdadeiro *modelo de tabela*, com os **campos extras** que nem sempre estão nos outros modelos: + +* `id` +* `secret_name` + +Como `Hero` herda de `HeroBase`, ele **também** tem os **campos** declarados em `HeroBase`, então todos os campos para `Hero` são: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### `HeroPublic` - o *modelo de dados* público + +Em seguida, criamos um modelo `HeroPublic`, que será **retornado** para os clientes da API. + +Ele tem os mesmos campos que `HeroBase`, então não incluirá `secret_name`. + +Finalmente, a identidade dos nossos heróis está protegida! 🥷 + +Ele também declara novamente `id: int`. Ao fazer isso, estamos fazendo um **contrato** com os clientes da API, para que eles possam sempre esperar que o `id` estará lá e será um `int` (nunca será `None`). + +/// tip | Dica + +Fazer com que o modelo de retorno garanta que um valor esteja sempre disponível e sempre seja um `int` (não `None`) é muito útil para os clientes da API, eles podem escrever código muito mais simples com essa certeza. + +Além disso, **clientes gerados automaticamente** terão interfaces mais simples, para que os desenvolvedores que se comunicam com sua API possam ter uma experiência muito melhor trabalhando com sua API. 😎 + +/// + +Todos os campos em `HeroPublic` são os mesmos que em `HeroBase`, com `id` declarado como `int` (não `None`): + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### `HeroCreate` - o *modelo de dados* para criar um hero + +Agora criamos um modelo `HeroCreate`, este é o que **validará** os dados dos clientes. + +Ele tem os mesmos campos que `HeroBase`, e também tem `secret_name`. + +Agora, quando os clientes **criarem um novo hero**, eles enviarão o `secret_name`, ele será armazenado no banco de dados, mas esses nomes secretos não serão retornados na API para os clientes. + +/// tip | Dica + +É assim que você trataria **senhas**. Receba-as, mas não as retorne na API. + +Você também faria um **hash** com os valores das senhas antes de armazená-los, **nunca os armazene em texto simples**. + +/// + +Os campos de `HeroCreate` são: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### `HeroUpdate` - o *modelo de dados* para atualizar um hero + +Não tínhamos uma maneira de **atualizar um hero** na versão anterior do app, mas agora com **múltiplos modelos**, podemos fazer isso. 🎉 + +O *modelo de dados* `HeroUpdate` é um pouco especial, ele tem **todos os mesmos campos** que seriam necessários para criar um novo hero, mas todos os campos são **opcionais** (todos têm um valor padrão). Dessa forma, quando você atualizar um hero, poderá enviar apenas os campos que deseja atualizar. + +Como todos os **campos realmente mudam** (o tipo agora inclui `None` e eles agora têm um valor padrão de `None`), precisamos **declarar novamente** todos eles. + +Não precisamos herdar de `HeroBase`, pois estamos redeclarando todos os campos. Vou deixá-lo herdando apenas por consistência, mas isso não é necessário. É mais uma questão de gosto pessoal. 🤷 + +Os campos de `HeroUpdate` são: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### Criar com `HeroCreate` e retornar um `HeroPublic` + +Agora que temos **múltiplos modelos**, podemos atualizar as partes do app que os utilizam. + +Recebemos na requisição um *modelo de dados* `HeroCreate`, e a partir dele, criamos um *modelo de tabela* `Hero`. + +Esse novo *modelo de tabela* `Hero` terá os campos enviados pelo cliente, e também terá um `id` gerado pelo banco de dados. + +Em seguida, retornamos o mesmo *modelo de tabela* `Hero` como está na função. Mas como declaramos o `response_model` com o *modelo de dados* `HeroPublic`, o **FastAPI** usará `HeroPublic` para validar e serializar os dados. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip | Dica + +Agora usamos `response_model=HeroPublic` em vez da **anotação de tipo de retorno** `-> HeroPublic` porque o valor que estamos retornando na verdade *não* é um `HeroPublic`. + +Se tivéssemos declarado `-> HeroPublic`, seu editor e o linter reclamariam (com razão) que você está retornando um `Hero` em vez de um `HeroPublic`. + +Ao declará-lo no `response_model`, estamos dizendo ao **FastAPI** para fazer o seu trabalho, sem interferir nas anotações de tipo e na ajuda do seu editor e de outras ferramentas. + +/// + +### Ler Heroes com `HeroPublic` + +Podemos fazer o mesmo que antes para **ler** `Hero`s, novamente, usamos `response_model=list[HeroPublic]` para garantir que os dados sejam validados e serializados corretamente. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### Ler Um Hero com `HeroPublic` + +Podemos **ler** um único herói: + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### Atualizar um Hero com `HeroUpdate` + +Podemos **atualizar um hero**. Para isso, usamos uma operação HTTP `PATCH`. + +E no código, obtemos um `dict` com todos os dados enviados pelo cliente, **apenas os dados enviados pelo cliente**, excluindo quaisquer valores que estariam lá apenas por serem os valores padrão. Para fazer isso, usamos `exclude_unset=True`. Este é o truque principal. 🪄 + +Em seguida, usamos `hero_db.sqlmodel_update(hero_data)` para atualizar o `hero_db` com os dados de `hero_data`. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### Deletar um Hero Novamente + +**Deletar** um hero permanece praticamente o mesmo. + +Não vamos satisfazer o desejo de refatorar tudo neste aqui. 😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### Executar o App Novamente + +Você pode executar o app novamente: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +If you go to the `/docs` API UI, you will see that it is now updated, and it won't expect to receive the `id` from the client when creating a hero, etc. + +
+ +
+ +## Recapitulando + +Você pode usar **SQLModel** para interagir com um banco de dados SQL e simplificar o código com *modelos de dados* e *modelos de tabela*. + +Você pode aprender muito mais na documentação do **SQLModel**, há um mini tutorial sobre como usar SQLModel com **FastAPI** mais longo. 🚀 diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md index 009158fc6..aba4b8221 100644 --- a/docs/pt/docs/tutorial/static-files.md +++ b/docs/pt/docs/tutorial/static-files.md @@ -8,13 +8,16 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S * "Monte" uma instância de `StaticFiles()` em um caminho específico. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` -!!! note "Detalhes técnicos" - Você também pode usar `from starlette.staticfiles import StaticFiles`. +/// note | Detalhes técnicos - O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette. +Você também pode usar `from starlette.staticfiles import StaticFiles`. + +O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette. + +/// ### O que é "Montagem" diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md new file mode 100644 index 000000000..4f8eaa299 --- /dev/null +++ b/docs/pt/docs/tutorial/testing.md @@ -0,0 +1,249 @@ +# Testando + +Graças ao Starlette, testar aplicativos **FastAPI** é fácil e agradável. + +Ele é baseado no HTTPX, que por sua vez é projetado com base em Requests, por isso é muito familiar e intuitivo. + +Com ele, você pode usar o pytest diretamente com **FastAPI**. + +## Usando `TestClient` + +/// info | Informação + +Para usar o `TestClient`, primeiro instale o `httpx`. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e instalá-lo, por exemplo: + +```console +$ pip install httpx +``` + +/// + +Importe `TestClient`. + +Crie um `TestClient` passando seu aplicativo **FastAPI** para ele. + +Crie funções com um nome que comece com `test_` (essa é a convenção padrão do `pytest`). + +Use o objeto `TestClient` da mesma forma que você faz com `httpx`. + +Escreva instruções `assert` simples com as expressões Python padrão que você precisa verificar (novamente, `pytest` padrão). + +```Python hl_lines="2 12 15-18" +{!../../docs_src/app_testing/tutorial001.py!} +``` + +/// tip | Dica + +Observe que as funções de teste são `def` normais, não `async def`. + +E as chamadas para o cliente também são chamadas normais, não usando `await`. + +Isso permite que você use `pytest` diretamente sem complicações. + +/// + +/// note | Detalhes técnicos + +Você também pode usar `from starlette.testclient import TestClient`. + +**FastAPI** fornece o mesmo `starlette.testclient` que `fastapi.testclient` apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente da Starlette. + +/// + +/// tip | Dica + +Se você quiser chamar funções `async` em seus testes além de enviar solicitações ao seu aplicativo FastAPI (por exemplo, funções de banco de dados assíncronas), dê uma olhada em [Testes assíncronos](../advanced/async-tests.md){.internal-link target=_blank} no tutorial avançado. + +/// + +## Separando testes + +Em uma aplicação real, você provavelmente teria seus testes em um arquivo diferente. + +E seu aplicativo **FastAPI** também pode ser composto de vários arquivos/módulos, etc. + +### Arquivo do aplicativo **FastAPI** + +Digamos que você tenha uma estrutura de arquivo conforme descrito em [Aplicativos maiores](bigger-applications.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +No arquivo `main.py` você tem seu aplicativo **FastAPI**: + + +```Python +{!../../docs_src/app_testing/main.py!} +``` + +### Arquivo de teste + +Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia estar no mesmo pacote Python (o mesmo diretório com um arquivo `__init__.py`): + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Como esse arquivo está no mesmo pacote, você pode usar importações relativas para importar o objeto `app` do módulo `main` (`main.py`): + +```Python hl_lines="3" +{!../../docs_src/app_testing/test_main.py!} +``` + +...e ter o código para os testes como antes. + +## Testando: exemplo estendido + +Agora vamos estender este exemplo e adicionar mais detalhes para ver como testar diferentes partes. + +### Arquivo de aplicativo **FastAPI** estendido + +Vamos continuar com a mesma estrutura de arquivo de antes: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Digamos que agora o arquivo `main.py` com seu aplicativo **FastAPI** tenha algumas outras **operações de rotas**. + +Ele tem uma operação `GET` que pode retornar um erro. + +Ele tem uma operação `POST` que pode retornar vários erros. + +Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated` se possível. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated` se possível. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### Arquivo de teste estendido + +Você pode então atualizar `test_main.py` com os testes estendidos: + +```Python +{!> ../../docs_src/app_testing/app_b/test_main.py!} +``` + +Sempre que você precisar que o cliente passe informações na requisição e não souber como, você pode pesquisar (no Google) como fazer isso no `httpx`, ou até mesmo como fazer isso com `requests`, já que o design do HTTPX é baseado no design do Requests. + +Depois é só fazer o mesmo nos seus testes. + +Por exemplo: + +* Para passar um parâmetro *path* ou *query*, adicione-o à própria URL. +* Para passar um corpo JSON, passe um objeto Python (por exemplo, um `dict`) para o parâmetro `json`. +* Se você precisar enviar *Dados de Formulário* em vez de JSON, use o parâmetro `data`. +* Para passar *headers*, use um `dict` no parâmetro `headers`. +* Para *cookies*, um `dict` no parâmetro `cookies`. + +Para mais informações sobre como passar dados para o backend (usando `httpx` ou `TestClient`), consulte a documentação do HTTPX. + +/// info | Informação + +Observe que o `TestClient` recebe dados que podem ser convertidos para JSON, não para modelos Pydantic. + +Se você tiver um modelo Pydantic em seu teste e quiser enviar seus dados para o aplicativo durante o teste, poderá usar o `jsonable_encoder` descrito em [Codificador compatível com JSON](encoder.md){.internal-link target=_blank}. + +/// + +## Execute-o + +Depois disso, você só precisa instalar o `pytest`. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e instalá-lo, por exemplo: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +Ele detectará os arquivos e os testes automaticamente, os executará e informará os resultados para você. + +Execute os testes com: + +
+ +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
diff --git a/docs/pt/docs/virtual-environments.md b/docs/pt/docs/virtual-environments.md new file mode 100644 index 000000000..5fc1a8866 --- /dev/null +++ b/docs/pt/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# Ambientes Virtuais + +Ao trabalhar em projetos Python, você provavelmente deve usar um **ambiente virtual** (ou um mecanismo similar) para isolar os pacotes que você instala para cada projeto. + +/// info | Informação + +Se você já sabe sobre ambientes virtuais, como criá-los e usá-los, talvez seja melhor pular esta seção. 🤓 + +/// + +/// tip | Dica + +Um **ambiente virtual** é diferente de uma **variável de ambiente**. + +Uma **variável de ambiente** é uma variável no sistema que pode ser usada por programas. + +Um **ambiente virtual** é um diretório com alguns arquivos. + +/// + +/// info | Informação + +Esta página lhe ensinará como usar **ambientes virtuais** e como eles funcionam. + +Se você estiver pronto para adotar uma **ferramenta que gerencia tudo** para você (incluindo a instalação do Python), experimente uv. + +/// + +## Criar um Projeto + +Primeiro, crie um diretório para seu projeto. + +O que normalmente faço é criar um diretório chamado `code` dentro do meu diretório home/user. + +E dentro disso eu crio um diretório por projeto. + +
+ +```console +// Vá para o diretório inicial +$ cd +// Crie um diretório para todos os seus projetos de código +$ mkdir code +// Entre nesse diretório de código +$ cd code +// Crie um diretório para este projeto +$ mkdir awesome-project +// Entre no diretório do projeto +$ cd awesome-project +``` + +
+ +## Crie um ambiente virtual + +Ao começar a trabalhar em um projeto Python **pela primeira vez**, crie um ambiente virtual **dentro do seu projeto**. + +/// tip | Dica + +Você só precisa fazer isso **uma vez por projeto**, não toda vez que trabalhar. + +/// + +//// tab | `venv` + +Para criar um ambiente virtual, você pode usar o módulo `venv` que vem com o Python. + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | O que esse comando significa + +* `python`: usa o programa chamado `python` +* `-m`: chama um módulo como um script, nós diremos a ele qual módulo vem em seguida +* `venv`: usa o módulo chamado `venv` que normalmente vem instalado com o Python +* `.venv`: cria o ambiente virtual no novo diretório `.venv` + +/// + +//// + +//// tab | `uv` + +Se você tiver o `uv` instalado, poderá usá-lo para criar um ambiente virtual. + +
+ +```console +$ uv venv +``` + +
+ +/// tip | Dica + +Por padrão, `uv` criará um ambiente virtual em um diretório chamado `.venv`. + +Mas você pode personalizá-lo passando um argumento adicional com o nome do diretório. + +/// + +//// + +Esse comando cria um novo ambiente virtual em um diretório chamado `.venv`. + +/// details | `.venv` ou outro nome + +Você pode criar o ambiente virtual em um diretório diferente, mas há uma convenção para chamá-lo de `.venv`. + +/// + +## Ative o ambiente virtual + +Ative o novo ambiente virtual para que qualquer comando Python que você executar ou pacote que você instalar o utilize. + +/// tip | Dica + +Faça isso **toda vez** que iniciar uma **nova sessão de terminal** para trabalhar no projeto. + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Ou se você usa o Bash para Windows (por exemplo, Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip | Dica + +Toda vez que você instalar um **novo pacote** naquele ambiente, **ative** o ambiente novamente. + +Isso garante que, se você usar um **programa de terminal (CLI)** instalado por esse pacote, você usará aquele do seu ambiente virtual e não qualquer outro que possa ser instalado globalmente, provavelmente com uma versão diferente do que você precisa. + +/// + +## Verifique se o ambiente virtual está ativo + +Verifique se o ambiente virtual está ativo (o comando anterior funcionou). + +/// tip | Dica + +Isso é **opcional**, mas é uma boa maneira de **verificar** se tudo está funcionando conforme o esperado e se você está usando o ambiente virtual pretendido. + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +Se ele mostrar o binário `python` em `.venv/bin/python`, dentro do seu projeto (neste caso `awesome-project`), então funcionou. 🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +Se ele mostrar o binário `python` em `.venv\Scripts\python`, dentro do seu projeto (neste caso `awesome-project`), então funcionou. 🎉 + +//// + +## Atualizar `pip` + +/// tip | Dica + +Se você usar `uv`, você o usará para instalar coisas em vez do `pip`, então não precisará atualizar o `pip`. 😎 + +/// + +Se você estiver usando `pip` para instalar pacotes (ele vem por padrão com o Python), você deve **atualizá-lo** para a versão mais recente. + +Muitos erros exóticos durante a instalação de um pacote são resolvidos apenas atualizando o `pip` primeiro. + +/// tip | Dica + +Normalmente, você faria isso **uma vez**, logo após criar o ambiente virtual. + +/// + +Certifique-se de que o ambiente virtual esteja ativo (com o comando acima) e execute: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## Adicionar `.gitignore` + +Se você estiver usando **Git** (você deveria), adicione um arquivo `.gitignore` para excluir tudo em seu `.venv` do Git. + +/// tip | Dica + +Se você usou `uv` para criar o ambiente virtual, ele já fez isso para você, você pode pular esta etapa. 😎 + +/// + +/// tip | Dica + +Faça isso **uma vez**, logo após criar o ambiente virtual. + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | O que esse comando significa + +* `echo "*"`: irá "imprimir" o texto `*` no terminal (a próxima parte muda isso um pouco) +* `>`: qualquer coisa impressa no terminal pelo comando à esquerda de `>` não deve ser impressa, mas sim escrita no arquivo que vai à direita de `>` +* `.gitignore`: o nome do arquivo onde o texto deve ser escrito + +E `*` para Git significa "tudo". Então, ele ignorará tudo no diretório `.venv`. + +Esse comando criará um arquivo `.gitignore` com o conteúdo: + +```gitignore +* +``` + +/// + +## Instalar Pacotes + +Após ativar o ambiente, você pode instalar pacotes nele. + +/// tip | Dica + +Faça isso **uma vez** ao instalar ou atualizar os pacotes que seu projeto precisa. + +Se precisar atualizar uma versão ou adicionar um novo pacote, você **fará isso novamente**. + +/// + +### Instalar pacotes diretamente + +Se estiver com pressa e não quiser usar um arquivo para declarar os requisitos de pacote do seu projeto, você pode instalá-los diretamente. + +/// tip | Dica + +É uma (muito) boa ideia colocar os pacotes e versões que seu programa precisa em um arquivo (por exemplo `requirements.txt` ou `pyproject.toml`). + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Se você tem o `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### Instalar a partir de `requirements.txt` + +Se você tiver um `requirements.txt`, agora poderá usá-lo para instalar seus pacotes. + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Se você tem o `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +Um `requirements.txt` com alguns pacotes poderia se parecer com: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Execute seu programa + +Depois de ativar o ambiente virtual, você pode executar seu programa, e ele usará o Python dentro do seu ambiente virtual com os pacotes que você instalou lá. + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## Configure seu editor + +Você provavelmente usaria um editor. Certifique-se de configurá-lo para usar o mesmo ambiente virtual que você criou (ele provavelmente o detectará automaticamente) para que você possa obter erros de preenchimento automático e em linha. + +Por exemplo: + +* VS Code +* PyCharm + +/// tip | Dica + +Normalmente, você só precisa fazer isso **uma vez**, ao criar o ambiente virtual. + +/// + +## Desativar o ambiente virtual + +Quando terminar de trabalhar no seu projeto, você pode **desativar** o ambiente virtual. + +
+ +```console +$ deactivate +``` + +
+ +Dessa forma, quando você executar `python`, ele não tentará executá-lo naquele ambiente virtual com os pacotes instalados nele. + +## Pronto para trabalhar + +Agora você está pronto para começar a trabalhar no seu projeto. + + + +/// tip | Dica + +Você quer entender o que é tudo isso acima? + +Continue lendo. 👇🤓 + +/// + +## Por que ambientes virtuais + +Para trabalhar com o FastAPI, você precisa instalar o Python. + +Depois disso, você precisará **instalar** o FastAPI e quaisquer outros **pacotes** que queira usar. + +Para instalar pacotes, você normalmente usaria o comando `pip` que vem com o Python (ou alternativas semelhantes). + +No entanto, se você usar `pip` diretamente, os pacotes serão instalados no seu **ambiente Python global** (a instalação global do Python). + +### O Problema + +Então, qual é o problema em instalar pacotes no ambiente global do Python? + +Em algum momento, você provavelmente acabará escrevendo muitos programas diferentes que dependem de **pacotes diferentes**. E alguns desses projetos em que você trabalha dependerão de **versões diferentes** do mesmo pacote. 😱 + +Por exemplo, você pode criar um projeto chamado `philosophers-stone`, este programa depende de outro pacote chamado **`harry`, usando a versão `1`**. Então, você precisa instalar `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +Então, em algum momento depois, você cria outro projeto chamado `prisoner-of-azkaban`, e esse projeto também depende de `harry`, mas esse projeto precisa do **`harry` versão `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +Mas agora o problema é que, se você instalar os pacotes globalmente (no ambiente global) em vez de em um **ambiente virtual** local, você terá que escolher qual versão do `harry` instalar. + +Se você quiser executar `philosophers-stone`, precisará primeiro instalar `harry` versão `1`, por exemplo com: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +E então você acabaria com `harry` versão `1` instalado em seu ambiente Python global. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +Mas se você quiser executar `prisoner-of-azkaban`, você precisará desinstalar `harry` versão `1` e instalar `harry` versão `3` (ou apenas instalar a versão `3` desinstalaria automaticamente a versão `1`). + +
+ +```console +$ pip install "harry==3" +``` + +
+ +E então você acabaria com `harry` versão `3` instalado em seu ambiente Python global. + +E se você tentar executar `philosophers-stone` novamente, há uma chance de que **não funcione** porque ele precisa de `harry` versão `1`. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip | Dica + +É muito comum em pacotes Python tentar ao máximo **evitar alterações drásticas** em **novas versões**, mas é melhor prevenir do que remediar e instalar versões mais recentes intencionalmente e, quando possível, executar os testes para verificar se tudo está funcionando corretamente. + +/// + +Agora, imagine isso com **muitos** outros **pacotes** dos quais todos os seus **projetos dependem**. Isso é muito difícil de gerenciar. E você provavelmente acabaria executando alguns projetos com algumas **versões incompatíveis** dos pacotes, e não saberia por que algo não está funcionando. + +Além disso, dependendo do seu sistema operacional (por exemplo, Linux, Windows, macOS), ele pode ter vindo com o Python já instalado. E, nesse caso, provavelmente tinha alguns pacotes pré-instalados com algumas versões específicas **necessárias para o seu sistema**. Se você instalar pacotes no ambiente global do Python, poderá acabar **quebrando** alguns dos programas que vieram com seu sistema operacional. + +## Onde os pacotes são instalados + +Quando você instala o Python, ele cria alguns diretórios com alguns arquivos no seu computador. + +Alguns desses diretórios são os responsáveis ​​por ter todos os pacotes que você instala. + +Quando você executa: + +
+ +```console +// Não execute isso agora, é apenas um exemplo 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +Isso fará o download de um arquivo compactado com o código FastAPI, normalmente do PyPI. + +Ele também fará o **download** de arquivos para outros pacotes dos quais o FastAPI depende. + +Em seguida, ele **extrairá** todos esses arquivos e os colocará em um diretório no seu computador. + +Por padrão, ele colocará os arquivos baixados e extraídos no diretório que vem com a instalação do Python, que é o **ambiente global**. + +## O que são ambientes virtuais + +A solução para os problemas de ter todos os pacotes no ambiente global é usar um **ambiente virtual para cada projeto** em que você trabalha. + +Um ambiente virtual é um **diretório**, muito semelhante ao global, onde você pode instalar os pacotes para um projeto. + +Dessa forma, cada projeto terá seu próprio ambiente virtual (diretório `.venv`) com seus próprios pacotes. + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## O que significa ativar um ambiente virtual + +Quando você ativa um ambiente virtual, por exemplo com: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Ou se você usa o Bash para Windows (por exemplo, Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +Esse comando criará ou modificará algumas [variáveis ​​de ambiente](environment-variables.md){.internal-link target=_blank} que estarão disponíveis para os próximos comandos. + +Uma dessas variáveis ​​é a variável `PATH`. + +/// tip | Dica + +Você pode aprender mais sobre a variável de ambiente `PATH` na seção [Variáveis ​​de ambiente](environment-variables.md#path-environment-variable){.internal-link target=_blank}. + +/// + +A ativação de um ambiente virtual adiciona seu caminho `.venv/bin` (no Linux e macOS) ou `.venv\Scripts` (no Windows) à variável de ambiente `PATH`. + +Digamos que antes de ativar o ambiente, a variável `PATH` estava assim: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +Isso significa que o sistema procuraria programas em: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +Isso significa que o sistema procuraria programas em: + +* `C:\Windows\System32` + +//// + +Após ativar o ambiente virtual, a variável `PATH` ficaria mais ou menos assim: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Isso significa que o sistema agora começará a procurar primeiro por programas em: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +antes de procurar nos outros diretórios. + +Então, quando você digita `python` no terminal, o sistema encontrará o programa Python em + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +e usa esse. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +Isso significa que o sistema agora começará a procurar primeiro por programas em: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +antes de procurar nos outros diretórios. + +Então, quando você digita `python` no terminal, o sistema encontrará o programa Python em + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +e usa esse. + +//// + +Um detalhe importante é que ele colocará o caminho do ambiente virtual no **início** da variável `PATH`. O sistema o encontrará **antes** de encontrar qualquer outro Python disponível. Dessa forma, quando você executar `python`, ele usará o Python **do ambiente virtual** em vez de qualquer outro `python` (por exemplo, um `python` de um ambiente global). + +Ativar um ambiente virtual também muda algumas outras coisas, mas esta é uma das mais importantes. + +## Verificando um ambiente virtual + +Ao verificar se um ambiente virtual está ativo, por exemplo com: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +Isso significa que o programa `python` que será usado é aquele **no ambiente virtual**. + +você usa `which` no Linux e macOS e `Get-Command` no Windows PowerShell. + +A maneira como esse comando funciona é que ele vai e verifica na variável de ambiente `PATH`, passando por **cada caminho em ordem**, procurando pelo programa chamado `python`. Uma vez que ele o encontre, ele **mostrará o caminho** para esse programa. + +A parte mais importante é que quando você chama ``python`, esse é exatamente o "`python`" que será executado. + +Assim, você pode confirmar se está no ambiente virtual correto. + +/// tip | Dica + +É fácil ativar um ambiente virtual, obter um Python e então **ir para outro projeto**. + +E o segundo projeto **não funcionaria** porque você está usando o **Python incorreto**, de um ambiente virtual para outro projeto. + +É útil poder verificar qual `python` está sendo usado. 🤓 + +/// + +## Por que desativar um ambiente virtual + +Por exemplo, você pode estar trabalhando em um projeto `philosophers-stone`, **ativar esse ambiente virtual**, instalar pacotes e trabalhar com esse ambiente. + +E então você quer trabalhar em **outro projeto** `prisoner-of-azkaban`. + +Você vai para aquele projeto: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +Se você não desativar o ambiente virtual para `philosophers-stone`, quando você executar `python` no terminal, ele tentará usar o Python de `philosophers-stone`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Erro ao importar o Sirius, ele não está instalado 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +Mas se você desativar o ambiente virtual e ativar o novo para `prisoner-of-askaban`, quando você executar `python`, ele usará o Python do ambiente virtual em `prisoner-of-azkaban`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// Você não precisa estar no diretório antigo para desativar, você pode fazer isso de onde estiver, mesmo depois de ir para o outro projeto 😎 +$ deactivate + +// Ative o ambiente virtual em prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Agora, quando você executar o python, ele encontrará o pacote sirius instalado neste ambiente virtual ✨ +$ python main.py + +Eu juro solenemente 🐺 +``` + +
+ +## Alternativas + +Este é um guia simples para você começar e lhe ensinar como tudo funciona **por baixo**. + +Existem muitas **alternativas** para gerenciar ambientes virtuais, dependências de pacotes (requisitos) e projetos. + +Quando estiver pronto e quiser usar uma ferramenta para **gerenciar todo o projeto**, dependências de pacotes, ambientes virtuais, etc., sugiro que você experimente o uv. + +`uv` pode fazer muitas coisas, ele pode: + +* **Instalar o Python** para você, incluindo versões diferentes +* Gerenciar o **ambiente virtual** para seus projetos +* Instalar **pacotes** +* Gerenciar **dependências e versões** de pacotes para seu projeto +* Certifique-se de ter um conjunto **exato** de pacotes e versões para instalar, incluindo suas dependências, para que você possa ter certeza de que pode executar seu projeto em produção exatamente da mesma forma que em seu computador durante o desenvolvimento, isso é chamado de **bloqueio** +* E muitas outras coisas + +## Conclusão + +Se você leu e entendeu tudo isso, agora **você sabe muito mais** sobre ambientes virtuais do que muitos desenvolvedores por aí. 🤓 + +Saber esses detalhes provavelmente será útil no futuro, quando você estiver depurando algo que parece complexo, mas você saberá **como tudo funciona**. 😎 diff --git a/docs/ru/docs/about/index.md b/docs/ru/docs/about/index.md new file mode 100644 index 000000000..1015b667a --- /dev/null +++ b/docs/ru/docs/about/index.md @@ -0,0 +1,3 @@ +# О проекте + +FastAPI: внутреннее устройство, повлиявшие технологии и всё такое прочее. 🤓 diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md index 24a45fa55..3c5147e79 100644 --- a/docs/ru/docs/alternatives.md +++ b/docs/ru/docs/alternatives.md @@ -33,12 +33,18 @@ DRF использовался многими компаниями, включа Это был один из первых примеров **автоматического документирования API** и это была одна из первых идей, вдохновивших на создание **FastAPI**. -!!! note "Заметка" - Django REST Framework был создан Tom Christie. - Он же создал Starlette и Uvicorn, на которых основан **FastAPI**. +/// note | Заметка -!!! check "Идея для **FastAPI**" - Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом. +Django REST Framework был создан Tom Christie. +Он же создал Starlette и Uvicorn, на которых основан **FastAPI**. + +/// + +/// check | Идея для **FastAPI** + +Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом. + +/// ### Flask @@ -56,11 +62,13 @@ Flask часто используется и для приложений, кот Простота Flask, показалась мне подходящей для создания API. Но ещё нужно было найти "Django REST Framework" для Flask. -!!! check "Идеи для **FastAPI**" - Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части. +/// check | Идеи для **FastAPI** + +Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части. - Должна быть простая и лёгкая в использовании система маршрутизации запросов. +Должна быть простая и лёгкая в использовании система маршрутизации запросов. +/// ### Requests @@ -100,11 +108,13 @@ def read_url(): Глядите, как похоже `requests.get(...)` и `@app.get(...)`. -!!! check "Идеи для **FastAPI**" - * Должен быть простой и понятный API. - * Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего. - * Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации. +/// check | Идеи для **FastAPI** + +* Должен быть простой и понятный API. +* Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего. +* Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации. +/// ### Swagger / OpenAPI @@ -119,16 +129,19 @@ def read_url(): Вот почему, когда говорят о версии 2.0, обычно говорят "Swagger", а для версии 3+ "OpenAPI". -!!! check "Идеи для **FastAPI**" - Использовать открытые стандарты для спецификаций API вместо самодельных схем. +/// check | Идеи для **FastAPI** - Совместимость с основанными на стандартах пользовательскими интерфейсами: +Использовать открытые стандарты для спецификаций API вместо самодельных схем. - * Swagger UI - * ReDoc +Совместимость с основанными на стандартах пользовательскими интерфейсами: - Они были выбраны за популярность и стабильность. - Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**. +* Swagger UI +* ReDoc + +Они были выбраны за популярность и стабильность. +Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**. + +/// ### REST фреймворки для Flask @@ -152,8 +165,11 @@ def read_url(): Итак, чтобы определить каждую схему, Вам нужно использовать определенные утилиты и классы, предоставляемые Marshmallow. -!!! check "Идея для **FastAPI**" - Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку. +/// check | Идея для **FastAPI** + +Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку. + +/// ### Webargs @@ -165,11 +181,17 @@ Webargs - это инструмент, который был создан для Это превосходный инструмент и я тоже часто пользовался им до **FastAPI**. -!!! info "Информация" - Webargs бы создан разработчиками Marshmallow. +/// info | Информация + +Webargs бы создан разработчиками Marshmallow. + +/// -!!! check "Идея для **FastAPI**" - Должна быть автоматическая проверка входных данных. +/// check | Идея для **FastAPI** + +Должна быть автоматическая проверка входных данных. + +/// ### APISpec @@ -190,11 +212,17 @@ Marshmallow и Webargs осуществляют проверку, анализ Редактор кода не особо может помочь в такой парадигме. А изменив какие-то параметры или схемы для Marshmallow можно забыть отредактировать докстринг с YAML и сгенерированная схема становится недействительной. -!!! info "Информация" - APISpec тоже был создан авторами Marshmallow. +/// info | Информация + +APISpec тоже был создан авторами Marshmallow. + +/// + +/// check | Идея для **FastAPI** + +Необходима поддержка открытого стандарта для API - OpenAPI. -!!! check "Идея для **FastAPI**" - Необходима поддержка открытого стандарта для API - OpenAPI. +/// ### Flask-apispec @@ -218,11 +246,17 @@ Marshmallow и Webargs осуществляют проверку, анализ Эти генераторы проектов также стали основой для [Генераторов проектов с **FastAPI**](project-generation.md){.internal-link target=_blank}. -!!! info "Информация" - Как ни странно, но Flask-apispec тоже создан авторами Marshmallow. +/// info | Информация -!!! check "Идея для **FastAPI**" - Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных. +Как ни странно, но Flask-apispec тоже создан авторами Marshmallow. + +/// + +/// check | Идея для **FastAPI** + +Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных. + +/// ### NestJSAngular) @@ -242,25 +276,34 @@ Marshmallow и Webargs осуществляют проверку, анализ Кроме того, он не очень хорошо справляется с вложенными моделями. Если в запросе имеется объект JSON, внутренние поля которого, в свою очередь, являются вложенными объектами JSON, это не может быть должным образом задокументировано и проверено. -!!! check "Идеи для **FastAPI** " - Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода. +/// check | Идеи для **FastAPI** + +Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода. + +Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода. - Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода. +/// ### Sanic Sanic был одним из первых чрезвычайно быстрых Python-фреймворков основанных на `asyncio`. Он был сделан очень похожим на Flask. -!!! note "Технические детали" - В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым. +/// note | Технические детали - Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках. +В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым. -!!! check "Идеи для **FastAPI**" - Должна быть сумасшедшая производительность. +Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках. - Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц). +/// + +/// check | Идеи для **FastAPI** + +Должна быть сумасшедшая производительность. + +Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц). + +/// ### Falcon @@ -275,12 +318,15 @@ Falcon - ещё один высокопроизводительный Python-ф Либо эти функции должны быть встроены во фреймворк, сконструированный поверх Falcon, как в Hug. Такая же особенность присутствует и в других фреймворках, вдохновлённых идеей Falcon, использовать только один объект запроса и один объект ответа. -!!! check "Идея для **FastAPI**" - Найдите способы добиться отличной производительности. +/// check | Идея для **FastAPI** + +Найдите способы добиться отличной производительности. + +Объявлять параметры `ответа сервера` в функциях, как в Hug. - Объявлять параметры `ответа сервера` в функциях, как в Hug. +Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния. - Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния. +/// ### Molten @@ -302,13 +348,16 @@ Molten мне попался на начальной стадии написан Это больше похоже на Django, чем на Flask и Starlette. Он разделяет в коде вещи, которые довольно тесно связаны. -!!! check "Идея для **FastAPI**" - Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию". - Это улучшает помощь редактора и раньше это не было доступно в Pydantic. +/// check | Идея для **FastAPI** - Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic). +Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию". +Это улучшает помощь редактора и раньше это не было доступно в Pydantic. -### Hug +Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic). + +/// + +### Hug Hug был одним из первых фреймворков, реализовавших объявление параметров API с использованием подсказок типов Python. Эта отличная идея была использована и другими инструментами. @@ -325,15 +374,21 @@ Hug был одним из первых фреймворков, реализов Поскольку он основан на WSGI, старом стандарте для синхронных веб-фреймворков, он не может работать с веб-сокетами и другими модными штуками, но всё равно обладает высокой производительностью. -!!! info "Информация" - Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах. +/// info | Информация + +Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах. + +/// + +/// check | Идеи для **FastAPI** + +Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar. -!!! check "Идеи для **FastAPI**" - Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar. +Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры. - Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры. +Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки. - Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки. +/// ### APIStar (<= 0.5) @@ -363,24 +418,30 @@ Hug был одним из первых фреймворков, реализов Ныне APIStar - это набор инструментов для проверки спецификаций OpenAPI. -!!! info "Информация" - APIStar был создан Tom Christie. Тот самый парень, который создал: +/// info | Информация - * Django REST Framework - * Starlette (на котором основан **FastAPI**) - * Uvicorn (используемый в Starlette и **FastAPI**) +APIStar был создан Tom Christie. Тот самый парень, который создал: -!!! check "Идеи для **FastAPI**" - Воплощение. +* Django REST Framework +* Starlette (на котором основан **FastAPI**) +* Uvicorn (используемый в Starlette и **FastAPI**) - Мне казалось блестящей идеей объявлять множество функций (проверка данных, сериализация, документация) с помощью одних и тех же типов Python, которые при этом обеспечивают ещё и помощь редактора кода. +/// - После долгих поисков среди похожих друг на друга фреймворков и сравнения их различий, APIStar стал самым лучшим выбором. +/// check | Идеи для **FastAPI** - Но APIStar перестал быть фреймворком для создания веб-сервера, зато появился Starlette, новая и лучшая основа для построения подобных систем. - Это была последняя капля, сподвигнувшая на создание **FastAPI**. +Воплощение. - Я считаю **FastAPI** "духовным преемником" APIStar, улучившим его возможности благодаря урокам, извлечённым из всех упомянутых выше инструментов. +Мне казалось блестящей идеей объявлять множество функций (проверка данных, сериализация, документация) с помощью одних и тех же типов Python, которые при этом обеспечивают ещё и помощь редактора кода. + +После долгих поисков среди похожих друг на друга фреймворков и сравнения их различий, APIStar стал самым лучшим выбором. + +Но APIStar перестал быть фреймворком для создания веб-сервера, зато появился Starlette, новая и лучшая основа для построения подобных систем. +Это была последняя капля, сподвигнувшая на создание **FastAPI**. + +Я считаю **FastAPI** "духовным преемником" APIStar, улучившим его возможности благодаря урокам, извлечённым из всех упомянутых выше инструментов. + +/// ## Что используется в **FastAPI** @@ -391,10 +452,13 @@ Pydantic - это библиотека для валидации данных, Его можно сравнить с Marshmallow, хотя в бенчмарках Pydantic быстрее, чем Marshmallow. И он основан на тех же подсказках типов, которые отлично поддерживаются редакторами кода. -!!! check "**FastAPI** использует Pydantic" - Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema). +/// check | **FastAPI** использует Pydantic + +Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema). + +Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает. - Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает. +/// ### Starlette @@ -424,19 +488,25 @@ Starlette обеспечивает весь функционал микрофр **FastAPI** добавляет эти функции используя подсказки типов Python и Pydantic. Ещё **FastAPI** добавляет систему внедрения зависимостей, утилиты безопасности, генерацию схемы OpenAPI и т.д. -!!! note "Технические детали" - ASGI - это новый "стандарт" разработанный участниками команды Django. - Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен. +/// note | Технические детали - Тем не менее он уже используется в качестве "стандарта" несколькими инструментами. - Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`. +ASGI - это новый "стандарт" разработанный участниками команды Django. +Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен. -!!! check "**FastAPI** использует Starlette" - В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху. +Тем не менее он уже используется в качестве "стандарта" несколькими инструментами. +Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`. - Класс `FastAPI` наследуется напрямую от класса `Starlette`. +/// - Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette. +/// check | **FastAPI** использует Starlette + +В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху. + +Класс `FastAPI` наследуется напрямую от класса `Starlette`. + +Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette. + +/// ### Uvicorn @@ -448,12 +518,15 @@ Uvicorn является сервером, а не фреймворком. Он рекомендуется в качестве сервера для Starlette и **FastAPI**. -!!! check "**FastAPI** рекомендует его" - Как основной сервер для запуска приложения **FastAPI**. +/// check | **FastAPI** рекомендует его + +Как основной сервер для запуска приложения **FastAPI**. + +Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер. - Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер. +Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}. - Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}. +/// ## Тестовые замеры и скорость diff --git a/docs/ru/docs/async.md b/docs/ru/docs/async.md index 4d3ce2adf..6c5d982df 100644 --- a/docs/ru/docs/async.md +++ b/docs/ru/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - `await` можно использовать только внутри функций, объявленных с использованием `async def`. +/// note + +`await` можно использовать только внутри функций, объявленных с использованием `async def`. + +/// --- @@ -444,14 +447,17 @@ Starlette (и **FastAPI**) основаны на -Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](index.md#performance){.internal-link target=_blank} +Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](index.md#_11){.internal-link target=_blank} другого фреймворка (или хотя бы на уровне с ним). ### Зависимости @@ -502,4 +508,4 @@ Starlette (и **FastAPI**) основаны на Нет времени?. +В противном случае просто ознакомьтесь с основными принципами в разделе выше: Нет времени?. diff --git a/docs/ru/docs/contributing.md b/docs/ru/docs/contributing.md index f9b8912e5..67034ad03 100644 --- a/docs/ru/docs/contributing.md +++ b/docs/ru/docs/contributing.md @@ -24,63 +24,73 @@ $ python -m venv env Активируйте виртуально окружение командой: -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` + +
-
+//// -=== "Windows PowerShell" +//// tab | Windows PowerShell + +
+ +```console +$ .\env\Scripts\Activate.ps1 +``` -
+
- ```console - $ .\env\Scripts\Activate.ps1 - ``` +//// -
+//// tab | Windows Bash -=== "Windows Bash" +Если Вы пользуетесь Bash для Windows (например: Git Bash): - Если Вы пользуетесь Bash для Windows (например: Git Bash): +
-
+```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +
-
+//// Проверьте, что всё сработало: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which pip -
+some/directory/fastapi/env/bin/pip +``` - ```console - $ which pip +
- some/directory/fastapi/env/bin/pip - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +$ Get-Command pip - ```console - $ Get-Command pip +some/directory/fastapi/env/bin/pip +``` - some/directory/fastapi/env/bin/pip - ``` +
-
+//// Если в терминале появится ответ, что бинарник `pip` расположен по пути `.../env/bin/pip`, значит всё в порядке. 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip -!!! tip "Подсказка" - Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение. +/// tip | Подсказка + +Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение. + +Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально. - Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально. +/// ### pip @@ -149,9 +162,11 @@ $ bash scripts/format.sh Также существуют дополнительные инструменты/скрипты для работы с переводами в `./scripts/docs.py`. -!!! tip "Подсказка" +/// tip | Подсказка - Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке. +Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке. + +/// Вся документация имеет формат Markdown и расположена в директории `./docs/en/`. @@ -237,14 +252,17 @@ $ uvicorn tutorial001:app --reload #### Подсказки и инструкции -* Проверьте существующие пул-реквесты для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их. +* Проверьте существующие пул-реквесты для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их. + +/// tip | Подсказка + +Вы можете добавлять комментарии с предложениями по изменению в существующие пул-реквесты. -!!! tip "Подсказка" - Вы можете добавлять комментарии с предложениями по изменению в существующие пул-реквесты. +Ознакомьтесь с документацией о добавлении отзыва к пул-реквесту, чтобы утвердить его или запросить изменения. - Ознакомьтесь с документацией о добавлении отзыва к пул-реквесту, чтобы утвердить его или запросить изменения. +/// -* Проверьте проблемы и вопросы, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка. +* Проверьте проблемы и вопросы, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка. * Добавляйте один пул-реквест для каждой отдельной переведённой страницы. Это значительно облегчит другим его просмотр. @@ -264,8 +282,11 @@ $ uvicorn tutorial001:app --reload Кодом испанского языка является `es`. А значит директория для переводов на испанский язык: `docs/es/`. -!!! tip "Подсказка" - Главный ("официальный") язык - английский, директория для него `docs/en/`. +/// tip | Подсказка + +Главный ("официальный") язык - английский, директория для него `docs/en/`. + +/// Вы можете запустить сервер документации на испанском: @@ -304,8 +325,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip "Подсказка" - Заметьте, что в пути файла мы изменили только код языка с `en` на `es`. +/// tip | Подсказка + +Заметьте, что в пути файла мы изменили только код языка с `en` на `es`. + +/// * Теперь откройте файл конфигурации MkDocs для английского языка, расположенный тут: @@ -376,10 +400,13 @@ Updating en После чего Вы можете проверить в своем редакторе кода, что появился новый каталог `docs/ht/`. -!!! tip "Подсказка" - Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы. +/// tip | Подсказка + +Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы. + +Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀 - Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀 +/// Начните перевод с главной страницы `docs/ht/index.md`. diff --git a/docs/ru/docs/deployment/concepts.md b/docs/ru/docs/deployment/concepts.md index 681acf15e..7cdc29526 100644 --- a/docs/ru/docs/deployment/concepts.md +++ b/docs/ru/docs/deployment/concepts.md @@ -1,6 +1,6 @@ # Концепции развёртывания -Существует несколько концепций, применяемых для развёртывания приложений **FastAPI**, равно как и для любых других типов веб-приложений, среди которых Вы можете выбрать **наиболее подходящий** способ. +Существует несколько концепций, применяемых для развёртывания приложений **FastAPI**, равно как и для любых других типов веб-приложений, среди которых вы можете выбрать **наиболее подходящий** способ. Самые важные из них: @@ -13,11 +13,11 @@ Рассмотрим ниже влияние каждого из них на процесс **развёртывания**. -Наша конечная цель - **обслуживать клиентов Вашего API безопасно** и **бесперебойно**, с максимально эффективным использованием **вычислительных ресурсов** (например, удалённых серверов/виртуальных машин). 🚀 +Наша конечная цель - **обслуживать клиентов вашего API безопасно** и **бесперебойно**, с максимально эффективным использованием **вычислительных ресурсов** (например, удалённых серверов/виртуальных машин). 🚀 -Здесь я немного расскажу Вам об этих **концепциях** и надеюсь, что у Вас сложится **интуитивное понимание**, какой способ выбрать при развертывании Вашего API в различных окружениях, возможно, даже **ещё не существующих**. +Здесь я немного расскажу Вам об этих **концепциях** и надеюсь, что у вас сложится **интуитивное понимание**, какой способ выбрать при развертывании вашего API в различных окружениях, возможно, даже **ещё не существующих**. -Ознакомившись с этими концепциями, Вы сможете **оценить и выбрать** лучший способ развёртывании **Вашего API**. +Ознакомившись с этими концепциями, вы сможете **оценить и выбрать** лучший способ развёртывании **Вашего API**. В последующих главах я предоставлю Вам **конкретные рецепты** развёртывания приложения FastAPI. @@ -25,15 +25,15 @@ ## Использование более безопасного протокола HTTPS -В [предыдущей главе об HTTPS](./https.md){.internal-link target=_blank} мы рассмотрели, как HTTPS обеспечивает шифрование для Вашего API. +В [предыдущей главе об HTTPS](https.md){.internal-link target=_blank} мы рассмотрели, как HTTPS обеспечивает шифрование для вашего API. -Также мы заметили, что обычно для работы с HTTPS Вашему приложению нужен **дополнительный** компонент - **прокси-сервер завершения работы TLS**. +Также мы заметили, что обычно для работы с HTTPS вашему приложению нужен **дополнительный** компонент - **прокси-сервер завершения работы TLS**. И если прокси-сервер не умеет сам **обновлять сертификаты HTTPS**, то нужен ещё один компонент для этого действия. ### Примеры инструментов для работы с HTTPS -Вот некоторые инструменты, которые Вы можете применять как прокси-серверы: +Вот некоторые инструменты, которые вы можете применять как прокси-серверы: * Traefik * С автоматическим обновлением сертификатов ✨ @@ -47,7 +47,7 @@ * С дополнительным компонентом типа cert-manager для обновления сертификатов * Использование услуг облачного провайдера (читайте ниже 👇) -В последнем варианте Вы можете воспользоваться услугами **облачного сервиса**, который сделает большую часть работы, включая настройку HTTPS. Это может наложить дополнительные ограничения или потребовать дополнительную плату и т.п. Зато Вам не понадобится самостоятельно заниматься настройками прокси-сервера. +В последнем варианте вы можете воспользоваться услугами **облачного сервиса**, который сделает большую часть работы, включая настройку HTTPS. Это может наложить дополнительные ограничения или потребовать дополнительную плату и т.п. Зато Вам не понадобится самостоятельно заниматься настройками прокси-сервера. В дальнейшем я покажу Вам некоторые конкретные примеры их применения. @@ -63,7 +63,7 @@ Термином **программа** обычно описывают множество вещей: -* **Код**, который Вы написали, в нашем случае **Python-файлы**. +* **Код**, который вы написали, в нашем случае **Python-файлы**. * **Файл**, который может быть **исполнен** операционной системой, например `python`, `python.exe` или `uvicorn`. * Конкретная программа, **запущенная** операционной системой и использующая центральный процессор и память. В таком случае это также называется **процесс**. @@ -74,13 +74,13 @@ * Конкретная программа, **запущенная** операционной системой. * Это не имеет отношения к какому-либо файлу или коду, но нечто **определённое**, управляемое и **выполняемое** операционной системой. * Любая программа, любой код, **могут делать что-то** только когда они **выполняются**. То есть, когда являются **работающим процессом**. -* Процесс может быть **прерван** (или "убит") Вами или Вашей операционной системой. В результате чего он перестанет исполняться и **не будет продолжать делать что-либо**. -* Каждое приложение, которое Вы запустили на своём компьютере, каждая программа, каждое "окно" запускает какой-то процесс. И обычно на включенном компьютере **одновременно** запущено множество процессов. +* Процесс может быть **прерван** (или "убит") Вами или вашей операционной системой. В результате чего он перестанет исполняться и **не будет продолжать делать что-либо**. +* Каждое приложение, которое вы запустили на своём компьютере, каждая программа, каждое "окно" запускает какой-то процесс. И обычно на включенном компьютере **одновременно** запущено множество процессов. * И **одна программа** может запустить **несколько параллельных процессов**. -Если Вы заглянете в "диспетчер задач" или "системный монитор" (или аналогичные инструменты) Вашей операционной системы, то увидите множество работающих процессов. +Если вы заглянете в "диспетчер задач" или "системный монитор" (или аналогичные инструменты) вашей операционной системы, то увидите множество работающих процессов. -Вполне вероятно, что Вы увидите несколько процессов с одним и тем же названием браузерной программы (Firefox, Chrome, Edge и т. Д.). Обычно браузеры запускают один процесс на вкладку и вдобавок некоторые дополнительные процессы. +Вполне вероятно, что вы увидите несколько процессов с одним и тем же названием браузерной программы (Firefox, Chrome, Edge и т. Д.). Обычно браузеры запускают один процесс на вкладку и вдобавок некоторые дополнительные процессы. @@ -90,21 +90,21 @@ ## Настройки запуска приложения -В большинстве случаев когда Вы создаёте веб-приложение, то желаете, чтоб оно **работало постоянно** и непрерывно, предоставляя клиентам доступ в любое время. Хотя иногда у Вас могут быть причины, чтоб оно запускалось только при определённых условиях. +В большинстве случаев когда вы создаёте веб-приложение, то желаете, чтоб оно **работало постоянно** и непрерывно, предоставляя клиентам доступ в любое время. Хотя иногда у вас могут быть причины, чтоб оно запускалось только при определённых условиях. ### Удалённый сервер -Когда Вы настраиваете удалённый сервер (облачный сервер, виртуальную машину и т.п.), самое простое, что можно сделать, запустить Uvicorn (или его аналог) вручную, как Вы делаете при локальной разработке. +Когда вы настраиваете удалённый сервер (облачный сервер, виртуальную машину и т.п.), самое простое, что можно сделать, запустить Uvicorn (или его аналог) вручную, как вы делаете при локальной разработке. Это рабочий способ и он полезен **во время разработки**. -Но если Вы потеряете соединение с сервером, то не сможете отслеживать - работает ли всё ещё **запущенный Вами процесс**. +Но если вы потеряете соединение с сервером, то не сможете отслеживать - работает ли всё ещё **запущенный Вами процесс**. -И если сервер перезагрузится (например, после обновления или каких-то действий облачного провайдера), Вы скорее всего **этого не заметите**, чтобы снова запустить процесс вручную. Вследствие этого Ваш API останется мёртвым. 😱 +И если сервер перезагрузится (например, после обновления или каких-то действий облачного провайдера), вы скорее всего **этого не заметите**, чтобы снова запустить процесс вручную. Вследствие этого Ваш API останется мёртвым. 😱 ### Автоматический запуск программ -Вероятно Вы пожелаете, чтоб Ваша серверная программа (такая как Uvicorn) стартовала автоматически при включении сервера, без **человеческого вмешательства** и всегда могла управлять Вашим API (так как Uvicorn запускает приложение FastAPI). +Вероятно вы захотите, чтоб Ваша серверная программа (такая, как Uvicorn) стартовала автоматически при включении сервера, без **человеческого вмешательства** и всегда могла управлять Вашим API (так как Uvicorn запускает приложение FastAPI). ### Отдельная программа @@ -127,7 +127,7 @@ ## Перезапуск -Вы, вероятно, также пожелаете, чтоб Ваше приложение **перезапускалось**, если в нём произошёл сбой. +Вы, вероятно, также захотите, чтоб ваше приложение **перезапускалось**, если в нём произошёл сбой. ### Мы ошибаемся @@ -137,7 +137,7 @@ ### Небольшие ошибки обрабатываются автоматически -Когда Вы создаёте свои API на основе FastAPI и допускаете в коде ошибку, то FastAPI обычно остановит её распространение внутри одного запроса, при обработке которого она возникла. 🛡 +Когда вы создаёте свои API на основе FastAPI и допускаете в коде ошибку, то FastAPI обычно остановит её распространение внутри одного запроса, при обработке которого она возникла. 🛡 Клиент получит ошибку **500 Internal Server Error** в ответ на свой запрос, но приложение не сломается и будет продолжать работать с последующими запросами. @@ -151,12 +151,15 @@ Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз... -!!! tip "Заметка" - ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, Вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. +/// tip | Заметка - Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново. +... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. -Возможно Вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск Вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в Вашем коде внутри приложения, не может быть выполнено в принципе. +Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново. + +/// + +Возможно вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в вашем коде внутри приложения, не может быть выполнено в принципе. ### Примеры инструментов для автоматического перезапуска @@ -181,13 +184,13 @@ ### Множество процессов - Воркеры (Workers) -Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то Вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами. +Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами. **Несколько запущенных процессов** одной и той же API-программы часто называют **воркерами**. ### Процессы и порты́ -Помните ли Вы, как на странице [Об HTTPS](./https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта? +Помните ли Вы, как на странице [Об HTTPS](https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта? С тех пор ничего не изменилось. @@ -197,11 +200,11 @@ Работающая программа загружает в память данные, необходимые для её работы, например, переменные содержащие модели машинного обучения или большие файлы. Каждая переменная **потребляет некоторое количество оперативной памяти (RAM)** сервера. -Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения Вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти. +Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти. ### Память сервера -Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда Вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если Вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате Вашему API потребуется **4 ГБ оперативной памяти (RAM)**. +Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате вашему API потребуется **4 ГБ оперативной памяти (RAM)**. И если Ваш удалённый сервер или виртуальная машина располагает только 3 ГБ памяти, то попытка загрузить в неё 4 ГБ данных вызовет проблемы. 🚨 @@ -211,15 +214,15 @@ Менеджер процессов будет слушать определённый **сокет** (IP:порт) и передавать данные работающим процессам. -Каждый из этих процессов будет запускать Ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память. +Каждый из этих процессов будет запускать ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память. -Безусловно, на этом же сервере будут работать и **другие процессы**, которые не относятся к Вашему приложению. +Безусловно, на этом же сервере будут работать и **другие процессы**, которые не относятся к вашему приложению. -Интересная деталь - обычно в течение времени процент **использования центрального процессора (CPU)** каждым процессом может очень сильно **изменяться**, но объём занимаемой **оперативной памяти (RAM)** остаётся относительно **стабильным**. +Интересная деталь заключается в том, что процент **использования центрального процессора (CPU)** каждым процессом может сильно меняться с течением времени, но объём занимаемой **оперативной памяти (RAM)** остаётся относительно **стабильным**. -Если у Вас есть API, который каждый раз выполняет сопоставимый объем вычислений, и у Вас много клиентов, то **загрузка процессора**, вероятно, *также будет стабильной* (вместо того, чтобы постоянно быстро увеличиваться и уменьшаться). +Если у вас есть API, который каждый раз выполняет сопоставимый объем вычислений, и у вас много клиентов, то **загрузка процессора**, вероятно, *также будет стабильной* (вместо того, чтобы постоянно быстро увеличиваться и уменьшаться). ### Примеры стратегий и инструментов для запуска нескольких экземпляров приложения @@ -236,12 +239,15 @@ * **Kubernetes** и аналогичные **контейнерные системы** * Какой-то компонент в **Kubernetes** будет слушать **IP:port**. Необходимое количество запущенных экземпляров приложения будет осуществляться посредством запуска **нескольких контейнеров**, в каждом из которых работает **один процесс Uvicorn**. * **Облачные сервисы**, которые позаботятся обо всём за Вас - * Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб Вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, Вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости. + * Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости. + +/// tip | Заметка + +Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. -!!! tip "Заметка" - Если Вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. +Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. - Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](./docker.md){.internal-link target=_blank}. +/// ## Шаги, предшествующие запуску @@ -253,18 +259,21 @@ Поэтому Вам нужен будет **один процесс**, выполняющий эти **подготовительные шаги** до запуска приложения. -Также Вам нужно будет убедиться, что этот процесс выполнил подготовительные шаги *даже* если впоследствии Вы запустите **несколько процессов** (несколько воркеров) самого приложения. Если бы эти шаги выполнялись в каждом **клонированном процессе**, они бы **дублировали** работу, пытаясь выполнить её **параллельно**. И если бы эта работа была бы чем-то деликатным, вроде миграции базы данных, то это может вызвать конфликты между ними. +Также Вам нужно будет убедиться, что этот процесс выполнил подготовительные шаги *даже* если впоследствии вы запустите **несколько процессов** (несколько воркеров) самого приложения. Если бы эти шаги выполнялись в каждом **клонированном процессе**, они бы **дублировали** работу, пытаясь выполнить её **параллельно**. И если бы эта работа была бы чем-то деликатным, вроде миграции базы данных, то это может вызвать конфликты между ними. Безусловно, возможны случаи, когда нет проблем при выполнении предварительной подготовки параллельно или несколько раз. Тогда Вам повезло, работать с ними намного проще. -!!! tip "Заметка" - Имейте в виду, что в некоторых случаях запуск Вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. +/// tip | Заметка - Что ж, тогда Вам не нужно беспокоиться об этом. 🤷 +Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. + +Что ж, тогда Вам не нужно беспокоиться об этом. 🤷 + +/// ### Примеры стратегий запуска предварительных шагов -Существует **сильная зависимость** от того, как Вы **развёртываете свою систему**, запускаете программы, обрабатываете перезапуски и т.д. +Существует **сильная зависимость** от того, как вы **развёртываете свою систему**, запускаете программы, обрабатываете перезапуски и т.д. Вот некоторые возможные идеи: @@ -272,26 +281,29 @@ * Bash-скрипт, выполняющий предварительные шаги, а затем запускающий приложение. * При этом Вам всё ещё нужно найти способ - как запускать/перезапускать *такой* bash-скрипт, обнаруживать ошибки и т.п. -!!! tip "Заметка" - Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](./docker.md){.internal-link target=_blank}. +/// tip | Заметка + +Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. + +/// ## Утилизация ресурсов Ваш сервер располагает ресурсами, которые Ваши программы могут потреблять или **утилизировать**, а именно - время работы центрального процессора и объём оперативной памяти. -Как много системных ресурсов Вы предполагаете потребить/утилизировать? Если не задумываться, то можно ответить - "немного", но на самом деле Вы, вероятно, пожелаете использовать **максимально возможное количество**. +Как много системных ресурсов вы предполагаете потребить/утилизировать? Если не задумываться, то можно ответить - "немного", но на самом деле Вы, вероятно, захотите использовать **максимально возможное количество**. -Если Вы платите за содержание трёх серверов, но используете лишь малую часть системных ресурсов каждого из них, то Вы **выбрасываете деньги на ветер**, а также **впустую тратите электроэнергию** и т.п. +Если вы платите за содержание трёх серверов, но используете лишь малую часть системных ресурсов каждого из них, то вы **выбрасываете деньги на ветер**, а также **впустую тратите электроэнергию** и т.п. В таком случае было бы лучше обойтись двумя серверами, но более полно утилизировать их ресурсы (центральный процессор, оперативную память, жёсткий диск, сети передачи данных и т.д). -С другой стороны, если Вы располагаете только двумя серверами и используете **на 100% их процессоры и память**, но какой-либо процесс запросит дополнительную память, то операционная система сервера будет использовать жёсткий диск для расширения оперативной памяти (а диск работает в тысячи раз медленнее), а то вовсе **упадёт**. Или если какому-то процессу понадобится произвести вычисления, то ему придётся подождать, пока процессор освободится. +С другой стороны, если вы располагаете только двумя серверами и используете **на 100% их процессоры и память**, но какой-либо процесс запросит дополнительную память, то операционная система сервера будет использовать жёсткий диск для расширения оперативной памяти (а диск работает в тысячи раз медленнее), а то вовсе **упадёт**. Или если какому-то процессу понадобится произвести вычисления, то ему придётся подождать, пока процессор освободится. В такой ситуации лучше подключить **ещё один сервер** и перераспределить процессы между серверами, чтоб всем **хватало памяти и процессорного времени**. -Также есть вероятность, что по какой-то причине возник **всплеск** запросов к Вашему API. Возможно, это был вирус, боты или другие сервисы начали пользоваться им. И для таких происшествий Вы можете захотеть иметь дополнительные ресурсы. +Также есть вероятность, что по какой-то причине возник **всплеск** запросов к вашему API. Возможно, это был вирус, боты или другие сервисы начали пользоваться им. И для таких происшествий вы можете захотеть иметь дополнительные ресурсы. -При настройке логики развёртываний, Вы можете указать **целевое значение** утилизации ресурсов, допустим, **от 50% до 90%**. Обычно эти метрики и используют. +При настройке логики развёртываний, вы можете указать **целевое значение** утилизации ресурсов, допустим, **от 50% до 90%**. Обычно эти метрики и используют. Вы можете использовать простые инструменты, такие как `htop`, для отслеживания загрузки центрального процессора и оперативной памяти сервера, в том числе каждым процессом. Или более сложные системы мониторинга нескольких серверов. @@ -308,4 +320,4 @@ Осознание этих идей и того, как их применять, должно дать Вам интуитивное понимание, необходимое для принятия решений при настройке развертываний. 🤓 -В следующих разделах я приведу более конкретные примеры возможных стратегий, которым Вы можете следовать. 🚀 +В следующих разделах я приведу более конкретные примеры возможных стратегий, которым вы можете следовать. 🚀 diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md index f045ca944..31da01b78 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -4,8 +4,11 @@ Использование контейнеров на основе Linux имеет ряд преимуществ, включая **безопасность**, **воспроизводимость**, **простоту** и прочие. -!!! tip "Подсказка" - Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) +/// tip | Подсказка + +Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) + +///
Развернуть Dockerfile 👀 @@ -70,19 +73,19 @@ Docker является одним оз основных инструменто и т.п. -Использование подготовленных образов значительно упрощает **комбинирование** и использование разных инструментов. Например, Вы можете попытаться использовать новую базу данных. В большинстве случаев можно использовать **официальный образ** и всего лишь указать переменные окружения. +Использование подготовленных образов значительно упрощает **комбинирование** и использование разных инструментов. Например, вы можете попытаться использовать новую базу данных. В большинстве случаев можно использовать **официальный образ** и всего лишь указать переменные окружения. -Таким образом, Вы можете изучить, что такое контейнеризация и Docker, и использовать полученные знания с разными инструментами и компонентами. +Таким образом, вы можете изучить, что такое контейнеризация и Docker, и использовать полученные знания с разными инструментами и компонентами. -Так, Вы можете запустить одновременно **множество контейнеров** с базой данных, Python-приложением, веб-сервером, React-приложением и соединить их вместе через внутреннюю сеть. +Так, вы можете запустить одновременно **множество контейнеров** с базой данных, Python-приложением, веб-сервером, React-приложением и соединить их вместе через внутреннюю сеть. Все системы управления контейнерами (такие, как Docker или Kubernetes) имеют встроенные возможности для организации такого сетевого взаимодействия. ## Контейнеры и процессы -Обычно **образ контейнера** содержит метаданные предустановленной программы или команду, которую следует выполнить при запуске **контейнера**. Также он может содержать параметры, передаваемые предустановленной программе. Похоже на то, как если бы Вы запускали такую программу через терминал. +Обычно **образ контейнера** содержит метаданные предустановленной программы или команду, которую следует выполнить при запуске **контейнера**. Также он может содержать параметры, передаваемые предустановленной программе. Похоже на то, как если бы вы запускали такую программу через терминал. -Когда **контейнер** запущен, он будет выполнять прописанные в нём команды и программы. Но Вы можете изменить его так, чтоб он выполнял другие команды и программы. +Когда **контейнер** запущен, он будет выполнять прописанные в нём команды и программы. Но вы можете изменить его так, чтоб он выполнял другие команды и программы. Контейнер буде работать до тех пор, пока выполняется его **главный процесс** (команда или программа). @@ -100,17 +103,17 @@ Docker является одним оз основных инструменто * Использование с **Kubernetes** или аналогичным инструментом * Запуск в **Raspberry Pi** -* Использование в облачных сервисах, запускающих образы контейнеров для Вас и т.п. +* Использование в облачных сервисах, запускающих образы контейнеров для вас и т.п. ### Установить зависимости -Обычно Вашему приложению необходимы **дополнительные библиотеки**, список которых находится в отдельном файле. +Обычно вашему приложению необходимы **дополнительные библиотеки**, список которых находится в отдельном файле. На название и содержание такого файла влияет выбранный Вами инструмент **установки** этих библиотек (зависимостей). Чаще всего это простой файл `requirements.txt` с построчным перечислением библиотек и их версий. -При этом Вы, для выбора версий, будете использовать те же идеи, что упомянуты на странице [О версиях FastAPI](./versions.md){.internal-link target=_blank}. +При этом Вы, для выбора версий, будете использовать те же идеи, что упомянуты на странице [О версиях FastAPI](versions.md){.internal-link target=_blank}. Ваш файл `requirements.txt` может выглядеть как-то так: @@ -132,10 +135,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info "Информация" - Существуют и другие инструменты управления зависимостями. +/// info | Информация + +Существуют и другие инструменты управления зависимостями. - В этом же разделе, но позже, я покажу Вам пример использования Poetry. 👇 +В этом же разделе, но позже, я покажу вам пример использования Poetry. 👇 + +/// ### Создать приложение **FastAPI** @@ -195,20 +201,23 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Сначала копируйте **только** файл с зависимостями. - Этот файл **изменяется довольно редко**, Docker ищет изменения при постройке образа и если не находит, то использует **кэш**, в котором хранятся предыдущии версии сборки образа. + Этот файл **изменяется довольно редко**, Docker ищет изменения при постройке образа и если не находит, то использует **кэш**, в котором хранятся предыдущие версии сборки образа. 4. Установите библиотеки перечисленные в файле с зависимостями. Опция `--no-cache-dir` указывает `pip` не сохранять загружаемые библиотеки на локальной машине для использования их в случае повторной загрузки. В контейнере, в случае пересборки этого шага, они всё равно будут удалены. - !!! note "Заметка" - Опция `--no-cache-dir` нужна только для `pip`, она никак не влияет на Docker или контейнеры. + /// note | Заметка + + Опция `--no-cache-dir` нужна только для `pip`, она никак не влияет на Docker или контейнеры. + + /// Опция `--upgrade` указывает `pip` обновить библиотеки, емли они уже установлены. Ка и в предыдущем шаге с копированием файла, этот шаг также будет использовать **кэш Docker** в случае отсутствия изменений. - Использрвание кэша, особенно на этом шаге, позволит Вам **сэкономить** кучу времени при повторной сборке образа, так как зависимости будут сохранены в кеше, а не **загружаться и устанавливаться каждый раз**. + Использование кэша, особенно на этом шаге, позволит вам **сэкономить** кучу времени при повторной сборке образа, так как зависимости будут сохранены в кеше, а не **загружаться и устанавливаться каждый раз**. 5. Скопируйте директорию `./app` внутрь директории `/code` (в контейнере). @@ -216,14 +225,17 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 6. Укажите **команду**, запускающую сервер `uvicorn`. - `CMD` принимает список строк, разделённых запятыми, но при выполнении объединит их через пробел, собрав из них одну команду, которую Вы могли бы написать в терминале. + `CMD` принимает список строк, разделённых запятыми, но при выполнении объединит их через пробел, собрав из них одну команду, которую вы могли бы написать в терминале. - Эта команда будет выполнена в **текущей рабочей директории**, а именно в директории `/code`, котоая указана командой `WORKDIR /code`. + Эта команда будет выполнена в **текущей рабочей директории**, а именно в директории `/code`, которая указана в команде `WORKDIR /code`. - Так как команда выполняется внутрии директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. + Так как команда выполняется внутри директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. -!!! tip "Подсказка" - Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 +/// tip | Подсказка + +Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 + +/// На данном этапе структура проекта должны выглядеть так: @@ -238,7 +250,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] #### Использование прокси-сервера -Если Вы запускаете контейнер за прокси-сервером завершения TLS (балансирующего нагрузку), таким как Nginx или Traefik, добавьте опцию `--proxy-headers`, которая укажет Uvicorn, что он работает позади прокси-сервера и может доверять заголовкам отправляемым им. +Если вы запускаете контейнер за прокси-сервером завершения TLS (балансирующего нагрузку), таким как Nginx или Traefik, добавьте опцию `--proxy-headers`, которая укажет Uvicorn, что он работает позади прокси-сервера и может доверять заголовкам отправляемым им. ```Dockerfile CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] @@ -269,7 +281,7 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt Для загрузки и установки необходимых библиотек **может понадобиться несколько минут**, но использование **кэша** занимает несколько **секунд** максимум. -И так как во время разработки Вы будете часто пересобирать контейнер для проверки работоспособности внесённых изменений, то сэкономленные минуты сложатся в часы, а то и дни. +И так как во время разработки вы будете часто пересобирать контейнер для проверки работоспособности внесённых изменений, то сэкономленные минуты сложатся в часы, а то и дни. Так как папка с кодом приложения **изменяется чаще всего**, то мы расположили её в конце `Dockerfile`, ведь после внесённых в код изменений кэш не будет использован на этом и следующих шагах. @@ -294,14 +306,17 @@ $ docker build -t myimage . -!!! tip "Подсказка" - Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. +/// tip | Подсказка + +Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. - В данном случае это та же самая директория (`.`). +В данном случае это та же самая директория (`.`). + +/// ### Запуск Docker-контейнера -* Запустите контейнер, основанный на Вашем образе: +* Запустите контейнер, основанный на вашем образе:
@@ -315,7 +330,7 @@ $ docker run -d --name mycontainer -p 80:80 myimage Вы можете проверить, что Ваш Docker-контейнер работает перейдя по ссылке: http://192.168.99.100/items/5?q=somequery или http://127.0.0.1/items/5?q=somequery (или похожей, которую использует Ваш Docker-хост). -Там Вы увидите: +Там вы увидите: ```JSON {"item_id": 5, "q": "somequery"} @@ -325,21 +340,21 @@ $ docker run -d --name mycontainer -p 80:80 myimage Теперь перейдите по ссылке http://192.168.99.100/docs или http://127.0.0.1/docs (или похожей, которую использует Ваш Docker-хост). -Здесь Вы увидите автоматическую интерактивную документацию API (предоставляемую Swagger UI): +Здесь вы увидите автоматическую интерактивную документацию API (предоставляемую Swagger UI): ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) ## Альтернативная документация API -Также Вы можете перейти по ссылке http://192.168.99.100/redoc or http://127.0.0.1/redoc (или похожей, которую использует Ваш Docker-хост). +Также вы можете перейти по ссылке http://192.168.99.100/redoc or http://127.0.0.1/redoc (или похожей, которую использует Ваш Docker-хост). -Здесь Вы увидите альтернативную автоматическую документацию API (предоставляемую ReDoc): +Здесь вы увидите альтернативную автоматическую документацию API (предоставляемую ReDoc): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) ## Создание Docker-образа на основе однофайлового приложения FastAPI -Если Ваше приложение FastAPI помещено в один файл, например, `main.py` и структура Ваших файлов похожа на эту: +Если ваше приложение FastAPI помещено в один файл, например, `main.py` и структура Ваших файлов похожа на эту: ``` . @@ -374,9 +389,9 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Концепции развёртывания -Давайте вспомним о [Концепциях развёртывания](./concepts.md){.internal-link target=_blank} и применим их к контейнерам. +Давайте вспомним о [Концепциях развёртывания](concepts.md){.internal-link target=_blank} и применим их к контейнерам. -Контейнеры - это, в основном, инструмент упрощающий **сборку и развёртывание** приложения и они не обязыают к применению какой-то определённой **концепции развёртывания**, а значит мы можем выбирать нужную стратегию. +Контейнеры - это, в основном, инструмент упрощающий **сборку и развёртывание** приложения и они не обязывают к применению какой-то определённой **концепции развёртывания**, а значит мы можем выбирать нужную стратегию. **Хорошая новость** в том, что независимо от выбранной стратегии, мы всё равно можем покрыть все концепции развёртывания. 🎉 @@ -395,8 +410,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Это может быть другой контейнер, в котором есть, например, Traefik, работающий с **HTTPS** и **самостоятельно** обновляющий **сертификаты**. -!!! tip "Подсказка" - Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. +/// tip | Подсказка + +Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. + +/// В качестве альтернативы, работу с HTTPS можно доверить облачному провайдеру, если он предоставляет такую услугу. @@ -412,7 +430,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Запуск нескольких экземпляров приложения - Указание количества процессов -Если у Вас есть кластер машин под управлением **Kubernetes**, Docker Swarm Mode, Nomad или аналогичной сложной системой оркестрации контейнеров, скорее всего, вместо использования менеджера процессов (типа Gunicorn и его воркеры) в каждом контейнере, Вы захотите **управлять количеством запущенных экземпляров приложения** на **уровне кластера**. +Если у вас есть кластер машин под управлением **Kubernetes**, Docker Swarm Mode, Nomad или аналогичной сложной системой оркестрации контейнеров, скорее всего, вместо использования менеджера процессов (типа Gunicorn и его воркеры) в каждом контейнере, вы захотите **управлять количеством запущенных экземпляров приложения** на **уровне кластера**. В любую из этих систем управления контейнерами обычно встроен способ управления **количеством запущенных контейнеров** для распределения **нагрузки** от входящих запросов на **уровне кластера**. @@ -424,20 +442,23 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Поскольку этот компонент **принимает запросы** и равномерно **распределяет** их между компонентами, его также называют **балансировщиком нагрузки**. -!!! tip "Подсказка" - **Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. +/// tip | Подсказка + +**Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. + +/// -Система оркестрации, которую Вы используете для запуска и управления контейнерами, имеет встроенный инструмент **сетевого взаимодействия** (например, для передачи HTTP-запросов) между контейнерами с Вашими приложениями и **балансировщиком нагрузки** (который также может быть **прокси-сервером**). +Система оркестрации, которую вы используете для запуска и управления контейнерами, имеет встроенный инструмент **сетевого взаимодействия** (например, для передачи HTTP-запросов) между контейнерами с Вашими приложениями и **балансировщиком нагрузки** (который также может быть **прокси-сервером**). ### Один балансировщик - Множество контейнеров -При работе с **Kubernetes** или аналогичными системами оркестрации использование их внутреннней сети позволяет иметь один **балансировщик нагрузки**, который прослушивает **главный** порт и передаёт запросы **множеству запущенных контейнеров** с Вашими приложениями. +При работе с **Kubernetes** или аналогичными системами оркестрации использование их внутренней сети позволяет иметь один **балансировщик нагрузки**, который прослушивает **главный** порт и передаёт запросы **множеству запущенных контейнеров** с Вашими приложениями. В каждом из контейнеров обычно работает **только один процесс** (например, процесс Uvicorn управляющий Вашим приложением FastAPI). Контейнеры могут быть **идентичными**, запущенными на основе одного и того же образа, но у каждого будут свои отдельные процесс, память и т.п. Таким образом мы получаем преимущества **распараллеливания** работы по **разным ядрам** процессора или даже **разным машинам**. Система управления контейнерами с **балансировщиком нагрузки** будет **распределять запросы** к контейнерам с приложениями **по очереди**. То есть каждый запрос будет обработан одним из множества **одинаковых контейнеров** с одним и тем же приложением. -**Балансировщик нагрузки** может обрабатывать запросы к *разным* приложениям, расположенным в Вашем кластере (например, если у них разные домены или префиксы пути) и передавать запросы нужному контейнеру с требуемым приложением. +**Балансировщик нагрузки** может обрабатывать запросы к *разным* приложениям, расположенным в вашем кластере (например, если у них разные домены или префиксы пути) и передавать запросы нужному контейнеру с требуемым приложением. ### Один процесс на контейнер @@ -447,37 +468,37 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Использование менеджера процессов (Gunicorn или Uvicorn) внутри контейнера только добавляет **излишнее усложнение**, так как управление следует осуществлять системой оркестрации. -### Множество процессов внутри контейнера для особых случаев +### Множество процессов внутри контейнера для особых случаев -Безусловно, бывают **особые случаи**, когда может понадобится внутри контейнера запускать **менеджер процессов Gunicorn**, управляющий несколькими **процессами Uvicorn**. +Безусловно, бывают **особые случаи**, когда может понадобиться внутри контейнера запускать **менеджер процессов Gunicorn**, управляющий несколькими **процессами Uvicorn**. -Для таких случаев Вы можете использовать **официальный Docker-образ** (прим. пер: - *здесь и далее на этой странице, если Вы встретите сочетание "официальный Docker-образ" без уточнений, то автор имеет в виду именно предоставляемый им образ*), где в качестве менеджера процессов используется **Gunicorn**, запускающий несколько **процессов Uvicorn** и некоторые настройки по умолчанию, автоматически устанавливающие количество запущенных процессов в зависимости от количества ядер Вашего процессора. Я расскажу Вам об этом подробнее тут: [Официальный Docker-образ со встроенными Gunicorn и Uvicorn](#docker-gunicorn-uvicorn). +Для таких случаев вы можете использовать **официальный Docker-образ** (прим. пер: - *здесь и далее на этой странице, если вы встретите сочетание "официальный Docker-образ" без уточнений, то автор имеет в виду именно предоставляемый им образ*), где в качестве менеджера процессов используется **Gunicorn**, запускающий несколько **процессов Uvicorn** и некоторые настройки по умолчанию, автоматически устанавливающие количество запущенных процессов в зависимости от количества ядер вашего процессора. Я расскажу вам об этом подробнее тут: [Официальный Docker-образ со встроенными Gunicorn и Uvicorn](#docker-gunicorn-uvicorn). Некоторые примеры подобных случаев: #### Простое приложение -Вы можете использовать менеджер процессов внутри контейнера, если Ваше приложение **настолько простое**, что у Вас нет необходимости (по крайней мере, пока нет) в тщательных настройках количества процессов и Вам достаточно имеющихся настроек по умолчанию (если используется официальный Docker-образ) для запуска приложения **только на одном сервере**, а не в кластере. +Вы можете использовать менеджер процессов внутри контейнера, если ваше приложение **настолько простое**, что у вас нет необходимости (по крайней мере, пока нет) в тщательных настройках количества процессов и вам достаточно имеющихся настроек по умолчанию (если используется официальный Docker-образ) для запуска приложения **только на одном сервере**, а не в кластере. #### Docker Compose -С помощью **Docker Compose** можно разворачивать несколько контейнеров на **одном сервере** (не кластере), но при это у Вас не будет простого способа управления количеством запущенных контейнеров с одновременным сохранением общей сети и **балансировки нагрузки**. +С помощью **Docker Compose** можно разворачивать несколько контейнеров на **одном сервере** (не кластере), но при это у вас не будет простого способа управления количеством запущенных контейнеров с одновременным сохранением общей сети и **балансировки нагрузки**. В этом случае можно использовать **менеджер процессов**, управляющий **несколькими процессами**, внутри **одного контейнера**. #### Prometheus и прочие причины -У Вас могут быть и **другие причины**, когда использование **множества процессов** внутри **одного контейнера** будет проще, нежели запуск **нескольких контейнеров** с **единственным процессом** в каждом из них. +У вас могут быть и **другие причины**, когда использование **множества процессов** внутри **одного контейнера** будет проще, нежели запуск **нескольких контейнеров** с **единственным процессом** в каждом из них. -Например (в зависимости от конфигурации), у Вас могут быть инструменты подобные экспортёру Prometheus, которые должны иметь доступ к **каждому запросу** приходящему в контейнер. +Например (в зависимости от конфигурации), у вас могут быть инструменты подобные экспортёру Prometheus, которые должны иметь доступ к **каждому запросу** приходящему в контейнер. -Если у Вас будет **несколько контейнеров**, то Prometheus, по умолчанию, **при сборе метрик** получит их **только с одного контейнера**, который обрабатывает конкретный запрос, вместо **сбора метрик** со всех работающих контейнеров. +Если у вас будет **несколько контейнеров**, то Prometheus, по умолчанию, **при сборе метрик** получит их **только с одного контейнера**, который обрабатывает конкретный запрос, вместо **сбора метрик** со всех работающих контейнеров. В таком случае может быть проще иметь **один контейнер** со **множеством процессов**, с нужным инструментом (таким как экспортёр Prometheus) в этом же контейнере и собирающем метрики со всех внутренних процессов этого контейнера. --- -Самое главное - **ни одно** из перечисленных правил не является **высеченным в камне** и Вы не обязаны слепо их повторять. Вы можете использовать эти идеи при **рассмотрении Вашего конкретного случая** и самостоятельно решать, какая из концепции подходит лучше: +Самое главное - **ни одно** из перечисленных правил не является **высеченным на камне** и вы не обязаны слепо их повторять. вы можете использовать эти идеи при **рассмотрении вашего конкретного случая** и самостоятельно решать, какая из концепции подходит лучше: * Использование более безопасного протокола HTTPS * Настройки запуска приложения @@ -488,41 +509,47 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Управление памятью -При **запуске одного процесса на контейнер** Вы получаете относительно понятный, стабильный и ограниченный объём памяти, потребляемый одним контейнером. +При **запуске одного процесса на контейнер** вы получаете относительно понятный, стабильный и ограниченный объём памяти, потребляемый одним контейнером. Вы можете установить аналогичные ограничения по памяти при конфигурировании своей системы управления контейнерами (например, **Kubernetes**). Таким образом система сможет **изменять количество контейнеров** на **доступных ей машинах** приводя в соответствие количество памяти нужной контейнерам с количеством памяти доступной в кластере (наборе доступных машин). -Если у Вас **простенькое** приложение, вероятно у Вас не будет **необходимости** устанавливать жёсткие ограничения на выделяемую ему память. Но если приложение **использует много памяти** (например, оно использует модели **машинного обучения**), Вам следует проверить, как много памяти ему требуется и отрегулировать **количество контейнеров** запущенных на **каждой машине** (может быть даже добавить машин в кластер). +Если у вас **простенькое** приложение, вероятно у вас не будет **необходимости** устанавливать жёсткие ограничения на выделяемую ему память. Но если приложение **использует много памяти** (например, оно использует модели **машинного обучения**), вам следует проверить, как много памяти ему требуется и отрегулировать **количество контейнеров** запущенных на **каждой машине** (может быть даже добавить машин в кластер). -Если Вы запускаете **несколько процессов в контейнере**, то должны быть уверены, что эти процессы не **займут памяти больше**, чем доступно для контейнера. +Если вы запускаете **несколько процессов в контейнере**, то должны быть уверены, что эти процессы не **займут памяти больше**, чем доступно для контейнера. ## Подготовительные шаги при запуске контейнеров -Есть два основных подхода, которые Вы можете использовать при запуске контейнеров (Docker, Kubernetes и т.п.). +Есть два основных подхода, которые вы можете использовать при запуске контейнеров (Docker, Kubernetes и т.п.). ### Множество контейнеров -Когда Вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). +Когда вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). -!!! info "Информация" - При использовании Kubernetes, это может быть Инициализирующий контейнер. +/// info | Информация -При отсутствии такой необходимости (допустим, не нужно применять миграции к базе данных, а только проверить, что она готова принимать соединения), Вы можете проводить такую проверку в каждом контейнере перед запуском его основного процесса и запускать все контейнеры **одновременно**. +При использовании Kubernetes, это может быть Инициализирующий контейнер. + +/// + +При отсутствии такой необходимости (допустим, не нужно применять миграции к базе данных, а только проверить, что она готова принимать соединения), вы можете проводить такую проверку в каждом контейнере перед запуском его основного процесса и запускать все контейнеры **одновременно**. ### Только один контейнер -Если у Вас несложное приложение для работы которого достаточно **одного контейнера**, но в котором работает **несколько процессов** (или один процесс), то прохождение предварительных шагов можно осуществить в этом же контейнере до запуска основного процесса. Официальный Docker-образ поддерживает такие действия. +Если у вас несложное приложение для работы которого достаточно **одного контейнера**, но в котором работает **несколько процессов** (или один процесс), то прохождение предварительных шагов можно осуществить в этом же контейнере до запуска основного процесса. Официальный Docker-образ поддерживает такие действия. ## Официальный Docker-образ с Gunicorn и Uvicorn -Я подготовил для Вас Docker-образ, в который включён Gunicorn управляющий процессами (воркерами) Uvicorn, в соответствии с концепциями рассмотренными в предыдущей главе: [Рабочие процессы сервера (воркеры) - Gunicorn совместно с Uvicorn](./server-workers.md){.internal-link target=_blank}. +Я подготовил для вас Docker-образ, в который включён Gunicorn управляющий процессами (воркерами) Uvicorn, в соответствии с концепциями рассмотренными в предыдущей главе: [Рабочие процессы сервера (воркеры) - Gunicorn совместно с Uvicorn](server-workers.md){.internal-link target=_blank}. -Этот образ может быть полезен для ситуаций описанных тут: [Множество процессов внутри контейнера для особых случаев](#special-cases). +Этот образ может быть полезен для ситуаций описанных тут: [Множество процессов внутри контейнера для особых случаев](#_11). * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning "Предупреждение" - Скорее всего у Вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). +/// warning | Предупреждение + +Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). + +/// В этом образе есть **автоматический** механизм подстройки для запуска **необходимого количества процессов** в соответствии с доступным количеством ядер процессора. @@ -530,8 +557,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Он также поддерживает прохождение **Подготовительных шагов при запуске контейнеров** при помощи скрипта. -!!! tip "Подсказка" - Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: tiangolo/uvicorn-gunicorn-fastapi. +/// tip | Подсказка + +Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### Количество процессов в официальном Docker-образе @@ -539,11 +569,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Это означает, что он будет пытаться **выжать** из процессора как можно больше **производительности**. -Но Вы можете изменять и обновлять конфигурацию с помощью **переменных окружения** и т.п. +Но вы можете изменять и обновлять конфигурацию с помощью **переменных окружения** и т.п. Поскольку количество процессов зависит от процессора, на котором работает контейнер, **объём потребляемой памяти** также будет зависеть от этого. -А значит, если Вашему приложению требуется много оперативной памяти (например, оно использует модели машинного обучения) и Ваш сервер имеет центральный процессор с большим количеством ядер, но **не слишком большим объёмом оперативной памяти**, то может дойти до того, что контейнер попытается занять памяти больше, чем доступно, из-за чего будет падение производительности (или сервер вовсе упадёт). 🚨 +А значит, если вашему приложению требуется много оперативной памяти (например, оно использует модели машинного обучения) и Ваш сервер имеет центральный процессор с большим количеством ядер, но **не слишком большим объёмом оперативной памяти**, то может дойти до того, что контейнер попытается занять памяти больше, чем доступно, из-за чего будет падение производительности (или сервер вовсе упадёт). 🚨 ### Написание `Dockerfile` @@ -562,7 +592,7 @@ COPY ./app /app ### Большие приложения -Если Вы успели ознакомиться с разделом [Приложения содержащие много файлов](../tutorial/bigger-applications.md){.internal-link target=_blank}, состоящие из множества файлов, Ваш Dockerfile может выглядеть так: +Если вы успели ознакомиться с разделом [Приложения содержащие много файлов](../tutorial/bigger-applications.md){.internal-link target=_blank}, состоящие из множества файлов, Ваш Dockerfile может выглядеть так: ```Dockerfile hl_lines="7" FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 @@ -576,9 +606,9 @@ COPY ./app /app/app ### Как им пользоваться -Если Вы используете **Kubernetes** (или что-то вроде того), скорее всего Вам **не нужно** использовать официальный Docker-образ (или другой похожий) в качестве основы, так как управление **количеством запущенных контейнеров** должно быть настроено на уровне кластера. В таком случае лучше **создать образ с нуля**, как описано в разделе Создать [Docker-образ для FastAPI](#docker-fastapi). +Если вы используете **Kubernetes** (или что-то вроде того), скорее всего вам **не нужно** использовать официальный Docker-образ (или другой похожий) в качестве основы, так как управление **количеством запущенных контейнеров** должно быть настроено на уровне кластера. В таком случае лучше **создать образ с нуля**, как описано в разделе Создать [Docker-образ для FastAPI](#docker-fastapi). -Официальный образ может быть полезен в отдельных случаях, описанных выше в разделе [Множество процессов внутри контейнера для особых случаев](#special-cases). Например, если Ваше приложение **достаточно простое**, не требует запуска в кластере и способно уместиться в один контейнер, то его настройки по умолчанию будут работать довольно хорошо. Или же Вы развертываете его с помощью **Docker Compose**, работаете на одном сервере и т. д +Официальный образ может быть полезен в отдельных случаях, описанных выше в разделе [Множество процессов внутри контейнера для особых случаев](#_11). Например, если ваше приложение **достаточно простое**, не требует запуска в кластере и способно уместиться в один контейнер, то его настройки по умолчанию будут работать довольно хорошо. Или же вы развертываете его с помощью **Docker Compose**, работаете на одном сервере и т. д ## Развёртывание образа контейнера @@ -590,11 +620,11 @@ COPY ./app /app/app * С использованием **Kubernetes** в кластере * С использованием режима Docker Swarm в кластере * С использованием других инструментов, таких как Nomad -* С использованием облачного сервиса, который будет управлять разворачиванием Вашего контейнера +* С использованием облачного сервиса, который будет управлять разворачиванием вашего контейнера ## Docker-образ и Poetry -Если Вы пользуетесь Poetry для управления зависимостями Вашего проекта, то можете использовать многоэтапную сборку образа: +Если вы пользуетесь Poetry для управления зависимостями вашего проекта, то можете использовать многоэтапную сборку образа: ```{ .dockerfile .annotate } # (1) @@ -659,24 +689,27 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Запустите `uvicorn`, указав ему использовать объект `app`, расположенный в `app.main`. -!!! tip "Подсказка" - Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. +/// tip | Подсказка + +Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. + +/// **Этапы сборки Docker-образа** являются частью `Dockerfile` и работают как **временные образы контейнеров**. Они нужны только для создания файлов, используемых в дальнейших этапах. -Первый этап был нужен только для **установки Poetry** и **создания файла `requirements.txt`**, в которым прописаны зависимости Вашего проекта, взятые из файла `pyproject.toml`. +Первый этап был нужен только для **установки Poetry** и **создания файла `requirements.txt`**, в которым прописаны зависимости вашего проекта, взятые из файла `pyproject.toml`. На **следующем этапе** `pip` будет использовать файл `requirements.txt`. В итоговом образе будет содержаться **только последний этап сборки**, предыдущие этапы будут отброшены. -При использовании Poetry, имеет смысл использовать **многоэтапную сборку Docker-образа**, потому что на самом деле Вам не нужен Poetry и его зависимости в окончательном образе контейнера, Вам **нужен только** сгенерированный файл `requirements.txt` для установки зависимостей Вашего проекта. +При использовании Poetry, имеет смысл использовать **многоэтапную сборку Docker-образа**, потому что на самом деле вам не нужен Poetry и его зависимости в окончательном образе контейнера, вам **нужен только** сгенерированный файл `requirements.txt` для установки зависимостей вашего проекта. А на последнем этапе, придерживаясь описанных ранее правил, создаётся итоговый образ ### Использование прокси-сервера завершения TLS и Poetry -И снова повторюсь, если используете прокси-сервер (балансировщик нагрузки), такой, как Nginx или Traefik, добавьте в команду запуска опцию `--proxy-headers`: +И снова повторюсь, если используете прокси-сервер (балансировщик нагрузки), такой как Nginx или Traefik, добавьте в команду запуска опцию `--proxy-headers`: ```Dockerfile CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] @@ -695,6 +728,6 @@ CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port" В большинстве случаев Вам, вероятно, не нужно использовать какой-либо базовый образ, **лучше создать образ контейнера с нуля** на основе официального Docker-образа Python. -Позаботившись о **порядке написания** инструкций в `Dockerfile`, Вы сможете использовать **кэш Docker'а**, **минимизировав время сборки**, максимально повысив свою производительность (и избежать скуки). 😎 +Позаботившись о **порядке написания** инструкций в `Dockerfile`, вы сможете использовать **кэш Docker'а**, **минимизировав время сборки**, максимально повысив свою производительность (и не заскучать). 😎 В некоторых особых случаях вы можете использовать официальный образ Docker для FastAPI. 🤓 diff --git a/docs/ru/docs/deployment/https.md b/docs/ru/docs/deployment/https.md index a53ab6927..85c4cce60 100644 --- a/docs/ru/docs/deployment/https.md +++ b/docs/ru/docs/deployment/https.md @@ -1,11 +1,14 @@ # Об HTTPS -Обычно представляется, что HTTPS это некая опция, которая либо "включена", либо нет. +Обычно представляется, что HTTPS это некая опция, которая либо "включена", либо нет. Но всё несколько сложнее. -!!! tip "Заметка" - Если Вы торопитесь или Вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. +/// tip | Заметка + +Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. + +/// Чтобы **изучить основы HTTPS** для клиента, перейдите по ссылке https://howhttps.works/. @@ -22,8 +25,8 @@ * **TCP не знает о "доменах"**, но знает об IP-адресах. * Информация о **запрашиваемом домене** извлекается из запроса **на уровне HTTP**. * **Сертификаты HTTPS** "сертифицируют" **конкретный домен**, но проверка сертификатов и шифрование данных происходит на уровне протокола TCP, то есть **до того**, как станет известен домен-получатель данных. -* **По умолчанию** это означает, что у Вас может быть **только один сертификат HTTPS на один IP-адрес**. - * Не важно, насколько большой у Вас сервер и насколько маленькие приложения на нём могут быть. +* **По умолчанию** это означает, что у вас может быть **только один сертификат HTTPS на один IP-адрес**. + * Не важно, насколько большой у вас сервер и насколько маленькие приложения на нём могут быть. * Однако, у этой проблемы есть **решение**. * Существует **расширение** протокола **TLS** (который работает на уровне TCP, то есть до HTTP) называемое **SNI**. * Расширение SNI позволяет одному серверу (с **одним IP-адресом**) иметь **несколько сертификатов HTTPS** и обслуживать **множество HTTPS-доменов/приложений**. @@ -35,12 +38,12 @@ * получение **зашифрованных HTTPS-запросов** * отправка **расшифрованных HTTP запросов** в соответствующее HTTP-приложение, работающее на том же сервере (в нашем случае, это приложение **FastAPI**) -* получние **HTTP-ответа** от приложения +* получение **HTTP-ответа** от приложения * **шифрование ответа** используя подходящий **сертификат HTTPS** * отправка зашифрованного **HTTPS-ответа клиенту**. Такой сервер часто называют **Прокси-сервер завершения работы TLS** или просто "прокси-сервер". -Вот некоторые варианты, которые Вы можете использовать в качестве такого прокси-сервера: +Вот некоторые варианты, которые вы можете использовать в качестве такого прокси-сервера: * Traefik (может обновлять сертификаты) * Caddy (может обновлять сертификаты) @@ -67,24 +70,27 @@ ### Имя домена -Чаще всего, всё начинается с **приобретения имени домена**. Затем нужно настроить DNS-сервер (вероятно у того же провайдера, который выдал Вам домен). +Чаще всего, всё начинается с **приобретения имени домена**. Затем нужно настроить DNS-сервер (вероятно у того же провайдера, который выдал вам домен). -Далее, возможно, Вы получаете "облачный" сервер (виртуальную машину) или что-то типа этого, у которого есть постоянный **публичный IP-адрес**. +Далее, возможно, вы получаете "облачный" сервер (виртуальную машину) или что-то типа этого, у которого есть постоянный **публичный IP-адрес**. -На DNS-сервере (серверах) Вам следует настроить соответствующую ресурсную запись ("`запись A`"), указав, что **Ваш домен** связан с публичным **IP-адресом Вашего сервера**. +На DNS-сервере (серверах) вам следует настроить соответствующую ресурсную запись ("`запись A`"), указав, что **Ваш домен** связан с публичным **IP-адресом вашего сервера**. Обычно эту запись достаточно указать один раз, при первоначальной настройке всего сервера. -!!! tip "Заметка" - Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов. +/// tip | Заметка + +Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов. + +/// ### DNS Теперь давайте сфокусируемся на работе с HTTPS. -Всё начинается с того, что браузер спрашивает у **DNS-серверов**, какой **IP-адрес связан с доменом**, для примера возьмём домен `someapp.example.com`. +Всё начинается с того, что браузер спрашивает у **DNS-серверов**, какой **IP-адрес связан с доменом**, для примера возьмём домен `someapp.example.com`. -DNS-сервера присылают браузеру определённый **IP-адрес**, тот самый публичный IP-адрес Вашего сервера, который Вы указали в ресурсной "записи А" при настройке. +DNS-сервера присылают браузеру определённый **IP-адрес**, тот самый публичный IP-адрес вашего сервера, который вы указали в ресурсной "записи А" при настройке. @@ -96,7 +102,7 @@ DNS-сервера присылают браузеру определённый -Эта часть клиент-серверного взаимодействия устанавливает TLS-соединение и называется **TLS-рукопожатием**. +Эта часть клиент-серверного взаимодействия устанавливает TLS-соединение и называется **TLS-рукопожатием**. ### TLS с расширением SNI @@ -122,8 +128,11 @@ DNS-сервера присылают браузеру определённый Таким образом, **HTTPS** это тот же **HTTP**, но внутри **безопасного TLS-соединения** вместо чистого (незашифрованного) TCP-соединения. -!!! tip "Заметка" - Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP. +/// tip | Заметка + +Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP. + +/// ### HTTPS-запрос @@ -185,7 +194,7 @@ DNS-сервера присылают браузеру определённый * **Запуск в качестве программы-сервера** (как минимум, на время обновления сертификатов) на публичном IP-адресе домена. * Как уже не раз упоминалось, только один процесс может прослушивать определённый порт определённого IP-адреса. * Это одна из причин использования прокси-сервера ещё и в качестве программы обновления сертификатов. - * В случае, если обновлением сертификатов занимается другая программа, Вам понадобится остановить прокси-сервер, запустить программу обновления сертификатов на сокете, предназначенном для прокси-сервера, настроить прокси-сервер на работу с новыми сертификатами и перезапустить его. Эта схема далека от идеальной, так как Ваши приложения будут недоступны на время отключения прокси-сервера. + * В случае, если обновлением сертификатов занимается другая программа, вам понадобится остановить прокси-сервер, запустить программу обновления сертификатов на сокете, предназначенном для прокси-сервера, настроить прокси-сервер на работу с новыми сертификатами и перезапустить его. Эта схема далека от идеальной, так как Ваши приложения будут недоступны на время отключения прокси-сервера. Весь этот процесс обновления, одновременный с обслуживанием запросов, является одной из основных причин, по которой желательно иметь **отдельную систему для работы с HTTPS** в виде прокси-сервера завершения TLS, а не просто использовать сертификаты TLS непосредственно с сервером приложений (например, Uvicorn). @@ -193,6 +202,6 @@ DNS-сервера присылают браузеру определённый Наличие **HTTPS** очень важно и довольно **критично** в большинстве случаев. Однако, Вам, как разработчику, не нужно тратить много сил на это, достаточно **понимать эти концепции** и принципы их работы. -Но узнав базовые основы **HTTPS** Вы можете легко совмещать разные инструменты, которые помогут Вам в дальнейшей разработке. +Но узнав базовые основы **HTTPS** вы можете легко совмещать разные инструменты, которые помогут вам в дальнейшей разработке. -В следующих главах я покажу Вам несколько примеров, как настраивать **HTTPS** для приложений **FastAPI**. 🔒 +В следующих главах я покажу вам несколько примеров, как настраивать **HTTPS** для приложений **FastAPI**. 🔒 diff --git a/docs/ru/docs/deployment/index.md b/docs/ru/docs/deployment/index.md index d214a9d62..e88ddc3e2 100644 --- a/docs/ru/docs/deployment/index.md +++ b/docs/ru/docs/deployment/index.md @@ -8,7 +8,7 @@ Обычно **веб-приложения** размещают на удалённом компьютере с серверной программой, которая обеспечивает хорошую производительность, стабильность и т. д., Чтобы ваши пользователи могли эффективно, беспрерывно и беспроблемно обращаться к приложению. -Это отличется от **разработки**, когда вы постоянно меняете код, делаете в нём намеренные ошибки и исправляете их, останавливаете и перезапускаете сервер разработки и т. д. +Это отличается от **разработки**, когда вы постоянно меняете код, делаете в нём намеренные ошибки и исправляете их, останавливаете и перезапускаете сервер разработки и т. д. ## Стратегии развёртывания diff --git a/docs/ru/docs/deployment/manually.md b/docs/ru/docs/deployment/manually.md index 1d00b3086..9b1d32be8 100644 --- a/docs/ru/docs/deployment/manually.md +++ b/docs/ru/docs/deployment/manually.md @@ -1,100 +1,113 @@ # Запуск сервера вручную - Uvicorn -Для запуска приложения **FastAPI** на удалённой серверной машине Вам необходим программный сервер, поддерживающий протокол ASGI, такой как **Uvicorn**. +Для запуска приложения **FastAPI** на удалённой серверной машине вам необходим программный сервер, поддерживающий протокол ASGI, такой как **Uvicorn**. Существует три наиболее распространённые альтернативы: * Uvicorn: высокопроизводительный ASGI сервер. -* Hypercorn: ASGI сервер, помимо прочего поддерживающий HTTP/2 и Trio. +* Hypercorn: ASGI сервер, помимо прочего поддерживающий HTTP/2 и Trio. * Daphne: ASGI сервер, созданный для Django Channels. ## Сервер как машина и сервер как программа -В этих терминах есть некоторые различия и Вам следует запомнить их. 💡 +В этих терминах есть некоторые различия и вам следует запомнить их. 💡 Слово "**сервер**" чаще всего используется в двух контекстах: - удалённый или расположенный в "облаке" компьютер (физическая или виртуальная машина). - программа, запущенная на таком компьютере (например, Uvicorn). -Просто запомните, если Вам встретился термин "сервер", то обычно он подразумевает что-то из этих двух смыслов. +Просто запомните, если вам встретился термин "сервер", то обычно он подразумевает что-то из этих двух смыслов. -Когда имеют в виду именно удалённый компьютер, часто говорят просто **сервер**, но ещё его называют **машина**, **ВМ** (виртуальная машина), **нода**. Все эти термины обозначают одно и то же - удалённый компьютер, обычно под управлением Linux, на котором Вы запускаете программы. +Когда имеют в виду именно удалённый компьютер, часто говорят просто **сервер**, но ещё его называют **машина**, **ВМ** (виртуальная машина), **нода**. Все эти термины обозначают одно и то же - удалённый компьютер, обычно под управлением Linux, на котором вы запускаете программы. ## Установка программного сервера Вы можете установить сервер, совместимый с протоколом ASGI, так: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, молниесный ASGI сервер, основанный на библиотеках uvloop и httptools. +* Uvicorn, очень быстрый ASGI сервер, основанный на библиотеках uvloop и httptools. -
+
- ```console - $ pip install "uvicorn[standard]" +```console +$ pip install "uvicorn[standard]" - ---> 100% - ``` +---> 100% +``` -
+
+ +/// tip | Подсказка - !!! tip "Подсказка" - С опцией `standard`, Uvicorn будет установливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. +С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. - В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ. +В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ. -=== "Hypercorn" +/// - * Hypercorn, ASGI сервер, поддерживающий протокол HTTP/2. +//// -
+//// tab | Hypercorn - ```console - $ pip install hypercorn +* Hypercorn, ASGI сервер, поддерживающий протокол HTTP/2. - ---> 100% - ``` +
-
+```console +$ pip install hypercorn + +---> 100% +``` + +
- ...или какой-либо другой ASGI сервер. +...или какой-либо другой ASGI сервер. + +//// ## Запуск серверной программы -Затем запустите Ваше приложение так же, как было указано в руководстве ранее, но без опции `--reload`: +Затем запустите ваше приложение так же, как было указано в руководстве ранее, но без опции `--reload`: + +//// tab | Uvicorn + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 -=== "Uvicorn" +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +//// - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// tab | Hypercorn -
+
-=== "Hypercorn" +```console +$ hypercorn main:app --bind 0.0.0.0:80 -
+Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +
- Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +//// -
+/// warning | Предупреждение -!!! warning "Предупреждение" +Не забудьте удалить опцию `--reload`, если ранее пользовались ею. - Не забудьте удалить опцию `--reload`, если ранее пользовались ею. +Включение опции `--reload` требует дополнительных ресурсов, влияет на стабильность работы приложения и может повлечь прочие неприятности. - Включение опции `--reload` требует дополнительных ресурсов, влияет на стабильность работы приложения и может повлечь прочие неприятности. +Она сильно помогает во время **разработки**, но **не следует** использовать её при **реальной работе** приложения. - Она сильно помогает во время **разработки**, но **не следует** использовать её при **реальной работе** приложения. +/// ## Hypercorn с Trio @@ -103,11 +116,11 @@ Starlette и **FastAPI** основаны на `uvloop`, высокопроизводительной заменой `asyncio`. -Но если Вы хотите использовать **Trio** напрямую, то можете воспользоваться **Hypercorn**, так как они совместимы. ✨ +Но если вы хотите использовать **Trio** напрямую, то можете воспользоваться **Hypercorn**, так как они совместимы. ✨ ### Установка Hypercorn с Trio -Для начала, Вам нужно установить Hypercorn с поддержкой Trio: +Для начала, вам нужно установить Hypercorn с поддержкой Trio:
@@ -130,15 +143,15 @@ $ hypercorn main:app --worker-class trio
-Hypercorn, в свою очередь, запустит Ваше приложение использующее Trio. +Hypercorn, в свою очередь, запустит ваше приложение использующее Trio. -Таким образом, Вы сможете использовать Trio в своём приложении. Но лучше использовать AnyIO, для сохранения совместимости и с Trio, и с asyncio. 🎉 +Таким образом, вы сможете использовать Trio в своём приложении. Но лучше использовать AnyIO, для сохранения совместимости и с Trio, и с asyncio. 🎉 ## Концепции развёртывания В вышеприведённых примерах серверные программы (например Uvicorn) запускали только **один процесс**, принимающий входящие запросы с любого IP (на это указывал аргумент `0.0.0.0`) на определённый порт (в примерах мы указывали порт `80`). -Это основная идея. Но возможно, Вы озаботитесь добавлением дополнительных возможностей, таких как: +Это основная идея. Но возможно, вы озаботитесь добавлением дополнительных возможностей, таких как: * Использование более безопасного протокола HTTPS * Настройки запуска приложения @@ -147,4 +160,4 @@ Hypercorn, в свою очередь, запустит Ваше приложе * Управление памятью * Использование перечисленных функций перед запуском приложения. -Я поведаю Вам больше о каждой из этих концепций в следующих главах, с конкретными примерами стратегий работы с ними. 🚀 +Я расскажу вам больше о каждой из этих концепций в следующих главах, с конкретными примерами стратегий работы с ними. 🚀 diff --git a/docs/ru/docs/deployment/versions.md b/docs/ru/docs/deployment/versions.md index 91b9038e9..e8db30ce8 100644 --- a/docs/ru/docs/deployment/versions.md +++ b/docs/ru/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI следует соглашению в том, что любые изменения "ПАТЧ"-версии предназначены для исправления багов и внесения обратно совместимых изменений. -!!! Подсказка - "ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. +/// tip | Подсказка + +"ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. + +/// Итак, вы можете закрепить версию следующим образом: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Обратно несовместимые изменения и новые функции добавляются в "МИНОРНЫЕ" версии. -!!! Подсказка - "МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. +/// tip | Подсказка + +"МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. + +/// ## Обновление версий FastAPI diff --git a/docs/ru/docs/environment-variables.md b/docs/ru/docs/environment-variables.md new file mode 100644 index 000000000..a6c7b0c77 --- /dev/null +++ b/docs/ru/docs/environment-variables.md @@ -0,0 +1,297 @@ +# Переменные окружения + +/// tip + +Если вы уже знаете, что такое «переменные окружения» и как их использовать, можете пропустить это. + +/// + +Переменная окружения (также известная как «**env var**») - это переменная, которая живет **вне** кода Python, в **операционной системе**, и может быть прочитана вашим кодом Python (или другими программами). + +Переменные окружения могут быть полезны для работы с **настройками** приложений, как часть **установки** Python и т.д. + +## Создание и использование переменных окружения + +Можно **создавать** и использовать переменные окружения в **оболочке (терминале)**, не прибегая к помощи Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Вы можете создать переменную окружения MY_NAME с помощью +$ export MY_NAME="Wade Wilson" + +// Затем её можно использовать в других программах, например +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Создайте переменную окружения MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Используйте её с другими программами, например +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Чтение переменных окружения в python + +Так же существует возможность создания переменных окружения **вне** Python, в терминале (или любым другим способом), а затем **чтения их в Python**. + +Например, у вас есть файл `main.py`: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +Второй аргумент `os.getenv()` - это возвращаемое по умолчанию значение. + +Если значение не указано, то по умолчанию оно равно `None`. В данном случае мы указываем `«World»` в качестве значения по умолчанию. +/// + +Затем можно запустить эту программу на Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Здесь мы еще не устанавливаем переменную окружения +$ python main.py + +// Поскольку мы не задали переменную окружения, мы получим значение по умолчанию + +Hello World from Python + +// Но если мы сначала создадим переменную окружения +$ export MY_NAME="Wade Wilson" + +// А затем снова запустим программу +$ python main.py + +// Теперь она прочитает переменную окружения + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Здесь мы еще не устанавливаем переменную окружения +$ python main.py + +// Поскольку мы не задали переменную окружения, мы получим значение по умолчанию + +Hello World from Python + +// Но если мы сначала создадим переменную окружения +$ $Env:MY_NAME = "Wade Wilson" + +// А затем снова запустим программу +$ python main.py + +// Теперь она может прочитать переменную окружения + +Hello Wade Wilson from Python +``` + +
+ +//// + +Поскольку переменные окружения могут быть установлены вне кода, но могут быть прочитаны кодом, и их не нужно хранить (фиксировать в `git`) вместе с остальными файлами, их принято использовать для конфигураций или **настроек**. + +Вы также можете создать переменную окружения только для **конкретного вызова программы**, которая будет доступна только для этой программы и только на время ее выполнения. + +Для этого создайте её непосредственно перед самой программой, в той же строке: + +
+ +```console +// Создайте переменную окружения MY_NAME в строке для этого вызова программы +$ MY_NAME="Wade Wilson" python main.py + +// Теперь она может прочитать переменную окружения + +Hello Wade Wilson from Python + +// После этого переменная окружения больше не существует +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +Подробнее об этом можно прочитать на сайте The Twelve-Factor App: Config. + +/// + +## Типизация и Валидация + +Эти переменные окружения могут работать только с **текстовыми строками**, поскольку они являются внешними по отношению к Python и должны быть совместимы с другими программами и остальной системой (и даже с различными операционными системами, такими как Linux, Windows, macOS). + +Это означает, что **любое значение**, считанное в Python из переменной окружения, **будет `str`**, и любое преобразование к другому типу или любая проверка должны быть выполнены в коде. + +Подробнее об использовании переменных окружения для работы с **настройками приложения** вы узнаете в [Расширенное руководство пользователя - Настройки и переменные среды](./advanced/settings.md){.internal-link target=_blank}. + +## Переменная окружения `PATH` + +Существует **специальная** переменная окружения **`PATH`**, которая используется операционными системами (Linux, macOS, Windows) для поиска программ для запуска. + +Значение переменной `PATH` - это длинная строка, состоящая из каталогов, разделенных двоеточием `:` в Linux и macOS, и точкой с запятой `;` в Windows. + +Например, переменная окружения `PATH` может выглядеть следующим образом: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Это означает, что система должна искать программы в каталогах: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Это означает, что система должна искать программы в каталогах: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Когда вы вводите **команду** в терминале, операционная система **ищет** программу в **каждой из тех директорий**, которые перечислены в переменной окружения `PATH`. + +Например, когда вы вводите `python` в терминале, операционная система ищет программу под названием `python` в **первой директории** в этом списке. + +Если она ее находит, то **использует ее**. В противном случае она продолжает искать в **других каталогах**. + +### Установка Python и обновление `PATH` + +При установке Python вас могут спросить, нужно ли обновить переменную окружения `PATH`. + +//// tab | Linux, macOS + +Допустим, вы устанавливаете Python, и он оказывается в каталоге `/opt/custompython/bin`. + +Если вы скажете «да», чтобы обновить переменную окружения `PATH`, то программа установки добавит `/opt/custompython/bin` в переменную окружения `PATH`. + +Это может выглядеть следующим образом: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Таким образом, когда вы набираете `python` в терминале, система найдет программу Python в `/opt/custompython/bin` (последний каталог) и использует ее. + +//// + +//// tab | Windows + +Допустим, вы устанавливаете Python, и он оказывается в каталоге `C:\opt\custompython\bin`. + +Если вы согласитесь обновить переменную окружения `PATH`, то программа установки добавит `C:\opt\custompython\bin` в переменную окружения `PATH`. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Таким образом, когда вы набираете `python` в терминале, система найдет программу Python в `C:\opt\custompython\bin` (последний каталог) и использует ее. + +//// + +Итак, если вы напечатаете: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +Система **найдет** программу `python` в `/opt/custompython/bin` и запустит ее. + +Это примерно эквивалентно набору текста: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +Система **найдет** программу `python` в каталоге `C:\opt\custompython\bin\python` и запустит ее. + +Это примерно эквивалентно набору текста: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +Эта информация будет полезна при изучении [Виртуальных окружений](virtual-environments.md){.internal-link target=_blank}. + +## Вывод + +Благодаря этому вы должны иметь базовое представление о том, что такое **переменные окружения** и как использовать их в Python. + +Подробнее о них вы также можете прочитать в статье о переменных окружения на википедии. + +Во многих случаях не всегда очевидно, как переменные окружения могут быть полезны и применимы. Но они постоянно появляются в различных сценариях разработки, поэтому знать о них полезно. + +Например, эта информация понадобится вам в следующем разделе, посвященном [Виртуальным окружениям](virtual-environments.md). diff --git a/docs/ru/docs/external-links.md b/docs/ru/docs/external-links.md deleted file mode 100644 index 2448ef82e..000000000 --- a/docs/ru/docs/external-links.md +++ /dev/null @@ -1,33 +0,0 @@ -# Внешние ссылки и статьи - -**FastAPI** имеет отличное и постоянно растущее сообщество. - -Существует множество сообщений, статей, инструментов и проектов, связанных с **FastAPI**. - -Вот неполный список некоторых из них. - -!!! tip - Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте Pull Request. - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Проекты - -Последние GitHub-проекты с пометкой `fastapi`: - -
-
diff --git a/docs/ru/docs/fastapi-people.md b/docs/ru/docs/fastapi-people.md deleted file mode 100644 index 0e42aab69..000000000 --- a/docs/ru/docs/fastapi-people.md +++ /dev/null @@ -1,180 +0,0 @@ - -# Люди, поддерживающие FastAPI - -У FastAPI замечательное сообщество, которое доброжелательно к людям с любым уровнем знаний. - -## Создатель и хранитель - -Хай! 👋 - -Это я: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Я создал и продолжаю поддерживать **FastAPI**. Узнать обо мне больше можно тут [Помочь FastAPI - Получить помощь - Связаться с автором](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -... но на этой странице я хочу показать вам наше сообщество. - ---- - -**FastAPI** получает огромную поддержку от своего сообщества. И я хочу отметить вклад его участников. - -Это люди, которые: - -* [Помогают другим с их проблемами (вопросами) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Создают пул-реквесты](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Делают ревью пул-реквестов, [что особенно важно для переводов на другие языки](contributing.md#translations){.internal-link target=_blank}. - -Поаплодируем им! 👏 🙇 - -## Самые активные участники за прошедший месяц - -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} в течение последнего месяца. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Эксперты - -Здесь представлены **Эксперты FastAPI**. 🤓 - -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} за *всё время*. - -Оказывая помощь многим другим, они подтвердили свой уровень знаний. ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Рейтинг участников, внёсших вклад в код - -Здесь представлен **Рейтинг участников, внёсших вклад в код**. 👷 - -Эти люди [сделали наибольшее количество пул-реквестов](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}, *включённых в основной код*. - -Они сделали наибольший вклад в исходный код, документацию, переводы и т.п. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -На самом деле таких людей довольно много (более сотни), вы можете увидеть всех на этой странице FastAPI GitHub Contributors page. 👷 - -## Рейтинг ревьюеров - -Здесь представлен **Рейтинг ревьюеров**. 🕵️ - -### Проверки переводов на другие языки - -Я знаю не очень много языков (и не очень хорошо 😅). -Итак, ревьюеры - это люди, которые могут [**подтвердить предложенный вами перевод** документации](contributing.md#translations){.internal-link target=_blank}. Без них не было бы документации на многих языках. - ---- - -В **Рейтинге ревьюеров** 🕵️ представлены те, кто проверил наибольшее количество пул-реквестов других участников, обеспечивая качество кода, документации и, особенно, **переводов на другие языки**. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Спонсоры - -Здесь представлены **Спонсоры**. 😎 - -Спонсоры поддерживают мою работу над **FastAPI** (и другими проектами) главным образом через GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Золотые спонсоры - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Серебрянные спонсоры - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Бронзовые спонсоры - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Индивидуальные спонсоры - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## О данных - технические детали - -Основная цель этой страницы - подчеркнуть усилия сообщества по оказанию помощи другим. - -Особенно это касается усилий, которые обычно менее заметны и во многих случаях более трудоемки, таких как помощь другим в решении проблем и проверка пул-реквестов с переводами. - -Данные рейтинги подсчитываются каждый месяц, ознакомиться с тем, как это работает можно тут. - -Кроме того, я также подчеркиваю вклад спонсоров. - -И я оставляю за собой право обновлять алгоритмы подсчёта, виды рейтингов, пороговые значения и т.д. (так, на всякий случай 🤷). diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index 110c7d31e..77d6b936a 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -66,10 +66,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! Информация - `**second_user_data` означает: +/// info | Информация - Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` . +`**second_user_data` означает: + +Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` . + +/// ### Поддержка редакторов (IDE) diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md index 3ad3e6fd4..474b3d689 100644 --- a/docs/ru/docs/help-fastapi.md +++ b/docs/ru/docs/help-fastapi.md @@ -26,13 +26,13 @@ ## Добавить **FastAPI** звезду на GitHub -Вы можете добавить FastAPI "звезду" на GitHub (кликнуть на кнопку звезды в верхнем правом углу экрана): https://github.com/tiangolo/fastapi. ⭐️ +Вы можете добавить FastAPI "звезду" на GitHub (кликнуть на кнопку звезды в верхнем правом углу экрана): https://github.com/fastapi/fastapi. ⭐️ Чем больше звёзд, тем легче другим пользователям найти нас и увидеть, что проект уже стал полезным для многих. ## Отслеживать свежие выпуски в репозитории на GitHub -Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): https://github.com/tiangolo/fastapi. 👀 +Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): https://github.com/fastapi/fastapi. 👀 Там же Вы можете указать в настройках - "Releases only". @@ -59,7 +59,7 @@ ## Оставить сообщение в Twitter о **FastAPI** -Оставьте сообщение в Twitter о **FastAPI** и позвольте мне и другим узнать - почему он Вам нравится. 🎉 +Оставьте сообщение в Twitter о **FastAPI** и позвольте мне и другим узнать - почему он Вам нравится. 🎉 Я люблю узнавать о том, как **FastAPI** используется, что Вам понравилось в нём, в каких проектах/компаниях Вы используете его и т.п. @@ -71,9 +71,9 @@ ## Помочь другим с их проблемами на GitHub -Вы можете посмотреть, какие проблемы испытывают другие люди и попытаться помочь им. Чаще всего это вопросы, на которые, весьма вероятно, Вы уже знаете ответ. 🤓 +Вы можете посмотреть, какие проблемы испытывают другие люди и попытаться помочь им. Чаще всего это вопросы, на которые, весьма вероятно, Вы уже знаете ответ. 🤓 -Если Вы будете много помогать людям с решением их проблем, Вы можете стать официальным [Экспертом FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. 🎉 +Если Вы будете много помогать людям с решением их проблем, Вы можете стать официальным [Экспертом FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. 🎉 Только помните, самое важное при этом - доброта. Столкнувшись с проблемой, люди расстраиваются и часто задают вопросы не лучшим образом, но постарайтесь быть максимально доброжелательным. 🤗 @@ -117,7 +117,7 @@ ## Отслеживать репозиторий на GitHub -Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): https://github.com/tiangolo/fastapi. 👀 +Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): https://github.com/fastapi/fastapi. 👀 Если Вы выберете "Watching" вместо "Releases only", то будете получать уведомления когда кто-либо попросит о помощи с решением его проблемы. @@ -125,7 +125,7 @@ ## Запросить помощь с решением проблемы -Вы можете создать новый запрос с просьбой о помощи в репозитории на GitHub, например: +Вы можете создать новый запрос с просьбой о помощи в репозитории на GitHub, например: * Задать **вопрос** или попросить помощи в решении **проблемы**. * Предложить новое **улучшение**. @@ -162,12 +162,15 @@ * Затем, используя **комментарий**, сообщите, что Вы сделали проверку, тогда я буду знать, что Вы действительно проверили код. -!!! Информация - К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. +/// info | Информация - Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅 +К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. - Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓 +Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅 + +Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓 + +/// * Если Вы считаете, что пул-реквест можно упростить, то можете попросить об этом, но не нужно быть слишком придирчивым, может быть много субъективных точек зрения (и у меня тоже будет своя 🙈), поэтому будет лучше, если Вы сосредоточитесь на фундаментальных вещах. @@ -188,9 +191,9 @@ Вы можете [сделать вклад](contributing.md){.internal-link target=_blank} в код фреймворка используя пул-реквесты, например: * Исправить опечатку, которую Вы нашли в документации. -* Поделиться статьёй, видео или подкастом о FastAPI, которые Вы создали или нашли изменив этот файл. +* Поделиться статьёй, видео или подкастом о FastAPI, которые Вы создали или нашли изменив этот файл. * Убедитесь, что Вы добавили свою ссылку в начало соответствующего раздела. -* Помочь с [переводом документации](contributing.md#translations){.internal-link target=_blank} на Ваш язык. +* Помочь с [переводом документации](contributing.md#_8){.internal-link target=_blank} на Ваш язык. * Вы также можете проверять переводы сделанные другими. * Предложить новые разделы документации. * Исправить существующуе проблемы/баги. @@ -207,8 +210,8 @@ Основные задачи, которые Вы можете выполнить прямо сейчас: -* [Помочь другим с их проблемами на GitHub](#help-others-with-issues-in-github){.internal-link target=_blank} (смотрите вышестоящую секцию). -* [Проверить пул-реквесты](#review-pull-requests){.internal-link target=_blank} (смотрите вышестоящую секцию). +* [Помочь другим с их проблемами на GitHub](#github_1){.internal-link target=_blank} (смотрите вышестоящую секцию). +* [Проверить пул-реквесты](#-){.internal-link target=_blank} (смотрите вышестоящую секцию). Эти две задачи **отнимают больше всего времени**. Это основная работа по поддержке FastAPI. @@ -218,10 +221,13 @@ Подключайтесь к 👥 чату в Discord 👥 и общайтесь с другими участниками сообщества FastAPI. -!!! Подсказка - Вопросы по проблемам с фреймворком лучше задавать в GitHub issues, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. +/// tip | Подсказка + +Вопросы по проблемам с фреймворком лучше задавать в GitHub issues, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. + +Используйте этот чат только для бесед на отвлечённые темы. - Используйте этот чат только для бесед на отвлечённые темы. +/// ### Не использовать чаты для вопросов @@ -229,7 +235,7 @@ В разделе "проблемы" на GitHub, есть шаблон, который поможет Вам написать вопрос правильно, чтобы Вам было легче получить хороший ответ или даже решить проблему самостоятельно, прежде чем Вы зададите вопрос. В GitHub я могу быть уверен, что всегда отвечаю на всё, даже если это займет какое-то время. И я не могу сделать то же самое в чатах. 😅 -Кроме того, общение в чатах не так легкодоступно для поиска, как в GitHub, потому вопросы и ответы могут потеряться среди другого общения. И только проблемы решаемые на GitHub учитываются в получении лычки [Эксперт FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, так что весьма вероятно, что Вы получите больше внимания на GitHub. +Кроме того, общение в чатах не так легкодоступно для поиска, как в GitHub, потому вопросы и ответы могут потеряться среди другого общения. И только проблемы решаемые на GitHub учитываются в получении лычки [Эксперт FastAPI](fastapi-people.md#_3){.internal-link target=_blank}, так что весьма вероятно, что Вы получите больше внимания на GitHub. С другой стороны, в чатах тысячи пользователей, а значит есть большие шансы в любое время найти там кого-то, с кем можно поговорить. 😄 diff --git a/docs/ru/docs/history-design-future.md b/docs/ru/docs/history-design-future.md index e9572a6d6..96604e3a4 100644 --- a/docs/ru/docs/history-design-future.md +++ b/docs/ru/docs/history-design-future.md @@ -1,6 +1,6 @@ # История создания и дальнейшее развитие -Однажды, один из пользователей **FastAPI** задал вопрос: +Однажды, один из пользователей **FastAPI** задал вопрос: > Какова история этого проекта? Создаётся впечатление, что он явился из ниоткуда и завоевал мир за несколько недель [...] diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 477567af6..5ebe1494b 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ Готовый к внедрению высокопроизводительный фреймворк, простой в изучении и разработке.

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +29,11 @@ **Документация**: https://fastapi.tiangolo.com -**Исходный код**: https://github.com/tiangolo/fastapi +**Исходный код**: https://github.com/fastapi/fastapi --- -FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python 3.8+, в основе которого лежит стандартная аннотация типов Python. +FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python, в основе которого лежит стандартная аннотация типов Python. Ключевые особенности: @@ -63,7 +69,7 @@ FastAPI — это современный, быстрый (высокопрои "_В последнее время я много где использую **FastAPI**. [...] На самом деле я планирую использовать его для всех **сервисов машинного обучения моей команды в Microsoft**. Некоторые из них интегрируются в основной продукт **Windows**, а некоторые — в продукты **Office**._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -87,7 +93,7 @@ FastAPI — это современный, быстрый (высокопрои "_Честно говоря, то, что вы создали, выглядит очень солидно и отполировано. Во многих смыслах я хотел, чтобы **Hug** был именно таким — это действительно вдохновляет, когда кто-то создаёт такое._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -109,8 +115,6 @@ FastAPI — это современный, быстрый (высокопрои ## Зависимости -Python 3.8+ - FastAPI стоит на плечах гигантов: * Starlette для части связанной с вебом. @@ -128,7 +132,7 @@ $ pip install fastapi
-Вам также понадобится сервер ASGI для производства, такой как Uvicorn или Hypercorn. +Вам также понадобится сервер ASGI для производства, такой как Uvicorn или Hypercorn.
@@ -325,7 +329,7 @@ def update_item(item_id: int, item: Item): Вам не нужно изучать новый синтаксис, методы или классы конкретной библиотеки и т. д. -Только стандартный **Python 3.8+**. +Только стандартный **Python**. Например, для `int`: @@ -439,7 +443,7 @@ item: Item Используется Pydantic: -* email_validator - для проверки электронной почты. +* email-validator - для проверки электронной почты. Используется Starlette: @@ -448,12 +452,12 @@ item: Item * python-multipart - Обязательно, если вы хотите поддерживать форму "парсинга" с помощью `request.form()`. * itsdangerous - Обязательно, для поддержки `SessionMiddleware`. * pyyaml - Обязательно, для поддержки `SchemaGenerator` Starlette (возможно, вам это не нужно с FastAPI). -* ujson - Обязательно, если вы хотите использовать `UJSONResponse`. Используется FastAPI / Starlette: * uvicorn - сервер, который загружает и обслуживает ваше приложение. * orjson - Обязательно, если вы хотите использовать `ORJSONResponse`. +* ujson - Обязательно, если вы хотите использовать `UJSONResponse`. Вы можете установить все это с помощью `pip install "fastapi[all]"`. diff --git a/docs/ru/docs/project-generation.md b/docs/ru/docs/project-generation.md index 76253d6f2..efd6794ad 100644 --- a/docs/ru/docs/project-generation.md +++ b/docs/ru/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: **FastAPI**: +* Бэкенд построен на фреймворке **FastAPI**: * **Быстрый**: Высокопроизводительный, на уровне **NodeJS** и **Go** (благодаря Starlette и Pydantic). * **Интуитивно понятный**: Отличная поддержка редактора. Автодополнение кода везде. Меньше времени на отладку. * **Простой**: Разработан так, чтоб быть простым в использовании и изучении. Меньше времени на чтение документации. diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index 3c8492c67..e5905304a 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -12,15 +12,18 @@ Python имеет поддержку необязательных аннотац Но даже если вы никогда не используете **FastAPI**, вам будет полезно немного узнать о них. -!!! note - Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу. +/// note + +Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу. + +/// ## Мотивация Давайте начнем с простого примера: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Вызов этой программы выводит: @@ -36,7 +39,7 @@ John Doe * Соединяет их через пробел. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Отредактируем пример @@ -80,7 +83,7 @@ John Doe Это аннотации типов: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Это не то же самое, что объявление значений по умолчанию, например: @@ -110,7 +113,7 @@ John Doe Проверьте эту функцию, она уже имеет аннотации типов: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок: @@ -120,7 +123,7 @@ John Doe Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Объявление типов @@ -141,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generic-типы с параметрами типов @@ -159,7 +162,7 @@ John Doe Импортируйте `List` из `typing` (с заглавной `L`): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Объявите переменную с тем же синтаксисом двоеточия (`:`). @@ -169,13 +172,16 @@ John Doe Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` -!!! tip - Эти внутренние типы в квадратных скобках называются «параметрами типов». +/// tip + +Эти внутренние типы в квадратных скобках называются «параметрами типов». + +В этом случае `str` является параметром типа, передаваемым в `List`. - В этом случае `str` является параметром типа, передаваемым в `List`. +/// Это означает: "переменная `items` является `list`, и каждый из элементов этого списка является `str`". @@ -194,7 +200,7 @@ John Doe Вы бы сделали то же самое, чтобы объявить `tuple` и `set`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Это означает: @@ -211,7 +217,7 @@ John Doe Второй параметр типа предназначен для значений `dict`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Это означает: @@ -225,7 +231,7 @@ John Doe Вы также можете использовать `Optional`, чтобы объявить, что переменная имеет тип, например, `str`, но это является «необязательным», что означает, что она также может быть `None`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Использование `Optional[str]` вместо просто `str` позволит редактору помочь вам в обнаружении ошибок, в которых вы могли бы предположить, что значение всегда является `str`, хотя на самом деле это может быть и `None`. @@ -250,13 +256,13 @@ John Doe Допустим, у вас есть класс `Person` с полем `name`: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Тогда вы можете объявить переменную типа `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` И снова вы получаете полную поддержку редактора: @@ -278,11 +284,14 @@ John Doe Взято из официальной документации Pydantic: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` -!!! info - Чтобы узнать больше о Pydantic, читайте его документацию. +/// info + +Чтобы узнать больше о Pydantic, читайте его документацию. + +/// **FastAPI** целиком основан на Pydantic. @@ -310,5 +319,8 @@ John Doe Важно то, что при использовании стандартных типов Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.) **FastAPI** сделает за вас большую часть работы. -!!! info - Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`. +/// info + +Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`. + +/// diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 73ba860bc..0f6ce0eb3 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр. @@ -34,7 +34,7 @@ Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Добавление фоновой задачи @@ -42,7 +42,7 @@ Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` принимает следующие аргументы: @@ -57,17 +57,21 @@ **FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +```Python hl_lines="11 13 20 23" +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="13 15 22 25" +{!> ../../docs_src/background_tasks/tutorial002.py!} +``` - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +//// В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен. diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index 02a598004..0c4cbb09c 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -6,50 +6,67 @@ Сначала вы должны импортировать его: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +```Python hl_lines="2" +{!> ../../docs_src/body_fields/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +//// tab | Python 3.8+ -!!! warning "Внимание" - Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.). +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | Внимание + +Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.). + +/// ## Объявление атрибутов модели Вы можете использовать функцию `Field` с атрибутами модели: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9-12" +{!> ../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +//// Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д. -!!! note "Технические детали" - На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. +/// note | Технические детали - И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`. +На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. - У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже. +И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`. - Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. +У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже. -!!! tip "Подсказка" - Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`. +Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. + +/// + +/// tip | Подсказка + +Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`. + +/// ## Добавление дополнительной информации @@ -58,9 +75,12 @@ Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры принимаемых данных. -!!! warning "Внимание" - Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения. - Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой. +/// warning | Внимание + +Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения. +Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой. + +/// ## Резюме diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index e52ef6f6f..594e1dbca 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ Вы также можете объявить параметры тела запроса как необязательные, установив значение по умолчанию, равное `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="18-20" +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// tip | Заметка + +Рекомендуется использовать `Annotated` версию, если это возможно. + +/// + +```Python hl_lines="17-19" +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +/// tip | Заметка -!!! Заметка - Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. +Рекомендуется использовать версию с `Annotated`, если это возможно. + +/// + +```Python hl_lines="19-21" +{!> ../../docs_src/body_multiple_params/tutorial001.py!} +``` + +//// + +/// note | Заметка + +Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. + +/// ## Несколько параметров тела запроса @@ -62,17 +81,21 @@ Но вы также можете объявить множество параметров тела запроса, например `item` и `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../docs_src/body_multiple_params/tutorial002.py!} +``` + +//// В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются моделями Pydantic). @@ -93,9 +116,11 @@ } ``` -!!! Внимание - Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. +/// note | Внимание + +Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. +/// **FastAPI** сделает автоматические преобразование из запроса, так что параметр `item` получит своё конкретное содержимое, и то же самое происходит с пользователем `user`. @@ -111,41 +136,57 @@ Но вы можете указать **FastAPI** обрабатывать его, как ещё один ключ тела запроса, используя `Body`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="23" +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +/// tip | Заметка -=== "Python 3.8+" +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="20" +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | Заметка - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +/// + +```Python hl_lines="22" +{!> ../../docs_src/body_multiple_params/tutorial003.py!} +``` + +//// В этом случае, **FastAPI** будет ожидать тело запроса в формате: @@ -185,44 +226,63 @@ q: str | None = None Например: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="27" +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="27" +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Заметка + +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +/// -=== "Python 3.9+" +```Python hl_lines="25" +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +/// tip | Заметка -=== "Python 3.10+ non-Annotated" +Рекомендуется использовать `Annotated` версию, если это возможно. - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. +/// - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +```Python hl_lines="27" +{!> ../../docs_src/body_multiple_params/tutorial004.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. +/// info | Информация - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +`Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. -!!! Информация - `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. +/// ## Добавление одного body-параметра @@ -238,41 +298,57 @@ item: Item = Body(embed=True) так же, как в этом примере: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip | Заметка -=== "Python 3.9+" +Рекомендуется использовать `Annotated` версию, если это возможно. - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. +/// tip | Заметка - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +Рекомендуется использовать `Annotated` версию, если это возможно. -=== "Python 3.8+ non-Annotated" +/// - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. +```Python hl_lines="17" +{!> ../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// В этом случае **FastAPI** будет ожидать тело запроса в формате: diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index 51a32ba56..9abd4f432 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ Вы можете определять атрибут как подтип. Например, тип `list` в Python: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial001.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +//// Это приведёт к тому, что обьект `tags` преобразуется в список, несмотря на то что тип его элементов не объявлен. @@ -31,7 +35,7 @@ Но в версиях Python до 3.9 (начиная с 3.6) сначала вам необходимо импортировать `List` из стандартного модуля `typing` в Python: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### Объявление `list` с указанием типов для вложенных элементов @@ -61,23 +65,29 @@ my_list: List[str] Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как "список строк": -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial002.py!} +``` + +//// ## Типы множеств @@ -87,23 +97,29 @@ my_list: List[str] Тогда мы можем обьявить поле `tags` как множество строк: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// + +//// tab | Python 3.9+ + +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 14" +{!> ../../docs_src/body_nested_models/tutorial003.py!} +``` - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +//// С помощью этого, даже если вы получите запрос с повторяющимися данными, они будут преобразованы в множество уникальных элементов. @@ -125,45 +141,57 @@ my_list: List[str] Например, мы можем определить модель `Image`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-9" +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9-11" +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-11" +{!> ../../docs_src/body_nested_models/tutorial004.py!} +``` - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// ### Использование вложенной модели в качестве типа Также мы можем использовать эту модель как тип атрибута: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// Это означает, что **FastAPI** будет ожидать тело запроса, аналогичное этому: @@ -196,23 +224,29 @@ my_list: List[str] Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8" +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +```Python hl_lines="4 10" +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10" +{!> ../../docs_src/body_nested_models/tutorial005.py!} +``` - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +//// Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON схему / OpenAPI. @@ -220,23 +254,29 @@ my_list: List[str] Вы также можете использовать модели Pydantic в качестве типов вложенных в `list`, `set` и т.д: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д) JSON-содержимое в следующем формате: @@ -264,33 +304,45 @@ my_list: List[str] } ``` -!!! info "Информация" - Заметьте, что теперь у ключа `images` есть список объектов изображений. +/// info | Информация + +Заметьте, что теперь у ключа `images` есть список объектов изображений. + +/// ## Глубоко вложенные модели Вы можете определять модели с произвольным уровнем вложенности: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 12 18 21 25" +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} +``` + +//// - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9 14 20 23 27" +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14 20 23 27" +{!> ../../docs_src/body_nested_models/tutorial007.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info | Информация - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image` -!!! info "Информация" - Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image` +/// ## Тела с чистыми списками элементов @@ -308,17 +360,21 @@ images: list[Image] например так: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +```Python hl_lines="15" +{!> ../../docs_src/body_nested_models/tutorial008.py!} +``` + +//// ## Универсальная поддержка редактора @@ -348,26 +404,33 @@ images: list[Image] В этом случае вы принимаете `dict`, пока у него есть ключи типа `int` со значениями типа `float`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/body_nested_models/tutorial009.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +//// -=== "Python 3.8+" +/// tip | Совет - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +Имейте в виду, что JSON поддерживает только ключи типа `str`. -!!! tip "Совет" - Имейте в виду, что JSON поддерживает только ключи типа `str`. +Но Pydantic обеспечивает автоматическое преобразование данных. - Но Pydantic обеспечивает автоматическое преобразование данных. +Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные. - Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные. +А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`. - А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md index 4998ab31a..c80952f70 100644 --- a/docs/ru/docs/tutorial/body-updates.md +++ b/docs/ru/docs/tutorial/body-updates.md @@ -6,23 +6,29 @@ Вы можете использовать функцию `jsonable_encoder` для преобразования входных данных в JSON, так как нередки случаи, когда работать можно только с простыми типами данных (например, для хранения в NoSQL-базе данных). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="28-33" - {!> ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +```Python hl_lines="28-33" +{!> ../../docs_src/body_updates/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-35" +{!> ../../docs_src/body_updates/tutorial001_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="30-35" +{!> ../../docs_src/body_updates/tutorial001.py!} +``` - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` +//// `PUT` используется для получения данных, которые должны полностью заменить существующие данные. @@ -48,14 +54,17 @@ Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми. -!!! note "Технические детали" - `PATCH` менее распространен и известен, чем `PUT`. +/// note | Технические детали + +`PATCH` менее распространен и известен, чем `PUT`. + +А многие команды используют только `PUT`, даже для частичного обновления. - А многие команды используют только `PUT`, даже для частичного обновления. +Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений. - Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений. +Но в данном руководстве более или менее понятно, как они должны использоваться. - Но в данном руководстве более или менее понятно, как они должны использоваться. +/// ### Использование параметра `exclude_unset` в Pydantic @@ -65,23 +74,29 @@ В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +```Python hl_lines="32" +{!> ../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +```Python hl_lines="34" +{!> ../../docs_src/body_updates/tutorial002_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// tab | Python 3.6+ + +```Python hl_lines="34" +{!> ../../docs_src/body_updates/tutorial002.py!} +``` + +//// ### Использование параметра `update` в Pydantic @@ -89,23 +104,29 @@ Например, `stored_item_model.copy(update=update_data)`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="33" +{!> ../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// tab | Python 3.9+ + +```Python hl_lines="35" +{!> ../../docs_src/body_updates/tutorial002_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="35" +{!> ../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +//// ### Кратко о частичном обновлении @@ -122,32 +143,44 @@ * Сохранить данные в своей БД. * Вернуть обновленную модель. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="28-35" +{!> ../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-37" +{!> ../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="30-37" +{!> ../../docs_src/body_updates/tutorial002.py!} +``` - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +//// -=== "Python 3.9+" +/// tip | Подсказка - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +Эту же технику можно использовать и для операции HTTP `PUT`. -=== "Python 3.6+" +Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования. - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +/// -!!! tip "Подсказка" - Эту же технику можно использовать и для операции HTTP `PUT`. +/// note | Технические детали - Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования. +Обратите внимание, что входная модель по-прежнему валидируется. -!!! note "Технические детали" - Обратите внимание, что входная модель по-прежнему валидируется. +Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`). - Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`). +Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}. - Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}. +/// diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index 96f80af06..62927f0d1 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -8,19 +8,22 @@ Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами. -!!! info "Информация" - Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. +/// info | Информация - Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования. +Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. - Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса. +Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования. + +Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса. + +/// ## Импортирование `BaseModel` из Pydantic Первое, что вам необходимо сделать, это импортировать `BaseModel` из пакета `pydantic`: ```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ## Создание вашей собственной модели @@ -30,7 +33,7 @@ Используйте аннотации типов Python для всех атрибутов: ```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` Также как и при описании параметров запроса, когда атрибут модели имеет значение по умолчанию, он является необязательным. Иначе он обязателен. Используйте `None`, чтобы сделать его необязательным без использования конкретных значений по умолчанию. @@ -60,7 +63,7 @@ Чтобы добавить параметр к вашему *обработчику*, объявите его также, как вы объявляли параметры пути или параметры запроса: ```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ...и укажите созданную модель в качестве типа параметра, `Item`. @@ -110,23 +113,26 @@ -!!! tip "Подсказка" - Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin. +/// tip | Подсказка + +Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin. - Он улучшает поддержку редактором моделей Pydantic в части: +Он улучшает поддержку редактором моделей Pydantic в части: - * автодополнения, - * проверки типов, - * рефакторинга, - * поиска, - * инспектирования. +* автодополнения, +* проверки типов, +* рефакторинга, +* поиска, +* инспектирования. + +/// ## Использование модели Внутри функции вам доступны все атрибуты объекта модели напрямую: ```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} +{!../../docs_src/body/tutorial002.py!} ``` ## Тело запроса + параметры пути @@ -136,7 +142,7 @@ **FastAPI** распознает, какие параметры функции соответствуют параметрам пути и должны быть **получены из пути**, а какие параметры функции, объявленные как модели Pydantic, должны быть **получены из тела запроса**. ```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} +{!../../docs_src/body/tutorial003.py!} ``` ## Тело запроса + параметры пути + параметры запроса @@ -146,7 +152,7 @@ **FastAPI** распознает каждый из них и возьмет данные из правильного источника. ```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} +{!../../docs_src/body/tutorial004.py!} ``` Параметры функции распознаются следующим образом: @@ -155,11 +161,14 @@ * Если аннотация типа параметра содержит **примитивный тип** (`int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**. * Если аннотация типа параметра представляет собой **модель Pydantic**, он будет интерпретирован как параметр **тела запроса**. -!!! note "Заметка" - FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`. +/// note | Заметка + +FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`. + +Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки. - Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки. +/// ## Без Pydantic -Если вы не хотите использовать модели Pydantic, вы все еще можете использовать параметры **тела запроса**. Читайте в документации раздел [Тело - Несколько параметров: Единичные значения в теле](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. +Если вы не хотите использовать модели Pydantic, вы все еще можете использовать параметры **тела запроса**. Читайте в документации раздел [Тело - Несколько параметров: Единичные значения в теле](body-multiple-params.md#_2){.internal-link target=_blank}. diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index 5f99458b6..88533f7f8 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -6,17 +6,21 @@ Сначала импортируйте `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## Объявление параметров `Cookie` @@ -24,25 +28,35 @@ Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +/// note | Технические детали - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +`Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`. -=== "Python 3.8+" +Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Технические детали" - `Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`. +/// info | Дополнительная информация - Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. +Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса. -!!! info "Дополнительная информация" - Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md index 8c7fbc046..622cd5a98 100644 --- a/docs/ru/docs/tutorial/cors.md +++ b/docs/ru/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * Отдельных HTTP-заголовков или всех вместе, используя `"*"`. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` `CORSMiddleware` использует для параметров "запрещающие" значения по умолчанию, поэтому вам нужно явным образом разрешить использование отдельных источников, методов или заголовков, чтобы браузеры могли использовать их в кросс-доменном контексте. @@ -78,7 +78,10 @@ Для получения более подробной информации о CORS, обратитесь к Документации CORS от Mozilla. -!!! note "Технические детали" - Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`. +/// note | Технические детали - **FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette. +Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette. + +/// diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 38709e56d..0feeaa20c 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ В вашем FastAPI приложении, импортируйте и вызовите `uvicorn` напрямую: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### Описание `__name__ == "__main__"` @@ -74,8 +74,11 @@ from myapp import app не будет выполнена. -!!! Информация - Для получения дополнительной информации, ознакомьтесь с официальной документацией Python. +/// info | Информация + +Для получения дополнительной информации, ознакомьтесь с официальной документацией Python. + +/// ## Запуск вашего кода с помощью отладчика diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md index b6ad25daf..486ff9ea9 100644 --- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,41 +6,57 @@ В предыдущем примере мы возвращали `словарь` из нашей зависимости: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +/// tip | Подсказка -=== "Python 3.10+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="7" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="11" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений. @@ -101,117 +117,165 @@ fluffy = Cat(name="Mr Fluffy") Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="11-15" +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.6+" +```Python hl_lines="11-15" +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// - ```Python hl_lines="12-16" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.10+ без Annotated" +```Python hl_lines="12-16" +{!> ../../docs_src/dependencies/tutorial002_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +/// + +```Python hl_lines="9-13" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="11-15" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` + +//// Обратите внимание на метод `__init__`, используемый для создания экземпляра класса: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="13" +{!> ../../docs_src/dependencies/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.9+" +/// tip | Подсказка - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.6+" +/// - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` -=== "Python 3.10+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.6+ без Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip | Подсказка -=== "Python 3.6+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ...имеет те же параметры, что и ранее используемая функция `common_parameters`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +//// tab | Python 3.6+ + +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` -=== "Python 3.10+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +/// tip | Подсказка -=== "Python 3.6+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="6" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// Эти параметры и будут использоваться **FastAPI** для "решения" зависимости. @@ -227,41 +291,57 @@ fluffy = Cat(name="Mr Fluffy") Теперь вы можете объявить свою зависимость, используя этот класс. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="20" +{!> ../../docs_src/dependencies/tutorial002_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.6+" +/// tip | Подсказка - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +/// tip | Подсказка -=== "Python 3.6+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// **FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию. @@ -269,20 +349,27 @@ fluffy = Cat(name="Mr Fluffy") Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`: -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// Последний параметр `CommonQueryParams`, в: @@ -298,77 +385,107 @@ fluffy = Cat(name="Mr Fluffy") В этом случае первый `CommonQueryParams`, в: -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// - ```Python - commons: Annotated[CommonQueryParams, ... - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python - commons: CommonQueryParams ... - ``` +/// + +```Python +commons: CommonQueryParams ... +``` + +//// ...не имеет никакого специального значения для **FastAPI**. FastAPI не будет использовать его для преобразования данных, валидации и т.д. (поскольку для этого используется `Depends(CommonQueryParams)`). На самом деле можно написать просто: -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[Any, Depends(CommonQueryParams)] - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python - commons = Depends(CommonQueryParams) - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// ...как тут: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../docs_src/dependencies/tutorial003_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} - ``` +/// tip | Подсказка -=== "Python 3.6+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial003_an.py!} - ``` +/// -=== "Python 3.10+ без Annotated" +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial003_py310.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +/// + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial003.py!} +``` + +//// Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д: @@ -378,101 +495,141 @@ fluffy = Cat(name="Mr Fluffy") Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`: -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// Для случаев, когда зависимостью является *конкретный* класс, который **FastAPI** "вызовет" для создания экземпляра этого класса, можно использовать укороченную запись. Вместо того чтобы писать: -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// ...следует написать: -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python - commons: Annotated[CommonQueryParams, Depends()] - ``` +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` -=== "Python 3.6 без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.6 без Annotated - ```Python - commons: CommonQueryParams = Depends() - ``` +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`. Аналогичный пример будет выглядеть следующим образом: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.9+" +```Python hl_lines="20" +{!> ../../docs_src/dependencies/tutorial004_an.py!} +``` + +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.6+" +/// tip | Подсказка - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial004_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial004_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial004.py!} +``` + +//// ...и **FastAPI** будет знать, что делать. -!!! tip "Подсказка" - Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. +/// tip | Подсказка + +Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. + +Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода. - Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода. +/// diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..305ce46cb --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,181 @@ +# Зависимости в декораторах операции пути + +В некоторых случаях, возвращаемое значение зависимости не используется внутри *функции операции пути*. + +Или же зависимость не возвращает никакого значения. + +Но вам всё-таки нужно, чтобы она выполнилась. + +Для таких ситуаций, вместо объявления *функции операции пути* с параметром `Depends`, вы можете добавить список зависимостей `dependencies` в *декоратор операции пути*. + +## Добавление `dependencies` в *декоратор операции пути* + +*Декоратор операции пути* получает необязательный аргумент `dependencies`. + +Это должен быть `list` состоящий из `Depends()`: + +//// tab | Python 3.9+ + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8 без Annotated + +/// подсказка + +Рекомендуется использовать версию с Annotated, если возможно. + +/// + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// + +Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*. + +/// подсказка + +Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку. + +Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов. + +Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости. + +/// + +/// дополнительная | информация + +В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`. + +Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}. + +/// + +## Исключения в dependencies и возвращаемые значения + +Вы можете использовать те же *функции* зависимостей, что и обычно. + +### Требования к зависимостям + +Они могут объявлять требования к запросу (например заголовки) или другие подзависимости: + +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7 12" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8 без Annotated + +/// подсказка + +Рекомендуется использовать версию с Annotated, если возможно. + +/// + +```Python hl_lines="6 11" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// + +### Вызов исключений + +Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости: + +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8 без Annotated + +/// подсказка + +Рекомендуется использовать версию с Annotated, если возможно. + +/// + +```Python hl_lines="8 13" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// + +### Возвращаемые значения + +И они могут возвращать значения или нет, эти значения использоваться не будут. + +Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена: + +//// tab | Python 3.9+ + +```Python hl_lines="11 16" +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../docs_src/dependencies/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8 без Annotated + +/// подсказка + +Рекомендуется использовать версию с Annotated, если возможно. + +/// + +```Python hl_lines="9 14" +{!> ../../docs_src/dependencies/tutorial006.py!} +``` + +//// + +## Dependencies для группы *операций путей* + +Позже, читая о том как структурировать большие приложения ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), возможно, многофайловые, вы узнаете как объявить единый параметр `dependencies` для всей группы *операций путей*. + +## Глобальный Dependencies + +Далее мы увидим, как можно добавить dependencies для всего `FastAPI` приложения, так чтобы они применялись к каждой *операции пути*. diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..83f8ec0d2 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,325 @@ +# Зависимости с yield + +FastAPI поддерживает зависимости, которые выполняют некоторые дополнительные действия после завершения работы. + +Для этого используйте `yield` вместо `return`, а дополнительный код напишите после него. + +/// tip | Подсказка + +Обязательно используйте `yield` один-единственный раз. + +/// + +/// note | Технические детали + +Любая функция, с которой может работать: + +* `@contextlib.contextmanager` или +* `@contextlib.asynccontextmanager` + +будет корректно использоваться в качестве **FastAPI**-зависимости. + +На самом деле, FastAPI использует эту пару декораторов "под капотом". + +/// + +## Зависимость базы данных с помощью `yield` + +Например, с его помощью можно создать сессию работы с базой данных и закрыть его после завершения. + +Перед созданием ответа будет выполнен только код до и включая `yield`. + +```Python hl_lines="2-4" +{!../../docs_src/dependencies/tutorial007.py!} +``` + +Полученное значение и есть то, что будет внедрено в функцию операции пути и другие зависимости: + +```Python hl_lines="4" +{!../../docs_src/dependencies/tutorial007.py!} +``` + +Код, следующий за оператором `yield`, выполняется после доставки ответа: + +```Python hl_lines="5-6" +{!../../docs_src/dependencies/tutorial007.py!} +``` + +/// tip | Подсказка + +Можно использовать как `async` так и обычные функции. + +**FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями. + +/// + +## Зависимость с `yield` и `try` одновременно + +Если использовать блок `try` в зависимости с `yield`, то будет получено всякое исключение, которое было выброшено при использовании зависимости. + +Например, если какой-то код в какой-то момент в середине, в другой зависимости или в *функции операции пути*, сделал "откат" транзакции базы данных или создал любую другую ошибку, то вы получите исключение в своей зависимости. + +Таким образом, можно искать конкретное исключение внутри зависимости с помощью `except SomeException`. + +Таким же образом можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены, независимо от того, было ли исключение или нет. + +```Python hl_lines="3 5" +{!../../docs_src/dependencies/tutorial007.py!} +``` + +## Подзависимости с `yield` + +Вы можете иметь подзависимости и "деревья" подзависимостей любого размера и формы, и любая из них или все они могут использовать `yield`. + +**FastAPI** будет следить за тем, чтобы "код по выходу" в каждой зависимости с `yield` выполнялся в правильном порядке. + +Например, `dependency_c` может иметь зависимость от `dependency_b`, а `dependency_b` от `dependency_a`: + +//// tab | Python 3.9+ + +```Python hl_lines="6 14 22" +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="5 13 21" +{!> ../../docs_src/dependencies/tutorial008_an.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="4 12 20" +{!> ../../docs_src/dependencies/tutorial008.py!} +``` + +//// + +И все они могут использовать `yield`. + +В этом случае `dependency_c` для выполнения своего кода выхода нуждается в том, чтобы значение из `dependency_b` (здесь `dep_b`) было еще доступно. + +И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода. + +//// tab | Python 3.9+ + +```Python hl_lines="18-19 26-27" +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="17-18 25-26" +{!> ../../docs_src/dependencies/tutorial008_an.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="16-17 24-25" +{!> ../../docs_src/dependencies/tutorial008.py!} +``` + +//// + +Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга. + +Либо у вас может быть одна зависимость, которая требует несколько других зависимостей с `yield` и т.д. + +Комбинации зависимостей могут быть какими вам угодно. + +**FastAPI** проследит за тем, чтобы все выполнялось в правильном порядке. + +/// note | Технические детали + +Это работает благодаря Контекстным менеджерам в Python. + +/// + + **FastAPI** использует их "под капотом" с этой целью. + +## Зависимости с `yield` и `HTTPException` + +Вы видели, что можно использовать зависимости с `yield` совместно с блоком `try`, отлавливающие исключения. + +Таким же образом вы можете поднять исключение `HTTPException` или что-то подобное в завершающем коде, после `yield`. + +Код выхода в зависимостях с `yield` выполняется *после* отправки ответа, поэтому [Обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже будет запущен. В коде выхода (после `yield`) нет ничего, перехватывающего исключения, брошенные вашими зависимостями. + +Таким образом, если после `yield` возникает `HTTPException`, то стандартный (или любой пользовательский) обработчик исключений, который перехватывает `HTTPException` и возвращает ответ HTTP 400, уже не сможет перехватить это исключение. + +Благодаря этому все, что установлено в зависимости (например, сеанс работы с БД), может быть использовано, например, фоновыми задачами. + +Фоновые задачи выполняются *после* отправки ответа. Поэтому нет возможности поднять `HTTPException`, так как нет даже возможности изменить уже отправленный ответ. + +Но если фоновая задача создает ошибку в БД, то, по крайней мере, можно сделать откат или чисто закрыть сессию в зависимости с помощью `yield`, а также, возможно, занести ошибку в журнал или сообщить о ней в удаленную систему отслеживания. + +Если у вас есть код, который, как вы знаете, может вызвать исключение, сделайте самую обычную/"питонячью" вещь и добавьте блок `try` в этот участок кода. + +Если у вас есть пользовательские исключения, которые вы хотите обрабатывать *до* возврата ответа и, возможно, модифицировать ответ, даже вызывая `HTTPException`, создайте [Cобственный обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +/// tip | Подсказка + +Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после. + +/// + +Последовательность выполнения примерно такая, как на этой схеме. Время течет сверху вниз. А каждый столбец - это одна из частей, взаимодействующих с кодом или выполняющих код. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise HTTPException + dep -->> handler: Auto forward exception + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + dep -->> handler: Auto forward exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +/// info | Дополнительная информация + +Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*. + +После отправки одного из этих ответов никакой другой ответ не может быть отправлен. + +/// + +/// tip | Подсказка + +На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка. + +/// + +## Зависимости с `yield`, `HTTPException` и фоновыми задачами + +/// warning | Внимание + +Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже. + +Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах. + +/// + +До версии FastAPI 0.106.0 вызывать исключения после `yield` было невозможно, код выхода в зависимостях с `yield` выполнялся *после* отправки ответа, поэтому [Обработчик Ошибок](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже был бы запущен. + +Это было сделано главным образом для того, чтобы позволить использовать те же объекты, "отданные" зависимостями, внутри фоновых задач, поскольку код выхода будет выполняться после завершения фоновых задач. + +Тем не менее, поскольку это означало бы ожидание ответа в сети, а также ненужное удержание ресурса в зависимости от доходности (например, соединение с базой данных), это было изменено в FastAPI 0.106.0. + +/// tip | Подсказка + +Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных). +Таким образом, вы, вероятно, получите более чистый код. + +/// + +Если вы полагались на это поведение, то теперь вам следует создавать ресурсы для фоновых задач внутри самой фоновой задачи, а внутри использовать только те данные, которые не зависят от ресурсов зависимостей с `yield`. + +Например, вместо того чтобы использовать ту же сессию базы данных, вы создадите новую сессию базы данных внутри фоновой задачи и будете получать объекты из базы данных с помощью этой новой сессии. А затем, вместо того чтобы передавать объект из базы данных в качестве параметра в функцию фоновой задачи, вы передадите идентификатор этого объекта, а затем снова получите объект в функции фоновой задачи. + +## Контекстные менеджеры + +### Что такое "контекстные менеджеры" + +"Контекстные менеджеры" - это любые объекты Python, которые можно использовать в операторе `with`. + +Например, можно использовать `with` для чтения файла: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Под капотом" open("./somefile.txt") создаёт объект называемый "контекстным менеджером". + +Когда блок `with` завершается, он обязательно закрывает файл, даже если были исключения. + +Когда вы создаете зависимость с помощью `yield`, **FastAPI** внутренне преобразует ее в контекстный менеджер и объединяет с некоторыми другими связанными инструментами. + +### Использование менеджеров контекста в зависимостях с помощью `yield` + +/// warning | Внимание + +Это более или менее "продвинутая" идея. + +Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт. + +/// + +В Python для создания менеджеров контекста можно создать класс с двумя методами: `__enter__()` и `__exit__()`. + +Вы также можете использовать их внутри зависимостей **FastAPI** с `yield`, используя операторы +`with` или `async with` внутри функции зависимости: + +```Python hl_lines="1-9 13" +{!../../docs_src/dependencies/tutorial010.py!} +``` + +/// tip | Подсказка + +Другой способ создания контекстного менеджера - с помощью: + +* `@contextlib.contextmanager` или +* `@contextlib.asynccontextmanager` + +используйте их для оформления функции с одним `yield`. + +Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`. + +Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит). + +FastAPI сделает это за вас на внутреннем уровне. + +/// diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md index eb1b4d7c1..a4dfeb8ac 100644 --- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,35 @@ В этом случае они будут применяться ко всем *операциям пути* в приложении: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8 non-Annotated" +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial012_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +//// - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.py!} - ``` +//// tab | Python 3.8 non-Annotated + +/// tip | Подсказка + +Рекомендуется использовать 'Annotated' версию, если это возможно. + +/// + +```Python hl_lines="15" +{!> ../../docs_src/dependencies/tutorial012.py!} +``` + +//// Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения. diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md index ad6e835e5..b6cf7c780 100644 --- a/docs/ru/docs/tutorial/dependencies/index.md +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -29,42 +29,57 @@ Давайте для начала сфокусируемся на зависимостях. Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="8-9" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-11" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="9-12" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | Подсказка - ```Python hl_lines="9-12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. -=== "Python 3.10+ non-Annotated" +/// - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +```Python hl_lines="6-7" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip "Подсказка" +/// tip | Подсказка - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +/// + +```Python hl_lines="8-11" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` + +//// **И всё.** @@ -84,91 +99,125 @@ И в конце она возвращает `dict`, содержащий эти значения. -!!! Информация +/// info | Информация + +**FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. - **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. + Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`. - Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`. +Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. - Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. +/// ### Import `Depends` -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | Подсказка - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. -=== "Python 3.10+ non-Annotated" +/// + +```Python hl_lines="1" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +//// - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + +/// + +```Python hl_lines="3" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// ### Объявите зависимость в "зависимом" Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 18" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` +```Python hl_lines="13 18" +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="15 20" +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="16 21" +{!> ../../docs_src/dependencies/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | Подсказка - ```Python hl_lines="16 21" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. -=== "Python 3.10+ non-Annotated" +/// + +```Python hl_lines="11 16" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +//// - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. +Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. + +/// + +```Python hl_lines="15 20" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// `Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию. @@ -176,8 +225,11 @@ И потом функция берёт параметры так же, как *функция обработки пути*. -!!! tip "Подсказка" - В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. +/// tip | Подсказка + +В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. + +/// Каждый раз, когда новый запрос приходит, **FastAPI** позаботится о: @@ -198,10 +250,13 @@ common_parameters --> read_users Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*. -!!! check "Проверка" - Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. +/// check | Проверка + +Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. + +Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше. - Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше. +/// ## Объединяем с `Annotated` зависимостями @@ -215,29 +270,37 @@ commons: Annotated[dict, Depends(common_parameters)] Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12 16 21" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} - ``` +```Python hl_lines="12 16 21" +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14 18 23" - {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="14 18 23" +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} +``` - ```Python hl_lines="15 19 24" - {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} - ``` +//// -!!! tip "Подсказка" - Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. +//// tab | Python 3.8+ - Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎 +```Python hl_lines="15 19 24" +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} +``` +//// + +/// tip | Подсказка + +Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. + +Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎 + +/// Зависимости продолжат работу как ожидалось, и **лучшая часть** в том, что **информация о типе будет сохранена**. Это означает, что ваш редактор кода будет корректно обрабатывать **автодополнения**, **встроенные ошибки** и так далее. То же самое относится и к инструментам, таким как `mypy`. @@ -253,8 +316,11 @@ commons: Annotated[dict, Depends(common_parameters)] Это всё не важно. **FastAPI** знает, что нужно сделать. 😎 -!!! note "Информация" - Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. +/// note | Информация + +Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. + +/// ## Интеграция с OpenAPI diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..0e8cb20e7 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,255 @@ +# Подзависимости + +Вы можете создавать зависимости, которые имеют **подзависимости**. + +Их **вложенность** может быть любой глубины. + +**FastAPI** сам займётся их управлением. + +## Провайдер зависимости + +Можно создать первую зависимость следующим образом: + +//// tab | Python 3.10+ + +```Python hl_lines="8-9" +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-9" +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="9-10" +{!> ../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="6-7" +{!> ../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.6 без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="8-9" +{!> ../../docs_src/dependencies/tutorial005.py!} +``` + +//// + +Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его. + +Это довольно просто (хотя и не очень полезно), но поможет нам сосредоточиться на том, как работают подзависимости. + +## Вторая зависимость + +Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"): + +//// tab | Python 3.10+ + +```Python hl_lines="13" +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="14" +{!> ../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="11" +{!> ../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.6 без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="13" +{!> ../../docs_src/dependencies/tutorial005.py!} +``` + +//// + +Остановимся на объявленных параметрах: + +* Несмотря на то, что эта функция сама является зависимостью, она также является зависимой от чего-то другого. + * Она зависит от `query_extractor` и присваивает возвращаемое ей значение параметру `q`. +* Она также объявляет необязательный куки-параметр `last_query` в виде строки. + * Если пользователь не указал параметр `q` в запросе, то мы используем последний использованный запрос, который мы ранее сохранили в куки-параметре `last_query`. + +## Использование зависимости + +Затем мы можем использовать зависимость вместе с: + +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="24" +{!> ../../docs_src/dependencies/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10 без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.6 без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="22" +{!> ../../docs_src/dependencies/tutorial005.py!} +``` + +//// + +/// info | Дополнительная информация + +Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`. + +Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове. + +/// + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Использование одной и той же зависимости несколько раз + +Если одна из ваших зависимостей объявлена несколько раз для одной и той же *функции операции пути*, например, несколько зависимостей имеют общую подзависимость, **FastAPI** будет знать, что вызывать эту подзависимость нужно только один раз за запрос. + +При этом возвращаемое значение будет сохранено в "кэш" и будет передано всем "зависимым" функциям, которые нуждаются в нем внутри этого конкретного запроса, вместо того, чтобы вызывать зависимость несколько раз для одного и того же запроса. + +В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`: + +//// tab | Python 3.6+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// + +## Резюме + +Помимо всех этих умных слов, используемых здесь, система внедрения зависимостей довольно проста. + +Это просто функции, которые выглядят так же, как *функции операций путей*. + +Но, тем не менее, эта система очень мощная и позволяет вам объявлять вложенные графы (деревья) зависимостей сколь угодно глубоко. + +/// tip | Подсказка + +Все это может показаться не столь полезным на этих простых примерах. + +Но вы увидите как это пригодится в главах посвященных безопасности. + +И вы также увидите, сколько кода это вам сэкономит. + +/// diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md index c26b2c941..523644ac8 100644 --- a/docs/ru/docs/tutorial/encoder.md +++ b/docs/ru/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ Она принимает объект, например, модель Pydantic, и возвращает его версию, совместимую с JSON: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.6+ + +```Python hl_lines="5 22" +{!> ../../docs_src/encoder/tutorial001.py!} +``` + +//// В данном примере она преобразует Pydantic модель в `dict`, а `datetime` - в `str`. @@ -38,5 +42,8 @@ Функция не возвращает большой `str`, содержащий данные в формате JSON (в виде строки). Она возвращает стандартную структуру данных Python (например, `dict`) со значениями и подзначениями, которые совместимы с JSON. -!!! note "Технические детали" - `jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях. +/// note | Технические детали + +`jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях. + +/// diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index d4727e2d4..82cb0ff7a 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -55,28 +55,36 @@ Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов. -=== "Python 3.8 и выше" +//// tab | Python 3.8 и выше - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../docs_src/extra_data_types/tutorial001.py!} +``` -=== "Python 3.10 и выше" +//// - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// tab | Python 3.10 и выше + +```Python hl_lines="1 2 11-15" +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как: -=== "Python 3.8 и выше" +//// tab | Python 3.8 и выше + +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// tab | Python 3.10 и выше -=== "Python 3.10 и выше" +```Python hl_lines="17-18" +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index 78855313d..241f70779 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -8,26 +8,33 @@ * **Модель для вывода** не должна содержать пароль. * **Модель для базы данных**, возможно, должна содержать хэшированный пароль. -!!! danger "Внимание" - Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить. +/// danger | Внимание - Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить. + +Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. + +/// ## Множественные модели Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../docs_src/extra_models/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../docs_src/extra_models/tutorial001.py!} +``` + +//// ### Про `**user_in.dict()` @@ -139,8 +146,11 @@ UserInDB( ) ``` -!!! warning "Предупреждение" - Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность. +/// warning | Предупреждение + +Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность. + +/// ## Сократите дублирование @@ -158,17 +168,21 @@ UserInDB( В этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля): -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../docs_src/extra_models/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../docs_src/extra_models/tutorial002.py!} +``` - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// ## `Union` или `anyOf` @@ -178,20 +192,27 @@ UserInDB( Для этого используйте стандартные аннотации типов в Python `typing.Union`: -!!! note "Примечание" - При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. +/// note | Примечание + +При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. -=== "Python 3.10+" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +//// tab | Python 3.10+ -=== "Python 3.8+" +```Python hl_lines="1 14-15 18-20 33" +{!> ../../docs_src/extra_models/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../docs_src/extra_models/tutorial003.py!} +``` + +//// ### `Union` в Python 3.10 @@ -213,17 +234,21 @@ some_variable: PlaneItem | CarItem Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше): -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +```Python hl_lines="18" +{!> ../../docs_src/extra_models/tutorial004_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 20" +{!> ../../docs_src/extra_models/tutorial004.py!} +``` + +//// ## Ответ с произвольным `dict` @@ -233,17 +258,21 @@ some_variable: PlaneItem | CarItem В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6" +{!> ../../docs_src/extra_models/tutorial005_py39.py!} +``` + +//// - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 8" +{!> ../../docs_src/extra_models/tutorial005.py!} +``` - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index b46f235bc..309f26c4f 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Самый простой FastAPI файл может выглядеть так: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Скопируйте в файл `main.py`. @@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note "Технические детали" - Команда `uvicorn main:app` обращается к: +/// note | Технические детали - * `main`: файл `main.py` (модуль Python). - * `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`. - * `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки. +Команда `uvicorn main:app` обращается к: + +* `main`: файл `main.py` (модуль Python). +* `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`. +* `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки. + +/// В окне вывода появится следующая строка: @@ -131,20 +134,23 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 1: импортируйте `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` это класс в Python, который предоставляет всю функциональность для API. -!!! note "Технические детали" - `FastAPI` это класс, который наследуется непосредственно от `Starlette`. +/// note | Технические детали + +`FastAPI` это класс, который наследуется непосредственно от `Starlette`. - Вы можете использовать всю функциональность Starlette в `FastAPI`. +Вы можете использовать всю функциональность Starlette в `FastAPI`. + +/// ### Шаг 2: создайте экземпляр `FastAPI` ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Переменная `app` является экземпляром класса `FastAPI`. @@ -166,7 +172,7 @@ $ uvicorn main:app --reload Если создать такое приложение: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` И поместить его в `main.py`, тогда вызов `uvicorn` будет таким: @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Дополнительная иформация" - Термин "path" также часто называется "endpoint" или "route". +/// info | Дополнительная иформация + +Термин "path" также часто называется "endpoint" или "route". + +/// При создании API, "путь" является основным способом разделения "задач" и "ресурсов". @@ -242,7 +251,7 @@ https://example.com/items/foo #### Определите *декоратор операции пути (path operation decorator)* ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Декоратор `@app.get("/")` указывает **FastAPI**, что функция, прямо под ним, отвечает за обработку запросов, поступающих по адресу: @@ -250,16 +259,19 @@ https://example.com/items/foo * путь `/` * использующих get операцию -!!! info "`@decorator` Дополнительная информация" - Синтаксис `@something` в Python называется "декоратор". +/// info | `@decorator` Дополнительная информация - Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин). +Синтаксис `@something` в Python называется "декоратор". - "Декоратор" принимает функцию ниже и выполняет с ней какое-то действие. +Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин). - В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`. +"Декоратор" принимает функцию ниже и выполняет с ней какое-то действие. - Это и есть "**декоратор операции пути**". +В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`. + +Это и есть "**декоратор операции пути**". + +/// Можно также использовать операции: @@ -274,14 +286,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip "Подсказка" - Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению. +/// tip | Подсказка + +Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению. - **FastAPI** не навязывает определенного значения для каждого метода. +**FastAPI** не навязывает определенного значения для каждого метода. - Информация здесь представлена как рекомендация, а не требование. +Информация здесь представлена как рекомендация, а не требование. - Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций. +Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций. + +/// ### Шаг 4: определите **функцию операции пути** @@ -292,7 +307,7 @@ https://example.com/items/foo * **функция**: функция ниже "декоратора" (ниже `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Это обычная Python функция. @@ -306,16 +321,19 @@ https://example.com/items/foo Вы также можете определить ее как обычную функцию вместо `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Технические детали" - Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note | Технические детали + +Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}. + +/// ### Шаг 5: верните результат ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д. diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md index 40b6f9bc4..a06644376 100644 --- a/docs/ru/docs/tutorial/handling-errors.md +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -26,7 +26,7 @@ ### Импортируйте `HTTPException` ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### Вызовите `HTTPException` в своем коде @@ -42,7 +42,7 @@ В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### Возвращаемый ответ @@ -63,12 +63,15 @@ } ``` -!!! tip "Подсказка" - При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`. +/// tip | Подсказка - Вы можете передать `dict`, `list` и т.д. +При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`. - Они автоматически обрабатываются **FastAPI** и преобразуются в JSON. +Вы можете передать `dict`, `list` и т.д. + +Они автоматически обрабатываются **FastAPI** и преобразуются в JSON. + +/// ## Добавление пользовательских заголовков @@ -79,7 +82,7 @@ Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` ## Установка пользовательских обработчиков исключений @@ -93,7 +96,7 @@ Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`: ```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`. @@ -106,10 +109,13 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "Технические детали" - Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`. +/// note | Технические детали + +Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`. - **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`. +/// ## Переопределение стандартных обработчиков исключений @@ -130,7 +136,7 @@ Обработчик исключения получит объект `Request` и исключение. ```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с: @@ -160,8 +166,11 @@ path -> item_id #### `RequestValidationError` или `ValidationError` -!!! warning "Внимание" - Это технические детали, которые можно пропустить, если они не важны для вас сейчас. +/// warning | Внимание + +Это технические детали, которые можно пропустить, если они не важны для вас сейчас. + +/// `RequestValidationError` является подклассом Pydantic `ValidationError`. @@ -180,13 +189,16 @@ path -> item_id Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON: ```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "Технические детали" - Можно также использовать `from starlette.responses import PlainTextResponse`. +/// note | Технические детали + +Можно также использовать `from starlette.responses import PlainTextResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. - **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. +/// ### Используйте тело `RequestValidationError` @@ -195,7 +207,7 @@ path -> item_id Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д. ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} +{!../../docs_src/handling_errors/tutorial005.py!} ``` Теперь попробуйте отправить недействительный элемент, например: @@ -255,7 +267,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений. diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md index 1be4ac707..904709b04 100644 --- a/docs/ru/docs/tutorial/header-params.md +++ b/docs/ru/docs/tutorial/header-params.md @@ -6,41 +6,57 @@ Сперва импортируйте `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../docs_src/header_params/tutorial001_an.py!} +``` -=== "Python 3.10+ без Annotated" +//// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="1" +{!> ../../docs_src/header_params/tutorial001_py310.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="3" +{!> ../../docs_src/header_params/tutorial001.py!} +``` + +//// ## Объявление параметров `Header` @@ -48,49 +64,71 @@ Первое значение является значением по умолчанию, вы можете передать все дополнительные параметры валидации или аннотации: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="10" +{!> ../../docs_src/header_params/tutorial001_an.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | Подсказка - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -!!! note "Технические детали" - `Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. +/// - Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. +```Python hl_lines="7" +{!> ../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial001.py!} +``` -!!! info "Дополнительная информация" - Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. +//// + +/// note | Технические детали + +`Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. + +Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. + +/// + +/// info | Дополнительная информация + +Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. + +/// ## Автоматическое преобразование @@ -108,44 +146,63 @@ Если по какой-либо причине вам необходимо отключить автоматическое преобразование подчеркиваний в дефисы, установите для параметра `convert_underscores` в `Header` значение `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/header_params/tutorial002_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11" +{!> ../../docs_src/header_params/tutorial002_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../docs_src/header_params/tutorial002_an.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="8" +{!> ../../docs_src/header_params/tutorial002_py310.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | Подсказка - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -!!! warning "Внимание" - Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. +/// + +```Python hl_lines="10" +{!> ../../docs_src/header_params/tutorial002.py!} +``` + +//// + +/// warning | Внимание + +Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. + +/// ## Повторяющиеся заголовки @@ -157,50 +214,71 @@ Например, чтобы объявить заголовок `X-Token`, который может появляться более одного раза, вы можете написать: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="10" +{!> ../../docs_src/header_params/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/header_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.9+ без Annotated" +//// tab | Python 3.9+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | Подсказка - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// Если вы взаимодействуете с этой *операцией пути*, отправляя два HTTP-заголовка, таких как: diff --git a/docs/ru/docs/tutorial/index.md b/docs/ru/docs/tutorial/index.md index ea3a1c37a..ddca2fbb1 100644 --- a/docs/ru/docs/tutorial/index.md +++ b/docs/ru/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...это также включает `uvicorn`, который вы можете использовать в качестве сервера, который запускает ваш код. -!!! note "Технические детали" - Вы также можете установить его по частям. +/// note | Технические детали - Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде: +Вы также можете установить его по частям. - ``` - pip install fastapi - ``` +Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде: - Также установите `uvicorn` для работы в качестве сервера: +``` +pip install fastapi +``` + +Также установите `uvicorn` для работы в качестве сервера: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать. - И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать. +/// ## Продвинутое руководство пользователя diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index 468e08917..ae739a043 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -18,11 +18,14 @@ Вы можете задать их следующим образом: ```Python hl_lines="3-16 19-31" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` -!!! tip "Подсказка" - Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе. +/// tip | Подсказка + +Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе. + +/// С этой конфигурацией автоматическая документация API будут выглядеть так: @@ -49,23 +52,29 @@ Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`: ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_). -!!! tip "Подсказка" - Вам необязательно добавлять метаданные для всех используемых тегов +/// tip | Подсказка + +Вам необязательно добавлять метаданные для всех используемых тегов + +/// ### Используйте собственные теги Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` -!!! info "Дополнительная информация" - Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#tags){.internal-link target=_blank}. +/// info | Дополнительная информация + +Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}. + +/// ### Проверьте документацию @@ -88,7 +97,7 @@ К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые его использует. @@ -107,5 +116,5 @@ К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index db99409f4..ac12b7084 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ Существует несколько параметров, которые вы можете передать вашему *декоратору операций пути* для его настройки. -!!! warning "Внимание" - Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*. +/// warning | Внимание + +Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*. + +/// ## Коды состояния @@ -13,52 +16,67 @@ Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в параметре `status`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1 15" +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="3 17" +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} +``` + +//// - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3 17" +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} +``` - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +//// Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI. -!!! note "Технические детали" - Вы также можете использовать `from starlette import status`. +/// note | Технические детали + +Вы также можете использовать `from starlette import status`. + +**FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette. - **FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette. +/// ## Теги Вы можете добавлять теги к вашим *операциям пути*, добавив параметр `tags` с `list` заполненным `str`-значениями (обычно в нём только одна строка): -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +```Python hl_lines="15 20 25" +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` +```Python hl_lines="17 22 27" +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 27" +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} +``` + +//// Они будут добавлены в схему OpenAPI и будут использованы в автоматической документации интерфейса: @@ -73,30 +91,36 @@ **FastAPI** поддерживает это так же, как и в случае с обычными строками: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## Краткое и развёрнутое содержание Вы можете добавить параметры `summary` и `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="20-21" +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} +``` + +//// - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20-21" +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} +``` - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +//// ## Описание из строк документации @@ -104,23 +128,29 @@ Вы можете использовать Markdown в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации). -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17-25" +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="19-27" +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} +``` - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +```Python hl_lines="19-27" +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} +``` + +//// Он будет использован в интерактивной документации: @@ -130,31 +160,43 @@ Вы можете указать описание ответа с помощью параметра `response_description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="21" +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +//// -=== "Python 3.9+" +/// info | Дополнительная информация - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом. -=== "Python 3.8+" +/// - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +/// check | Технические детали -!!! info "Дополнительная информация" - Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом. +OpenAPI указывает, что каждой *операции пути* необходимо описание ответа. -!!! check "Технические детали" - OpenAPI указывает, что каждой *операции пути* необходимо описание ответа. +Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response". - Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response". +/// @@ -163,7 +205,7 @@ Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` Он будет четко помечен как устаревший в интерактивной документации: diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index bd2c29d0a..ed19576a2 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -6,48 +6,67 @@ Сначала импортируйте `Path` из `fastapi`, а также импортируйте `Annotated`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="1 3" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3-4" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +/// tip | Подсказка -=== "Python 3.8+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ без Annotated" +```Python hl_lines="1" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// info | Информация - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход). -!!! info "Информация" - Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход). +Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`. - Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`. +Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`. - Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`. +/// ## Определите метаданные @@ -55,53 +74,75 @@ Например, чтобы указать значение метаданных `title` для path-параметра `item_id`, вы можете написать: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="11" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -!!! note "Примечание" - Path-параметр всегда является обязательным, поскольку он составляет часть пути. +/// - Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный. +```Python hl_lines="8" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным. +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note | Примечание + +Path-параметр всегда является обязательным, поскольку он составляет часть пути. + +Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный. + +Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным. + +/// ## Задайте нужный вам порядок параметров -!!! tip "Подсказка" - Это не имеет большого значения, если вы используете `Annotated`. +/// tip | Подсказка + +Это не имеет большого значения, если вы используете `Annotated`. + +/// Допустим, вы хотите объявить query-параметр `q` как обязательный параметр типа `str`. @@ -117,33 +158,45 @@ Поэтому вы можете определить функцию так: -=== "Python 3.8 без Annotated" +//// tab | Python 3.8 без Annotated + +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `Path()` в качестве значения по умолчанию для параметра функции. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +``` + +//// ## Задайте нужный вам порядок параметров, полезные приёмы -!!! tip "Подсказка" - Это не имеет большого значения, если вы используете `Annotated`. +/// tip | Подсказка + +Это не имеет большого значения, если вы используете `Annotated`. + +/// Здесь описан **небольшой приём**, который может оказаться удобным, хотя часто он вам не понадобится. @@ -161,24 +214,28 @@ Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ### Лучше с `Annotated` Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} - ``` +//// ## Валидация числовых данных: больше или равно @@ -186,26 +243,35 @@ Python не будет ничего делать с `*`, но он будет з В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual"). -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +/// + +```Python hl_lines="8" +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +//// ## Валидация числовых данных: больше и меньше или равно @@ -214,26 +280,35 @@ Python не будет ничего делать с `*`, но он будет з * `gt`: больше (`g`reater `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} - ``` +/// tip | Подсказка -=== "Python 3.8+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +//// ## Валидация числовых данных: числа с плавающей точкой, больше и меньше @@ -245,26 +320,35 @@ Python не будет ничего делать с `*`, но он будет з То же самое справедливо и для lt. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="13" +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="12" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} - ``` +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="11" +{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +//// ## Резюме @@ -277,16 +361,22 @@ Python не будет ничего делать с `*`, но он будет з * `lt`: меньше (`l`ess `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -!!! info "Информация" - `Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`. +/// info | Информация + +`Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`. + +Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее. + +/// + +/// note | Технические детали - Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее. +`Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов. -!!! note "Технические детали" - `Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов. +Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`. - Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`. +Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами. - Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами. +Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок. - Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок. +/// diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index 1241e0919..ba23ba5ea 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`. @@ -19,13 +19,16 @@ Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python. ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` Здесь, `item_id` объявлен типом `int`. -!!! check "Заметка" - Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.). +/// check | Заметка + +Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.). + +/// ## Преобразование данных @@ -35,10 +38,13 @@ {"item_id":3} ``` -!!! check "Заметка" - Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`. +/// check | Заметка + +Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`. + +Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов. - Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов. +/// ## Проверка данных @@ -63,12 +69,15 @@ Та же ошибка возникнет, если вместо `int` передать `float` , например: http://127.0.0.1:8000/items/4.2 -!!! check "Заметка" - **FastAPI** обеспечивает проверку типов, используя всё те же определения типов. +/// check | Заметка - Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку. +**FastAPI** обеспечивает проверку типов, используя всё те же определения типов. - Это очень полезно при разработке и отладке кода, который взаимодействует с API. +Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку. + +Это очень полезно при разработке и отладке кода, который взаимодействует с API. + +/// ## Документация @@ -76,10 +85,13 @@ -!!! check "Заметка" - Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI). +/// check | Заметка + +Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI). + +Обратите внимание, что параметр пути объявлен целочисленным. - Обратите внимание, что параметр пути объявлен целочисленным. +/// ## Преимущества стандартизации, альтернативная документация @@ -111,7 +123,7 @@ ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`. @@ -119,7 +131,7 @@ Аналогично, вы не можете переопределить операцию с путем: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003b.py!} +{!../../docs_src/path_params/tutorial003b.py!} ``` Первый будет выполняться всегда, так как путь совпадает первым. @@ -137,21 +149,27 @@ Затем создайте атрибуты класса с фиксированными допустимыми значениями: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! info "Дополнительная информация" - Перечисления (enum) доступны в Python начиная с версии 3.4. +/// info | Дополнительная информация -!!! tip "Подсказка" - Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения. +Перечисления (enum) доступны в Python начиная с версии 3.4. + +/// + +/// tip | Подсказка + +Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения. + +/// ### Определение *параметра пути* Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### Проверьте документацию @@ -169,7 +187,7 @@ Вы можете сравнить это значение с *элементом перечисления* класса `ModelName`: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### Получение *значения перечисления* @@ -177,11 +195,14 @@ Можно получить фактическое значение (в данном случае - `str`) с помощью `model_name.value` или в общем случае `your_enum_member.value`: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "Подсказка" - Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`. +/// tip | Подсказка + +Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`. + +/// #### Возврат *элементов перечисления* @@ -190,7 +211,7 @@ Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` Вы отправите клиенту такой JSON-ответ: @@ -230,13 +251,16 @@ OpenAPI не поддерживает способов объявления *п Можете использовать так: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "Подсказка" - Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`). +/// tip | Подсказка + +Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`). + +В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`. - В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`. +/// ## Резюме Используя **FastAPI** вместе со стандартными объявлениями типов Python (короткими и интуитивно понятными), вы получаете: diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index 108aefefc..f76570ce8 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,31 @@ Давайте рассмотрим следующий пример: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +//// Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный. -!!! note "Технические детали" - FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`. +/// note | Технические детали - `Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки. +FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`. + +`Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки. + +/// ## Расширенная валидация @@ -34,23 +41,27 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N * `Query` из пакета `fastapi`: * `Annotated` из пакета `typing` (или из `typing_extensions` для Python ниже 3.9) -=== "Python 3.10+" +//// tab | Python 3.10+ + +В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`. + +```Python hl_lines="1 3" +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` - В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`. +//// - ```Python hl_lines="1 3" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`. - В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`. +Эта библиотека будет установлена вместе с FastAPI. - Эта библиотека будет установлена вместе с FastAPI. +```Python hl_lines="3-4" +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - ```Python hl_lines="3-4" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// ## `Annotated` как тип для query-параметра `q` @@ -60,31 +71,39 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N У нас была аннотация следующего типа: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - q: str | None = None - ``` +```Python +q: str | None = None +``` -=== "Python 3.8+" +//// - ```Python - q: Union[str, None] = None - ``` +//// tab | Python 3.8+ + +```Python +q: Union[str, None] = None +``` + +//// Вот что мы получим, если обернём это в `Annotated`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +q: Annotated[str | None] = None +``` + +//// - ```Python - q: Annotated[str | None] = None - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python +q: Annotated[Union[str, None]] = None +``` - ```Python - q: Annotated[Union[str, None]] = None - ``` +//// Обе эти версии означают одно и тоже. `q` - это параметр, который может быть `str` или `None`, и по умолчанию он будет принимать `None`. @@ -94,17 +113,21 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N Теперь, когда у нас есть `Annotated`, где мы можем добавить больше метаданных, добавим `Query` со значением параметра `max_length` равным 50: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным. @@ -120,22 +143,29 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N В предыдущих версиях FastAPI (ниже 0.95.0) необходимо было использовать `Query` как значение по умолчанию для query-параметра. Так было вместо размещения его в `Annotated`, так что велика вероятность, что вам встретится такой код. Сейчас объясню. -!!! tip "Подсказка" - При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰 +/// tip | Подсказка + +При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰 + +/// Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} +``` + +//// В таком случае (без использования `Annotated`), мы заменили значение по умолчанию с `None` на `Query()` в функции. Теперь нам нужно установить значение по умолчанию для query-параметра `Query(default=None)`, что необходимо для тех же целей, как когда ранее просто указывалось значение по умолчанию (по крайней мере, для FastAPI). @@ -165,22 +195,25 @@ q: str | None = None Но он явно объявляет его как query-параметр. -!!! info "Дополнительная информация" - Запомните, важной частью объявления параметра как необязательного является: +/// info | Дополнительная информация + +Запомните, важной частью объявления параметра как необязательного является: - ```Python - = None - ``` +```Python += None +``` - или: +или: - ```Python - = Query(default=None) - ``` +```Python += Query(default=None) +``` - так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**. +так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**. - `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра. +`Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра. + +/// Теперь, мы можем указать больше параметров для `Query`. В данном случае, параметр `max_length` применяется к строкам: @@ -232,81 +265,113 @@ q: str = Query(default="rick") Вы также можете добавить параметр `min_length`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} - ``` +/// tip | Подсказка -=== "Python 3.9+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial003.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +//// ## Регулярные выражения Вы можете определить регулярное выражение, которому должен соответствовать параметр: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11" +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +``` + +//// - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+" +```Python hl_lines="12" +{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | Подсказка - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+" +/// - ```Python hl_lines="12" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} +``` + +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="11" +{!> ../../docs_src/query_params_str_validations/tutorial004.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +//// Данное регулярное выражение проверяет, что полученное значение параметра: @@ -324,29 +389,41 @@ q: str = Query(default="rick") Например, вы хотите для параметра запроса `q` указать, что он должен состоять минимум из 3 символов (`min_length=3`) и иметь значение по умолчанию `"fixedquery"`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+" +/// tip | Подсказка - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// + +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial005.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial005.py!} - ``` +/// note | Технические детали -!!! note "Технические детали" - Наличие значения по умолчанию делает параметр необязательным. +Наличие значения по умолчанию делает параметр необязательным. + +/// ## Обязательный параметр @@ -364,75 +441,103 @@ q: Union[str, None] = None Но у нас query-параметр определён как `Query`. Например: -=== "Annotated" +//// tab | Annotated + +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` + +//// - ```Python - q: Annotated[Union[str, None], Query(min_length=3)] = None - ``` +//// tab | без Annotated -=== "без Annotated" +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` - ```Python - q: Union[str, None] = Query(default=None, min_length=3) - ``` +//// В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ без Annotated" +```Python hl_lines="8" +{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial006.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006.py!} - ``` +/// tip | Подсказка - !!! tip "Подсказка" - Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. +Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. - Лучше будет использовать версию с `Annotated`. 😉 +Лучше будет использовать версию с `Annotated`. 😉 + +/// + +//// ### Обязательный параметр с Ellipsis (`...`) Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} - ``` +/// -!!! info "Дополнительная информация" - Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis". +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} +``` - Используется в Pydantic и FastAPI для определения, что значение требуется обязательно. +//// + +/// info | Дополнительная информация + +Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis". + +Используется в Pydantic и FastAPI для определения, что значение требуется обязательно. + +/// Таким образом, **FastAPI** определяет, что параметр является обязательным. @@ -442,72 +547,103 @@ q: Union[str, None] = None Чтобы этого добиться, вам нужно определить `None` как валидный тип для параметра запроса, но также указать `default=...`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+" +/// tip | Подсказка - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -!!! tip "Подсказка" - Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля. +/// + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} +``` + +//// + +/// tip | Подсказка + +Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля. + +/// ### Использование Pydantic's `Required` вместо Ellipsis (`...`) Если вас смущает `...`, вы можете использовать `Required` из Pydantic: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="4 10" +{!> ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 9" +{!> ../../docs_src/query_params_str_validations/tutorial006d_an.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="4 10" - {!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} - ``` +/// tip | Подсказка -=== "Python 3.8+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="2 9" - {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!} - ``` +/// + +```Python hl_lines="2 8" +{!> ../../docs_src/query_params_str_validations/tutorial006d.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="2 8" - {!> ../../../docs_src/query_params_str_validations/tutorial006d.py!} - ``` +Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. -!!! tip "Подсказка" - Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. +/// ## Множество значений для query-параметра @@ -515,50 +651,71 @@ q: Union[str, None] = None Например, query-параметр `q` может быть указан в URL несколько раз. И если вы ожидаете такой формат запроса, то можете указать это следующим образом: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.10+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +/// -=== "Python 3.9+ без Annotated" +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` +//// tab | Python 3.9+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +/// + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial011.py!} +``` + +//// Затем, получив такой URL: @@ -579,8 +736,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "Подсказка" - Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса. +/// tip | Подсказка + +Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса. + +/// Интерактивная документация API будет обновлена соответствующим образом, где будет разрешено множество значений: @@ -590,35 +750,49 @@ http://localhost:8000/items/?q=foo&q=bar Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.9+ без Annotated" +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +//// tab | Python 3.9+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial012.py!} +``` + +//// Если вы перейдёте по ссылке: @@ -641,31 +815,43 @@ http://localhost:8000/items/ Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} - ``` +/// tip | Подсказка -=== "Python 3.8+" +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial013.py!} +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// note | Технические детали - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial013.py!} - ``` +Запомните, что в таком случае, FastAPI не будет проверять содержимое списка. -!!! note "Технические детали" - Запомните, что в таком случае, FastAPI не будет проверять содержимое списка. +Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет. - Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет. +/// ## Больше метаданных @@ -673,86 +859,121 @@ http://localhost:8000/items/ Указанная информация будет включена в генерируемую OpenAPI документацию и использована в пользовательском интерфейсе и внешних инструментах. -!!! note "Технические детали" - Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI. +/// note | Технические детали - Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке. +Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI. + +Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке. + +/// Вы можете указать название query-параметра, используя параметр `title`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.9+" +/// tip | Подсказка - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+" +/// + +```Python hl_lines="8" +{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial007.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +//// Добавить описание, используя параметр `description`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="14" +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="15" +{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} +``` + +//// - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+" +/// tip | Подсказка - ```Python hl_lines="15" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// + +```Python hl_lines="11" +{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +/// + +```Python hl_lines="13" +{!> ../../docs_src/query_params_str_validations/tutorial008.py!} +``` + +//// ## Псевдонимы параметров @@ -772,41 +993,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ без Annotated" +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial009.py!} +``` + +//// ## Устаревшие параметры @@ -816,41 +1053,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда для `Query` укажите параметр `deprecated=True`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} +``` + +//// + +//// tab | Python 3.10+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="16" +{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} +``` - ```Python hl_lines="20" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="18" +{!> ../../docs_src/query_params_str_validations/tutorial010.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +//// В документации это будет отображено следующим образом: @@ -860,41 +1113,57 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11" +{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} +``` - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python hl_lines="8" +{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка + +Рекомендуется использовать версию с `Annotated` если возможно. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/query_params_str_validations/tutorial014.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index 6e885cb65..2c697224c 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`. @@ -63,38 +63,49 @@ http://127.0.0.1:8000/items/?skip=20 Аналогично, вы можете объявлять необязательные query-параметры, установив их значение по умолчанию, равное `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию. -!!! Важно - Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. +/// check | Важно + +Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. + +/// ## Преобразование типа параметра запроса Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// В этом случае, если вы сделаете запрос: @@ -137,17 +148,21 @@ http://127.0.0.1:8000/items/foo?short=yes Они будут обнаружены по именам: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 8" +{!> ../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8 10" +{!> ../../docs_src/query_params/tutorial004.py!} +``` - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// ## Обязательные query-параметры @@ -158,7 +173,7 @@ http://127.0.0.1:8000/items/foo?short=yes Но если вы хотите сделать query-параметр обязательным, вы можете просто не указывать значение по умолчанию: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`. @@ -203,17 +218,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Конечно, вы можете определить некоторые параметры как обязательные, некоторые - со значением по умполчанию, а некоторые - полностью необязательные: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/query_params/tutorial006.py!} +``` + +//// В этом примере, у нас есть 3 параметра запроса: @@ -221,5 +240,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, типа `int` и со значением по умолчанию `0`. * `limit`, необязательный `int`. -!!! подсказка - Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#predefined-values){.internal-link target=_blank}. +/// tip | Подсказка + +Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}. + +/// diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 79b3bd067..836d6efed 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -2,70 +2,97 @@ Используя класс `File`, мы можем позволить клиентам загружать файлы. -!!! info "Дополнительная информация" - Чтобы получать загруженные файлы, сначала установите `python-multipart`. +/// info | Дополнительная информация - Например: `pip install python-multipart`. +Чтобы получать загруженные файлы, сначала установите `python-multipart`. - Это связано с тем, что загружаемые файлы передаются как данные формы. +Например: `pip install python-multipart`. + +Это связано с тем, что загружаемые файлы передаются как данные формы. + +/// ## Импорт `File` Импортируйте `File` и `UploadFile` из модуля `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="1" +{!> ../../docs_src/request_files/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// tip | Подсказка - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="1" +{!> ../../docs_src/request_files/tutorial001.py!} +``` + +//// ## Определите параметры `File` Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="8" +{!> ../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/request_files/tutorial001.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +/// info | Дополнительная информация -=== "Python 3.6+ без Annotated" +`File` - это класс, который наследуется непосредственно от `Form`. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. - ```Python hl_lines="7" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// -!!! info "Дополнительная информация" - `File` - это класс, который наследуется непосредственно от `Form`. +/// tip | Подсказка - Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. +Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). -!!! tip "Подсказка" - Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). +/// Файлы будут загружены как данные формы. @@ -79,26 +106,35 @@ Определите параметр файла с типом `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="14" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="14" +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="13" +{!> ../../docs_src/request_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="13" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="12" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// + +```Python hl_lines="12" +{!> ../../docs_src/request_files/tutorial001.py!} +``` + +//// Использование `UploadFile` имеет ряд преимуществ перед `bytes`: @@ -141,11 +177,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "Технические детали `async`" - При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. +/// note | Технические детали `async` + +При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. + +/// + +/// note | Технические детали Starlette -!!! note "Технические детали Starlette" - **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. +**FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. + +/// ## Про данные формы ("Form Data") @@ -153,82 +195,113 @@ contents = myfile.file.read() **FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON. -!!! note "Технические детали" - Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. +/// note | Технические детали + +Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. + +Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела. + +Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST. + +/// - Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела. +/// warning | Внимание - Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST. +В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. -!!! warning "Внимание" - В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. +Это не является ограничением **FastAPI**, это часть протокола HTTP. - Это не является ограничением **FastAPI**, это часть протокола HTTP. +/// ## Необязательная загрузка файлов Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} - ``` +```Python hl_lines="10 18" +{!> ../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.10+ без Annotated - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} - ``` +/// tip | Подсказка -=== "Python 3.6+" +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="10 18" - {!> ../../../docs_src/request_files/tutorial001_02_an.py!} - ``` +/// -=== "Python 3.10+ без Annotated" +```Python hl_lines="7 15" +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="7 15" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +/// + +```Python hl_lines="9 17" +{!> ../../docs_src/request_files/tutorial001_02.py!} +``` + +//// ## `UploadFile` с дополнительными метаданными Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="8 14" +{!> ../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// - ```Python hl_lines="9 15" - {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+" +/// tip | Подсказка - ```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!} +``` - ```Python hl_lines="7 13" - {!> ../../../docs_src/request_files/tutorial001_03.py!} - ``` +//// ## Загрузка нескольких файлов @@ -238,76 +311,107 @@ contents = myfile.file.read() Для этого необходимо объявить список `bytes` или `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} - ``` +```Python hl_lines="10 15" +{!> ../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python hl_lines="11 16" - {!> ../../../docs_src/request_files/tutorial002_an.py!} - ``` +```Python hl_lines="11 16" +{!> ../../docs_src/request_files/tutorial002_an.py!} +``` -=== "Python 3.9+ без Annotated" +//// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// tab | Python 3.9+ без Annotated - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +/// tip | Подсказка -=== "Python 3.6+ без Annotated" +Предпочтительнее использовать версию с аннотацией, если это возможно. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// + +```Python hl_lines="8 13" +{!> ../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="10 15" +{!> ../../docs_src/request_files/tutorial002.py!} +``` + +//// Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. -!!! note "Technical Details" - Можно также использовать `from starlette.responses import HTMLResponse`. +/// note | Technical Details + +Можно также использовать `from starlette.responses import HTMLResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. - **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. +/// ### Загрузка нескольких файлов с дополнительными метаданными Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="11 18-20" - {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} - ``` +```Python hl_lines="11 18-20" +{!> ../../docs_src/request_files/tutorial003_an_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="12 19-21" - {!> ../../../docs_src/request_files/tutorial003_an.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.9+ без Annotated" +```Python hl_lines="12 19-21" +{!> ../../docs_src/request_files/tutorial003_an.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="9 16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// tab | Python 3.9+ без Annotated -=== "Python 3.6+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="9 16" +{!> ../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="11 18" +{!> ../../docs_src/request_files/tutorial003.py!} +``` - ```Python hl_lines="11 18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index a08232ca7..fd98ec953 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -2,67 +2,91 @@ Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`. -!!! info "Дополнительная информация" - Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`. +/// info | Дополнительная информация - Например: `pip install python-multipart`. +Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`. + +Например: `pip install python-multipart`. + +/// ## Импортируйте `File` и `Form` -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.6+ + +```Python hl_lines="1" +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+" +/// tip | Подсказка - ```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!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// ## Определите параметры `File` и `Form` Создайте параметры файла и формы таким же образом, как для `Body` или `Query`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10-12" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` +```Python hl_lines="10-12" +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +``` -=== "Python 3.6+" +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+ без Annotated" +```Python hl_lines="9-11" +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} +``` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="8" +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} +``` + +//// Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы. Вы можете объявить некоторые файлы как `bytes`, а некоторые - как `UploadFile`. -!!! warning "Внимание" - Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. +/// warning | Внимание + +Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. + +Это не ограничение **Fast API**, это часть протокола HTTP. - Это не ограничение **Fast API**, это часть протокола HTTP. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index fa2bcb7cb..cd17613de 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -2,60 +2,81 @@ Когда вам нужно получить поля формы вместо JSON, вы можете использовать `Form`. -!!! info "Дополнительная информация" - Чтобы использовать формы, сначала установите `python-multipart`. +/// info | Дополнительная информация - Например, выполните команду `pip install python-multipart`. +Чтобы использовать формы, сначала установите `python-multipart`. + +Например, выполните команду `pip install python-multipart`. + +/// ## Импорт `Form` Импортируйте `Form` из `fastapi`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +Рекомендуется использовать 'Annotated' версию, если это возможно. - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="1" +{!> ../../docs_src/request_forms/tutorial001.py!} +``` + +//// ## Определение параметров `Form` Создайте параметры формы так же, как это делается для `Body` или `Query`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="9" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +```Python hl_lines="8" +{!> ../../docs_src/request_forms/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +Рекомендуется использовать 'Annotated' версию, если это возможно. - ```Python hl_lines="7" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// + +```Python hl_lines="7" +{!> ../../docs_src/request_forms/tutorial001.py!} +``` + +//// Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы. @@ -63,11 +84,17 @@ Вы можете настроить `Form` точно так же, как настраиваете и `Body` ( `Query`, `Path`, `Cookie`), включая валидации, примеры, псевдонимы (например, `user-name` вместо `username`) и т.д. -!!! info "Дополнительная информация" - `Form` - это класс, который наследуется непосредственно от `Body`. +/// info | Дополнительная информация + +`Form` - это класс, который наследуется непосредственно от `Body`. + +/// + +/// tip | Подсказка -!!! tip "Подсказка" - Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). +Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). + +/// ## О "полях формы" @@ -75,17 +102,23 @@ **FastAPI** гарантирует правильное чтение этих данных из соответствующего места, а не из JSON. -!!! note "Технические детали" - Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. +/// note | Технические детали + +Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. + +Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе. + +Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте. + +/// - Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе. +/// warning | Предупреждение - Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте. +Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. -!!! warning "Предупреждение" - Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. +Это не ограничение **FastAPI**, это часть протокола HTTP. - Это не ограничение **FastAPI**, это часть протокола HTTP. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index 9b9b60dd5..c55be38ef 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -4,23 +4,29 @@ FastAPI позволяет использовать **аннотации типов** таким же способом, как и для ввода данных в **параметры** функции, вы можете использовать модели Pydantic, списки, словари, скалярные типы (такие, как int, bool и т.д.). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +```Python hl_lines="16 21" +{!> ../../docs_src/response_model/tutorial001_01_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="18 23" +{!> ../../docs_src/response_model/tutorial001_01_py39.py!} +``` + +//// - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="18 23" +{!> ../../docs_src/response_model/tutorial001_01.py!} +``` - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +//// FastAPI будет использовать этот возвращаемый тип для: @@ -53,35 +59,47 @@ FastAPI будет использовать этот возвращаемый т * `@app.delete()` * и др. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../docs_src/response_model/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 24-27" +{!> ../../docs_src/response_model/tutorial001.py!} +``` -!!! note "Технические детали" - Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. +//// + +/// note | Технические детали + +Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. + +/// `response_model` принимает те же типы, которые можно указать для какого-либо поля в модели Pydantic. Таким образом, это может быть как одиночная модель Pydantic, так и `список (list)` моделей Pydantic. Например, `List[Item]`. FastAPI будет использовать значение `response_model` для того, чтобы автоматически генерировать документацию, производить валидацию и т.п. А также для **конвертации и фильтрации выходных данных** в объявленный тип. -!!! tip "Подсказка" - Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. +/// tip | Подсказка + +Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. + +Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`. - Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`. +/// ### Приоритет `response_model` @@ -95,36 +113,47 @@ FastAPI будет использовать значение `response_model` д Здесь мы объявили модель `UserIn`, которая хранит пользовательский пароль в открытом виде: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +```Python hl_lines="7 9" +{!> ../../docs_src/response_model/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 11" +{!> ../../docs_src/response_model/tutorial002.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +/// info | Информация -!!! info "Информация" - Чтобы использовать `EmailStr`, прежде необходимо установить `email_validator`. - Используйте `pip install email-validator` - или `pip install pydantic[email]`. +Чтобы использовать `EmailStr`, прежде необходимо установить `email-validator`. +Используйте `pip install email-validator` +или `pip install pydantic[email]`. + +/// Далее мы используем нашу модель в аннотациях типа как для аргумента функции, так и для выходного значения: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../docs_src/response_model/tutorial002_py310.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../docs_src/response_model/tutorial002.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +//// Теперь всякий раз, когда клиент создает пользователя с паролем, API будет возвращать его пароль в ответе. @@ -132,52 +161,67 @@ FastAPI будет использовать значение `response_model` д Но что если мы захотим использовать эту модель для какой-либо другой *операции пути*? Мы можем, сами того не желая, отправить пароль любому другому пользователю. -!!! danger "Осторожно" - Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. +/// danger | Осторожно + +Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. + +/// ## Создание модели для ответа Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9 11 16" +{!> ../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 11 16" +{!> ../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// В таком случае, даже несмотря на то, что наша *функция операции пути* возвращает тот же самый объект пользователя с паролем, полученным на вход: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="24" +{!> ../../docs_src/response_model/tutorial003_py310.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// ...мы указали в `response_model` модель `UserOut`, в которой отсутствует поле, содержащее пароль - и он будет исключен из ответа: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +```Python hl_lines="22" +{!> ../../docs_src/response_model/tutorial003.py!} +``` + +//// Таким образом **FastAPI** позаботится о фильтрации ответа и исключит из него всё, что не указано в выходной модели (при помощи Pydantic). @@ -201,17 +245,21 @@ FastAPI будет использовать значение `response_model` д И в таких случаях мы можем использовать классы и наследование, чтобы пользоваться преимуществами **аннотаций типов** и получать более полную статическую проверку типов. Но при этом все так же получать **фильтрацию ответа** от FastAPI. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-10 13-14 18" +{!> ../../docs_src/response_model/tutorial003_01_py310.py!} +``` + +//// - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-13 15-16 20" +{!> ../../docs_src/response_model/tutorial003_01.py!} +``` - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +//// Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI. @@ -254,7 +302,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Самый частый сценарий использования - это [возвращать Response напрямую, как описано в расширенной документации](../advanced/response-directly.md){.internal-link target=_blank}. ```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} +{!> ../../docs_src/response_model/tutorial003_02.py!} ``` Это поддерживается FastAPI по-умолчанию, т.к. аннотация проставлена в классе (или подклассе) `Response`. @@ -266,7 +314,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Вы также можете указать подкласс `Response` в аннотации типа: ```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} +{!> ../../docs_src/response_model/tutorial003_03.py!} ``` Это сработает, потому что `RedirectResponse` является подклассом `Response` и FastAPI автоматически обработает этот простейший случай. @@ -277,17 +325,21 @@ FastAPI совместно с Pydantic выполнит некоторую ма То же самое произошло бы, если бы у вас было что-то вроде Union различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../docs_src/response_model/tutorial003_04_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/response_model/tutorial003_04.py!} +``` + +//// ...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`. @@ -299,17 +351,21 @@ FastAPI совместно с Pydantic выполнит некоторую ма В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../docs_src/response_model/tutorial003_05_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/response_model/tutorial003_05.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +//// Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓 @@ -317,23 +373,29 @@ FastAPI совместно с Pydantic выполнит некоторую ма Модель ответа может иметь значения по умолчанию, например: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="9 11-12" +{!> ../../docs_src/response_model/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11 13-14" +{!> ../../docs_src/response_model/tutorial004_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="11 13-14" +{!> ../../docs_src/response_model/tutorial004.py!} +``` - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// * `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию. * `tax: float = 10.5`, где `10.5` является значением по умолчанию. @@ -347,23 +409,29 @@ FastAPI совместно с Pydantic выполнит некоторую ма Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../docs_src/response_model/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="24" +{!> ../../docs_src/response_model/tutorial004_py39.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../docs_src/response_model/tutorial004.py!} +``` + +//// и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены. @@ -376,16 +444,22 @@ FastAPI совместно с Pydantic выполнит некоторую ма } ``` -!!! info "Информация" - "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта. +/// info | Информация + +"Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта. + +/// + +/// info | Информация -!!! info "Информация" - Вы также можете использовать: +Вы также можете использовать: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`. +как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`. + +/// #### Если значение поля отличается от значения по-умолчанию @@ -420,10 +494,13 @@ FastAPI достаточно умен (на самом деле, это засл И поэтому, они также будут включены в JSON ответа. -!!! tip "Подсказка" - Значением по умолчанию может быть что угодно, не только `None`. +/// tip | Подсказка + +Значением по умолчанию может быть что угодно, не только `None`. + +Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п. - Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п. +/// ### `response_model_include` и `response_model_exclude` @@ -433,45 +510,59 @@ FastAPI достаточно умен (на самом деле, это засл Это можно использовать как быстрый способ исключить данные из ответа, не создавая отдельную модель Pydantic. -!!! tip "Подсказка" - Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. +/// tip | Подсказка + +Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. + +Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты. - Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты. +То же самое применимо к параметру `response_model_by_alias`. - То же самое применимо к параметру `response_model_by_alias`. +/// -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +```Python hl_lines="29 35" +{!> ../../docs_src/response_model/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../docs_src/response_model/tutorial005.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +/// tip | Подсказка -!!! tip "Подсказка" - При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. +При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. - Того же самого можно достичь используя `set(["name", "description"])`. +Того же самого можно достичь используя `set(["name", "description"])`. + +/// #### Что если использовать `list` вместо `set`? Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="29 35" +{!> ../../docs_src/response_model/tutorial006_py310.py!} +``` - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="31 37" +{!> ../../docs_src/response_model/tutorial006.py!} +``` - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +//// ## Резюме diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md index b2f9b7704..f08b15379 100644 --- a/docs/ru/docs/tutorial/response-status-code.md +++ b/docs/ru/docs/tutorial/response-status-code.md @@ -9,16 +9,22 @@ * и других. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "Примечание" - Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса. +/// note | Примечание + +Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса. + +/// Параметр `status_code` принимает число, обозначающее HTTP код статуса ответа. -!!! info "Информация" - В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python. +/// info | Информация + +В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python. + +/// Это позволит: @@ -27,15 +33,21 @@ -!!! note "Примечание" - Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела. +/// note | Примечание + +Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела. + +FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует. - FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует. +/// ## Об HTTP кодах статуса ответа -!!! note "Примечание" - Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу. +/// note | Примечание + +Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу. + +/// В протоколе HTTP числовой код состояния из 3 цифр отправляется как часть ответа. @@ -54,15 +66,18 @@ * Для общих ошибок со стороны клиента можно просто использовать код `400`. * `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов. -!!! tip "Подсказка" - Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа. +/// tip | Подсказка + +Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа. + +/// ## Краткие обозначения для запоминания названий кодов Рассмотрим предыдущий пример еще раз: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` – это код статуса "Создано". @@ -72,17 +87,20 @@ Для удобства вы можете использовать переменные из `fastapi.status`. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` Они содержат те же числовые значения, но позволяют использовать подсказки редактора для выбора кода статуса: -!!! note "Технические детали" - Вы также можете использовать `from starlette import status` вместо `from fastapi import status`. +/// note | Технические детали + +Вы также можете использовать `from starlette import status` вместо `from fastapi import status`. + +**FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette. - **FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette. +/// ## Изменение кода статуса по умолчанию diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index e1011805a..daa264afc 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -8,24 +8,31 @@ Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-21" +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15-23" +{!> ../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API. -!!! tip Подсказка - Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации. +/// tip | Подсказка + +Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации. + +Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д. - Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д. +/// ## Дополнительные аргументы поля `Field` @@ -33,20 +40,27 @@ Вы можете использовать это, чтобы добавить аргумент `example` для каждого поля: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +```Python hl_lines="4 10-13" +{!> ../../docs_src/schema_extra_example/tutorial002.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +/// warning | Внимание -!!! warning Внимание - Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации. +Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации. + +/// ## Использование `example` и `examples` в OpenAPI @@ -66,41 +80,57 @@ Здесь мы передаём аргумент `example`, как пример данных ожидаемых в параметре `Body()`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="22-27" +{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="22-27" +{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +```Python hl_lines="23-28" +{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+" +/// tip | Заметка - ```Python hl_lines="23-28" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +Рекомендуется использовать версию с `Annotated`, если это возможно. -=== "Python 3.10+ non-Annotated" +/// - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +```Python hl_lines="18-23" +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +/// tip | Заметка - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +Рекомендуется использовать версию с `Annotated`, если это возможно. + +/// + +```Python hl_lines="20-25" +{!> ../../docs_src/schema_extra_example/tutorial003.py!} +``` + +//// ### Аргумент "example" в UI документации @@ -121,41 +151,57 @@ * `value`: Это конкретный пример, который отображается, например, в виде типа `dict`. * `externalValue`: альтернатива параметру `value`, URL-адрес, указывающий на пример. Хотя это может не поддерживаться таким же количеством инструментов разработки и тестирования API, как параметр `value`. -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23-49" +{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23-49" +{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +``` - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` +```Python hl_lines="24-50" +{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip | Заметка - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +Рекомендуется использовать версию с `Annotated`, если это возможно. - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="19-45" +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} +``` - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. +//// - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +//// tab | Python 3.8+ non-Annotated + +/// tip | Заметка + +Рекомендуется использовать версию с `Annotated`, если это возможно. + +/// + +```Python hl_lines="21-47" +{!> ../../docs_src/schema_extra_example/tutorial004.py!} +``` + +//// ### Аргумент "examples" в UI документации @@ -165,10 +211,13 @@ ## Технические Детали -!!! warning Внимание - Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**. +/// warning | Внимание + +Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**. + +Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить. - Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить. +/// Когда вы добавляете пример внутрь модели Pydantic, используя `schema_extra` или `Field(example="something")`, этот пример добавляется в **JSON Schema** для данной модели Pydantic. diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index fdeccc01a..484dfceff 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -20,36 +20,47 @@ Скопируйте пример в файл `main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python +{!> ../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/security/tutorial001_an.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ без Annotated - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +/// tip | Подсказка -=== "Python 3.8+ без Annotated" +Предпочтительнее использовать версию с аннотацией, если это возможно. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +```Python +{!> ../../docs_src/security/tutorial001.py!} +``` +//// ## Запуск -!!! info "Дополнительная информация" - Вначале, установите библиотеку `python-multipart`. +/// info | Дополнительная информация - А именно: `pip install python-multipart`. +Вначале, установите библиотеку `python-multipart`. - Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`. +А именно: `pip install python-multipart`. + +Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`. + +/// Запустите ваш сервер: @@ -71,17 +82,23 @@ $ uvicorn main:app --reload -!!! check "Кнопка авторизации!" - У вас уже появилась новая кнопка "Authorize". +/// check | Кнопка авторизации! + +У вас уже появилась новая кнопка "Authorize". - А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать. +А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать. + +/// При нажатии на нее появляется небольшая форма авторизации, в которую нужно ввести `имя пользователя` и `пароль` (и другие необязательные поля): -!!! note "Технические детали" - Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем. +/// note | Технические детали + +Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем. + +/// Конечно, это не фронтенд для конечных пользователей, но это отличный автоматический инструмент для интерактивного документирования всех ваших API. @@ -123,51 +140,69 @@ OAuth2 был разработан для того, чтобы бэкэнд ил В данном примере мы будем использовать **OAuth2**, с аутентификацией по паролю, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`. -!!! info "Дополнительная информация" - Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим. +/// info | Дополнительная информация + +Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим. + +И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант. - И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант. +В этом случае **FastAPI** также предоставляет инструменты для его реализации. - В этом случае **FastAPI** также предоставляет инструменты для его реализации. +/// При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8" +{!> ../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="7" +{!> ../../docs_src/security/tutorial001_an.py!} +``` + +//// - ```Python hl_lines="8" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+" +/// tip | Подсказка - ```Python hl_lines="7" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +Предпочтительнее использовать версию с аннотацией, если это возможно. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +```Python hl_lines="6" +{!> ../../docs_src/security/tutorial001.py!} +``` + +//// + +/// tip | Подсказка - ```Python hl_lines="6" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`. -!!! tip "Подсказка" - Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`. +Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`. - Поскольку мы используем относительный URL, если ваш API расположен по адресу `https://example.com/`, то он будет ссылаться на `https://example.com/token`. Если же ваш API расположен по адресу `https://example.com/api/v1/`, то он будет ссылаться на `https://example.com/api/v1/token`. +Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. - Использование относительного URL важно для того, чтобы ваше приложение продолжало работать даже в таких сложных случаях, как оно находится [за прокси-сервером](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. +/// Этот параметр не создает конечную точку / *операцию пути*, а объявляет, что URL `/token` будет таким, который клиент должен использовать для получения токена. Эта информация используется в OpenAPI, а затем в интерактивных системах документации API. Вскоре мы создадим и саму операцию пути. -!!! info "Дополнительная информация" - Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`. +/// info | Дополнительная информация + +Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`. + +Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней. - Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней. +/// Переменная `oauth2_scheme` является экземпляром `OAuth2PasswordBearer`, но она также является "вызываемой". @@ -183,35 +218,47 @@ oauth2_scheme(some, parameters) Теперь вы можете передать ваш `oauth2_scheme` в зависимость с помощью `Depends`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="12" - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python hl_lines="12" +{!> ../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/security/tutorial001_an.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Предпочтительнее использовать версию с аннотацией, если это возможно. - ```Python hl_lines="10" - {!> ../../../docs_src/security/tutorial001.py!} - ``` +/// + +```Python hl_lines="10" +{!> ../../docs_src/security/tutorial001.py!} +``` + +//// Эта зависимость будет предоставлять `строку`, которая присваивается параметру `token` в *функции операции пути*. **FastAPI** будет знать, что он может использовать эту зависимость для определения "схемы безопасности" в схеме OpenAPI (и автоматической документации по API). -!!! info "Технические детали" - **FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`. +/// info | Технические детали + +**FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`. + +Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI. - Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI. +/// ## Что он делает diff --git a/docs/ru/docs/tutorial/security/index.md b/docs/ru/docs/tutorial/security/index.md index d5fe4e76f..e4969c4cf 100644 --- a/docs/ru/docs/tutorial/security/index.md +++ b/docs/ru/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth2 включает в себя способы аутентификации OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS. -!!! tip "Подсказка" - В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) +/// tip | Подсказка +В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI может использовать следующие схемы авт * Это автоматическое обнаружение определено в спецификации OpenID Connect. -!!! tip "Подсказка" - Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. +/// tip | Подсказка + +Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. + +Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас. - Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас. +/// ## Преимущества **FastAPI** diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index ec09eb5a3..0287fb017 100644 --- a/docs/ru/docs/tutorial/static-files.md +++ b/docs/ru/docs/tutorial/static-files.md @@ -8,13 +8,16 @@ * "Примонтируйте" экземпляр `StaticFiles()` с указанием определенной директории. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` -!!! заметка "Технические детали" - Вы также можете использовать `from starlette.staticfiles import StaticFiles`. +/// note | Технические детали - **FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette. +Вы также можете использовать `from starlette.staticfiles import StaticFiles`. + +**FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette. + +/// ### Что такое "Монтирование" diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index ca47a6f51..0485ef801 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## Использование класса `TestClient` -!!! info "Информация" - Для использования класса `TestClient` необходимо установить библиотеку `httpx`. +/// info | Информация - Например, так: `pip install httpx`. +Для использования класса `TestClient` необходимо установить библиотеку `httpx`. + +Например, так: `pip install httpx`. + +/// Импортируйте `TestClient`. @@ -24,23 +27,32 @@ Напишите простое утверждение с `assert` дабы проверить истинность Python-выражения (это тоже стандарт `pytest`). ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` -!!! tip "Подсказка" - Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`. +/// tip | Подсказка + +Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`. + +И вызов клиента также осуществляется без `await`. + +Это позволяет вам использовать `pytest` без лишних усложнений. + +/// + +/// note | Технические детали + +Также можно написать `from starlette.testclient import TestClient`. - И вызов клиента также осуществляется без `await`. +**FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика. - Это позволяет вам использовать `pytest` без лишних усложнений. +/// -!!! note "Технические детали" - Также можно написать `from starlette.testclient import TestClient`. +/// tip | Подсказка - **FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика. +Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве. -!!! tip "Подсказка" - Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве. +/// ## Разделение тестов и приложения @@ -50,7 +62,7 @@ ### Файл приложения **FastAPI** -Допустим, структура файлов Вашего приложения похожа на ту, что описана на странице [Более крупные приложения](./bigger-applications.md){.internal-link target=_blank}: +Допустим, структура файлов Вашего приложения похожа на ту, что описана на странице [Более крупные приложения](bigger-applications.md){.internal-link target=_blank}: ``` . @@ -63,7 +75,7 @@ ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### Файл тестов @@ -81,7 +93,7 @@ Так как оба файла находятся в одной директории, для импорта объекта приложения из файла `main` в файл `test_main` Вы можете использовать относительный импорт: ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ...и писать дальше тесты, как и раньше. @@ -110,48 +122,64 @@ Обе *операции пути* требуют наличия в запросе заголовка `X-Token`. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` - !!! tip "Подсказка" - По возможности используйте версию с `Annotated`. +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// tab | Python 3.10+ без Annotated -=== "Python 3.8+ без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - По возможности используйте версию с `Annotated`. +По возможности используйте версию с `Annotated`. - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка + +По возможности используйте версию с `Annotated`. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### Расширенный файл тестов Теперь обновим файл `test_main.py`, добавив в него тестов: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` Если Вы не знаете, как передать информацию в запросе, можете воспользоваться поисковиком (погуглить) и задать вопрос: "Как передать информацию в запросе с помощью `httpx`", можно даже спросить: "Как передать информацию в запросе с помощью `requests`", поскольку дизайн HTTPX основан на дизайне Requests. @@ -168,10 +196,13 @@ Для получения дополнительной информации о передаче данных на бэкенд с помощью `httpx` или `TestClient` ознакомьтесь с документацией HTTPX. -!!! info "Информация" - Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic. +/// info | Информация + +Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic. + +Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}. - Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}. +/// ## Запуск тестов diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md new file mode 100644 index 000000000..836e63c8a --- /dev/null +++ b/docs/tr/docs/advanced/index.md @@ -0,0 +1,36 @@ +# Gelişmiş Kullanıcı Rehberi + +## Ek Özellikler + +[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfası **FastAPI**'ın tüm ana özelliklerini tanıtmaya yetecektir. + +İlerleyen bölümlerde diğer seçenekler, konfigürasyonlar ve ek özellikleri göreceğiz. + +/// tip | İpucu + +Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. + +Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. + +/// + +## Önce Öğreticiyi Okuyun + +[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfasındaki bilgilerle **FastAPI**'nın çoğu özelliğini kullanabilirsiniz. + +Sonraki bölümler bu sayfayı okuduğunuzu ve bu ana fikirleri bildiğinizi varsayarak hazırlanmıştır. + +## Diğer Kurslar + +[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfası ve bu **Gelişmiş Kullanıcı Rehberi**, öğretici bir kılavuz (bir kitap gibi) şeklinde yazılmıştır ve **FastAPI'ı öğrenmek** için yeterli olsa da, ek kurslarla desteklemek isteyebilirsiniz. + +Belki de öğrenme tarzınıza daha iyi uyduğu için başka kursları tercih edebilirsiniz. + +Bazı kurs sağlayıcıları ✨ [**FastAPI destekçileridir**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, bu FastAPI ve **ekosisteminin** sürekli ve sağlıklı bir şekilde **gelişmesini** sağlar. + +Ayrıca, size **iyi bir öğrenme deneyimi** sağlamakla kalmayıp, **iyi ve sağlıklı bir framework** olan FastAPI'a ve ve **topluluğuna** (yani size) olan gerçek bağlılıklarını gösterir. + +Onların kurslarını denemek isteyebilirsiniz: + +* Talk Python Training +* Test-Driven Development diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md new file mode 100644 index 000000000..709f74c72 --- /dev/null +++ b/docs/tr/docs/advanced/security/index.md @@ -0,0 +1,19 @@ +# Gelişmiş Güvenlik + +## Ek Özellikler + +[Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasında ele alınanların dışında güvenlikle ilgili bazı ek özellikler vardır. + +/// tip | İpucu + +Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. + +Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. + +/// + +## Önce Öğreticiyi Okuyun + +Sonraki bölümler [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasını okuduğunuzu varsayarak hazırlanmıştır. + +Bu bölümler aynı kavramlara dayanır, ancak bazı ek işlevsellikler sağlar. diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..12b6ab60f --- /dev/null +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -0,0 +1,15 @@ +# WebSockets'i Test Etmek + +WebSockets testi yapmak için `TestClient`'ı kullanabilirsiniz. + +Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e bağlanabilirsiniz: + +```Python hl_lines="27-31" +{!../../docs_src/app_testing/tutorial002.py!} +``` + +/// note | Not + +Daha fazla detay için Starlette'in Websockets'i Test Etmek dokümantasyonunu inceleyin. + +/// diff --git a/docs/tr/docs/advanced/wsgi.md b/docs/tr/docs/advanced/wsgi.md new file mode 100644 index 000000000..bc8da16df --- /dev/null +++ b/docs/tr/docs/advanced/wsgi.md @@ -0,0 +1,37 @@ +# WSGI - Flask, Django ve Daha Fazlasını FastAPI ile Kullanma + +WSGI uygulamalarını [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank} bölümlerinde gördüğünüz gibi bağlayabilirsiniz. + +Bunun için `WSGIMiddleware` ile Flask, Django vb. WSGI uygulamanızı sarmalayabilir ve FastAPI'ya bağlayabilirsiniz. + +## `WSGIMiddleware` Kullanımı + +`WSGIMiddleware`'ı projenize dahil edin. + +Ardından WSGI (örneğin Flask) uygulamanızı middleware ile sarmalayın. + +Son olarak da bir yol altında bağlama işlemini gerçekleştirin. + +```Python hl_lines="2-3 23" +{!../../docs_src/wsgi/tutorial001.py!} +``` + +## Kontrol Edelim + +Artık `/v1/` yolunun altındaki her istek Flask uygulaması tarafından işlenecektir. + +Geri kalanı ise **FastAPI** tarafından işlenecektir. + +Eğer uygulamanızı çalıştırıp http://localhost:8000/v1/ adresine giderseniz, Flask'tan gelen yanıtı göreceksiniz: + +```txt +Hello, World from Flask! +``` + +Eğer http://localhost:8000/v2/ adresine giderseniz, FastAPI'dan gelen yanıtı göreceksiniz: + +```JSON +{ + "message": "Hello World" +} +``` diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md index 462d8b304..c98b966b5 100644 --- a/docs/tr/docs/alternatives.md +++ b/docs/tr/docs/alternatives.md @@ -30,11 +30,17 @@ Django REST framework'ü, Django'nun API kabiliyetlerini arttırmak için arka p **Otomatik API dökümantasyonu**nun ilk örneklerinden biri olduğu için, **FastAPI** arayışına ilham veren ilk fikirlerden biri oldu. -!!! note "Not" - Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi. +/// note | Not -!!! check "**FastAPI**'a nasıl ilham verdi?" - Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı. +Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi. + +/// + +/// check | **FastAPI**'a nasıl ilham verdi? + +Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı. + +/// ### Flask @@ -50,10 +56,13 @@ Uygulama parçalarının böyle ayrılıyor oluşu ve istenilen özelliklerle ge Flask'ın basitliği göz önünde bulundurulduğu zaman, API geliştirmek için iyi bir seçim gibi görünüyordu. Sıradaki şey ise Flask için bir "Django REST Framework"! -!!! check "**FastAPI**'a nasıl ilham verdi?" - Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı. +/// check | **FastAPI**'a nasıl ilham verdi? - Basit ve kullanması kolay bir yönlendirme sistemine sahip olmalı. +Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı. + +Basit ve kullanması kolay bir yönlendirme sistemine sahip olmalı. + +/// ### Requests @@ -89,10 +98,13 @@ def read_url(): `requests.get(...)` ile `@app.get(...)` arasındaki benzerliklere bakın. -!!! check "**FastAPI**'a nasıl ilham verdi?" - * Basit ve sezgisel bir API'ya sahip olmalı. - * HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı. - * Mantıklı varsayılan değerlere ve buna rağmen güçlü bir özelleştirme desteğine sahip olmalı. +/// check | **FastAPI**'a nasıl ilham verdi? + +* Basit ve sezgisel bir API'ya sahip olmalı. +* HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı. +* Mantıklı varsayılan değerlere ve buna rağmen güçlü bir özelleştirme desteğine sahip olmalı. + +/// ### Swagger / OpenAPI @@ -106,15 +118,18 @@ Swagger bir noktada Linux Foundation'a verildi ve adı OpenAPI olarak değiştir İşte bu yüzden versiyon 2.0 hakkında konuşurken "Swagger", versiyon 3 ve üzeri için ise "OpenAPI" adını kullanmak daha yaygın. -!!! check "**FastAPI**'a nasıl ilham verdi?" - API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı. +/// check | **FastAPI**'a nasıl ilham verdi? + +API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı. + +Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli: - Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli: +* Swagger UI +* ReDoc - * Swagger UI - * ReDoc +Yukarıdaki ikisi oldukça popüler ve istikrarlı olduğu için seçildi, ancak hızlı bir araştırma yaparak **FastAPI** ile kullanabileceğiniz pek çok OpenAPI alternatifi arayüz bulabilirsiniz. - Yukarıdaki ikisi oldukça popüler ve istikrarlı olduğu için seçildi, ancak hızlı bir araştırma yaparak **FastAPI** ile kullanabileceğiniz pek çok OpenAPI alternatifi arayüz bulabilirsiniz. +/// ### Flask REST framework'leri @@ -132,8 +147,11 @@ Marshmallow bu özellikleri sağlamak için geliştirilmişti. Benim de geçmiş Ama... Python'un tip belirteçleri gelmeden önce oluşturulmuştu. Yani her şemayı tanımlamak için Marshmallow'un sunduğu spesifik araçları ve sınıfları kullanmanız gerekiyordu. -!!! check "**FastAPI**'a nasıl ilham verdi?" - Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı. +/// check | **FastAPI**'a nasıl ilham verdi? + +Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı. + +/// ### Webargs @@ -145,11 +163,17 @@ Veri doğrulama için arka planda Marshmallow kullanıyor, hatta aynı geliştir Webargs da harika bir araç ve onu da geçmişte henüz **FastAPI** yokken çok kullandım. -!!! info "Bilgi" - Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu. +/// info | Bilgi + +Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu. -!!! check "**FastAPI**'a nasıl ilham verdi?" - Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı. +/// + +/// check | **FastAPI**'a nasıl ilham verdi? + +Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı. + +/// ### APISpec @@ -167,11 +191,17 @@ Fakat sonrasında yine mikro sözdizimi problemiyle karşılaşıyoruz. Python m Editör bu konuda pek yardımcı olamaz. Üstelik eğer parametreleri ya da Marshmallow şemalarını değiştirip YAML kodunu güncellemeyi unutursak artık döküman geçerliliğini yitiriyor. -!!! info "Bilgi" - APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu. +/// info | Bilgi + +APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu. + +/// + +/// check | **FastAPI**'a nasıl ilham verdi? -!!! check "**FastAPI**'a nasıl ilham verdi?" - API'lar için açık standart desteği olmalı (OpenAPI gibi). +API'lar için açık standart desteği olmalı (OpenAPI gibi). + +/// ### Flask-apispec @@ -193,11 +223,17 @@ Bunu kullanmak, bir kaç NestJS (and Angular) @@ -213,24 +249,33 @@ Ama TypeScript verileri kod JavaScript'e derlendikten sonra korunmadığından, İç içe geçen derin modelleri pek iyi işleyemiyor. Yani eğer istekteki JSON gövdesi derin bir JSON objesiyse düzgün bir şekilde dökümante edilip doğrulanamıyor. -!!! check "**FastAPI**'a nasıl ilham oldu?" - Güzel bir editör desteği için Python tiplerini kullanmalı. +/// check | **FastAPI**'a nasıl ilham oldu? + +Güzel bir editör desteği için Python tiplerini kullanmalı. - Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı. +Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı. + +/// ### Sanic Sanic, `asyncio`'ya dayanan son derece hızlı Python kütüphanelerinden biriydi. Flask'a epey benzeyecek şekilde geliştirilmişti. -!!! note "Teknik detaylar" - İçerisinde standart Python `asyncio` döngüsü yerine `uvloop` kullanıldı. Hızının asıl kaynağı buydu. +/// note | Teknik detaylar + +İçerisinde standart Python `asyncio` döngüsü yerine `uvloop` kullanıldı. Hızının asıl kaynağı buydu. + +Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi de açık karşılaştırmalarda Sanicten daha hızlı gözüküyor. - Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi de açık karşılaştırmalarda Sanicten daha hızlı gözüküyor. +/// -!!! check "**FastAPI**'a nasıl ilham oldu?" - Uçuk performans sağlayacak bir yol bulmalı. +/// check | **FastAPI**'a nasıl ilham oldu? - Tam da bu yüzden **FastAPI** Starlette'e dayanıyor, çünkü Starlette şu anda kullanılabilir en hızlı framework. (üçüncü parti karşılaştırmalı testlerine göre) +Uçuk performans sağlayacak bir yol bulmalı. + +Tam da bu yüzden **FastAPI** Starlette'e dayanıyor, çünkü Starlette şu anda kullanılabilir en hızlı framework. (üçüncü parti karşılaştırmalı testlerine göre) + +/// ### Falcon @@ -240,12 +285,15 @@ Falcon ise bir diğer yüksek performanslı Python framework'ü. Minimal olacak Yani veri doğrulama, veri dönüştürme ve dökümantasyonun hepsi kodda yer almalı, otomatik halledemiyoruz. Ya da Falcon üzerine bir framework olarak uygulanmaları gerekiyor, aynı Hug'da olduğu gibi. Bu ayrım Falcon'un tasarımından esinlenen, istek ve cevap objelerini parametre olarak işleyen diğer kütüphanelerde de yer alıyor. -!!! check "**FastAPI**'a nasıl ilham oldu?" - Harika bir performans'a sahip olmanın yollarını bulmalı. +/// check | **FastAPI**'a nasıl ilham oldu? + +Harika bir performans'a sahip olmanın yollarını bulmalı. - Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu. +Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu. - FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor. +FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor. + +/// ### Molten @@ -263,12 +311,15 @@ Biraz daha detaylı ayarlamalara gerek duyuyor. Ayrıca Yol'lar fonksiyonun üstünde endpoint'i işleyen dekoratörler yerine farklı yerlerde tanımlanan fonksiyonlarla belirlenir. Bu Flask (ve Starlette) yerine daha çok Django'nun yaklaşımına daha yakın bir metot. Bu, kodda nispeten birbiriyle sıkı ilişkili olan şeyleri ayırmaya sebep oluyor. -!!! check "**FastAPI**'a nasıl ilham oldu?" - Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu. +/// check | **FastAPI**'a nasıl ilham oldu? + +Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu. + +Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı oldu. Şu anda bütün bu özellikler Pydantic'in yapısında yer alıyor. - Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı oldu. Şu anda bütün bu özellikler Pydantic'in yapısında yer alıyor. +/// -### Hug +### Hug Hug, Python tip belirteçlerini kullanarak API parametrelerinin tipini belirlemeyi uygulayan ilk framework'lerdendi. Bu, diğer araçlara da ilham kaynağı olan harika bir fikirdi. @@ -282,15 +333,21 @@ Ayrıca ilginç ve çok rastlanmayan bir özelliği vardı: aynı framework'ü k Senkron çalışan Python web framework'lerinin standardına (WSGI) dayandığından dolayı Websocket'leri ve diğer şeyleri işleyemiyor, ancak yine de yüksek performansa sahip. -!!! info "Bilgi" - Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi. +/// info | Bilgi + +Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi. + +/// + +/// check | **FastAPI**'a nasıl ilham oldu? -!!! check "**FastAPI**'a nasıl ilham oldu?" - Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi. +Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi. - **FastAPI**, Python tip belirteçlerini kullanarak parametre belirlemede ve API'ı otomatık tanımlayan bir şema üretmede de Hug'a esinlendi. +**FastAPI**, Python tip belirteçlerini kullanarak parametre belirlemede ve API'ı otomatık tanımlayan bir şema üretmede de Hug'a esinlendi. - **FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı. +**FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı. + +/// ### APIStar (<= 0.5) @@ -316,23 +373,29 @@ Geliştiricinin Starlette'e odaklanması gerekince proje de artık bir API web f Artık APIStar, OpenAPI özelliklerini doğrulamak için bir dizi araç sunan bir proje haline geldi. -!!! info "Bilgi" - APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi: +/// info | Bilgi + +APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi: + +* Django REST Framework +* **FastAPI**'ın da dayandığı Starlette +* Starlette ve **FastAPI** tarafından da kullanılan Uvicorn - * Django REST Framework - * **FastAPI**'ın da dayandığı Starlette - * Starlette ve **FastAPI** tarafından da kullanılan Uvicorn +/// -!!! check "**FastAPI**'a nasıl ilham oldu?" - Var oldu. +/// check | **FastAPI**'a nasıl ilham oldu? - Aynı Python veri tipleriyle birden fazla şeyi belirleme (veri doğrulama, veri dönüştürme ve dökümantasyon), bir yandan da harika bir editör desteği sunma, benim muhteşem bulduğum bir fikirdi. +Var oldu. - Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti. +Aynı Python veri tipleriyle birden fazla şeyi belirleme (veri doğrulama, veri dönüştürme ve dökümantasyon), bir yandan da harika bir editör desteği sunma, benim muhteşem bulduğum bir fikirdi. - Sonra APIStar bir sunucu olmayı bıraktı ve Starlette oluşturuldu. Starlette, böyle bir sunucu sistemi için daha iyi bir temel sunuyordu. Bu da **FastAPI**'ın son esin kaynağıydı. +Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti. - Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, tip desteği sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum. +Sonra APIStar bir sunucu olmayı bıraktı ve Starlette oluşturuldu. Starlette, böyle bir sunucu sistemi için daha iyi bir temel sunuyordu. Bu da **FastAPI**'ın son esin kaynağıydı. + +Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, tip desteği sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum. + +/// ## **FastAPI** Tarafından Kullanılanlar @@ -344,10 +407,13 @@ Tip belirteçleri kullanıyor olması onu aşırı sezgisel yapıyor. Marshmallow ile karşılaştırılabilir. Ancak karşılaştırmalarda Marshmallowdan daha hızlı görünüyor. Aynı Python tip belirteçlerine dayanıyor ve editör desteği de harika. -!!! check "**FastAPI** nerede kullanıyor?" - Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için! +/// check | **FastAPI** nerede kullanıyor? + +Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için! - **FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor. +**FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor. + +/// ### Starlette @@ -376,18 +442,23 @@ Ancak otomatik veri doğrulama, veri dönüştürme ve dökümantasyon sağlamyo Bu, **FastAPI**'ın onun üzerine tamamen Python tip belirteçlerine bağlı olarak eklediği (Pydantic ile) ana şeylerden biri. **FastAPI** bunun yanında artı olarak bağımlılık enjeksiyonu sistemi, güvenlik araçları, OpenAPI şema üretimi ve benzeri özellikler de ekliyor. -!!! note "Teknik Detaylar" - ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil. +/// note | Teknik Detaylar + +ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil. + +Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak kullanılmakta. Bu, Uvicorn'u farklı ASGI sunucularıyla (Daphne veya Hypercorn gibi) değiştirebileceğiniz veya `python-socketio` gibi ASGI ile uyumlu araçları ekleyebileciğiniz için birlikte çalışılabilirliği büyük ölçüde arttırıyor. - Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak kullanılmakta. Bu, Uvicorn'u farklı ASGI sunucularıyla (Daphne veya Hypercorn gibi) değiştirebileceğiniz veya `python-socketio` gibi ASGI ile uyumlu araçları ekleyebileciğiniz için birlikte çalışılabilirliği büyük ölçüde arttırıyor. +/// -!!! check "**FastAPI** nerede kullanıyor?" +/// check | **FastAPI** nerede kullanıyor? - Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta. +Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta. - `FastAPI` sınıfının kendisi direkt olarak `Starlette` sınıfını miras alıyor! +`FastAPI` sınıfının kendisi direkt olarak `Starlette` sınıfını miras alıyor! - Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz. +Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz. + +/// ### Uvicorn @@ -397,12 +468,15 @@ Bir web framework'ünden ziyade bir sunucudur, yani yollara bağlı yönlendirme Starlette ve **FastAPI** için tavsiye edilen sunucu Uvicorndur. -!!! check "**FastAPI** neden tavsiye ediyor?" - **FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn! +/// check | **FastAPI** neden tavsiye ediyor? + +**FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn! + +Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz! - Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz! +Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz. - Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz. +/// ## Karşılaştırma ve Hız diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md index aab939189..558a79cb7 100644 --- a/docs/tr/docs/async.md +++ b/docs/tr/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! not - Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. +/// note | Not + +Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. + +/// --- @@ -363,12 +366,15 @@ FastAPI'ye (Starlette aracılığıyla) güç veren ve bu kadar etkileyici bir p ## Çok Teknik Detaylar -!!! warning - Muhtemelen burayı atlayabilirsiniz. +/// warning + +Muhtemelen burayı atlayabilirsiniz. + +Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır. - Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır. +Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin. - Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin. +/// ### Path fonksiyonu @@ -376,7 +382,7 @@ FastAPI'ye (Starlette aracılığıyla) güç veren ve bu kadar etkileyici bir p Yukarıda açıklanan şekilde çalışmayan başka bir asenkron framework'den geliyorsanız ve küçük bir performans kazancı (yaklaşık 100 nanosaniye) için "def" ile *path fonksiyonu* tanımlamaya alışkınsanız, **FastAPI**'de tam tersi olacağını unutmayın. Bu durumlarda, *path fonksiyonu* G/Ç engelleyen durum oluşturmadıkça "async def" kullanmak daha iyidir. -Yine de, her iki durumda da, **FastAPI**'nin önceki frameworkden [hala daha hızlı](index.md#performance){.internal-link target=_blank} (veya en azından karşılaştırılabilir) olma olasılığı vardır. +Yine de, her iki durumda da, **FastAPI**'nin önceki frameworkden [hala daha hızlı](index.md#performans){.internal-link target=_blank} (veya en azından karşılaştırılabilir) olma olasılığı vardır. ### Bagımlılıklar diff --git a/docs/tr/docs/deployment/cloud.md b/docs/tr/docs/deployment/cloud.md new file mode 100644 index 000000000..5639567d4 --- /dev/null +++ b/docs/tr/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# FastAPI Uygulamasını Bulut Sağlayıcılar Üzerinde Yayınlama + +FastAPI uygulamasını yayınlamak için hemen hemen **herhangi bir bulut sağlayıcıyı** kullanabilirsiniz. + +Büyük bulut sağlayıcıların çoğu FastAPI uygulamasını yayınlamak için kılavuzlara sahiptir. + +## Bulut Sağlayıcılar - Sponsorlar + +Bazı bulut sağlayıcılar ✨ [**FastAPI destekçileridir**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, bu FastAPI ve **ekosisteminin** sürekli ve sağlıklı bir şekilde **gelişmesini** sağlar. + +Ayrıca, size **iyi servisler** sağlamakla kalmayıp, **iyi ve sağlıklı bir framework** olan FastAPI'a bağlılıklarını gösterir. + +Bu hizmetleri denemek ve kılavuzlarını incelemek isteyebilirsiniz: + +* Platform.sh +* Porter +* Coherence diff --git a/docs/tr/docs/deployment/index.md b/docs/tr/docs/deployment/index.md new file mode 100644 index 000000000..e03bb4ee0 --- /dev/null +++ b/docs/tr/docs/deployment/index.md @@ -0,0 +1,21 @@ +# Deployment (Yayınlama) + +**FastAPI** uygulamasını deploy etmek oldukça kolaydır. + +## Deployment Ne Anlama Gelir? + +Bir uygulamayı **deploy** etmek (yayınlamak), uygulamayı **kullanıcılara erişilebilir hale getirmek** için gerekli adımları gerçekleştirmek anlamına gelir. + +Bir **Web API** için bu süreç normalde uygulamayı **uzak bir makineye** yerleştirmeyi, iyi performans, kararlılık vb. özellikler sağlayan bir **sunucu programı** ile **kullanıcılarınızın** uygulamaya etkili ve kesintisiz bir şekilde **erişebilmesini** kapsar. + +Bu, kodu sürekli olarak değiştirdiğiniz, hata alıp hata giderdiğiniz, geliştirme sunucusunu durdurup yeniden başlattığınız vb. **geliştirme** aşamalarının tam tersidir. + +## Deployment Stratejileri + +Kullanım durumunuza ve kullandığınız araçlara bağlı olarak bir kaç farklı yol izleyebilirsiniz. + +Bir dizi araç kombinasyonunu kullanarak kendiniz **bir sunucu yayınlayabilirsiniz**, yayınlama sürecinin bir kısmını sizin için gerçekleştiren bir **bulut hizmeti** veya diğer olası seçenekleri kullanabilirsiniz. + +**FastAPI** uygulamasını yayınlarken aklınızda bulundurmanız gereken ana kavramlardan bazılarını size göstereceğim (ancak bunların çoğu diğer web uygulamaları için de geçerlidir). + +Sonraki bölümlerde akılda tutulması gereken diğer ayrıntıları ve yayınlama tekniklerinden bazılarını göreceksiniz. ✨ diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md deleted file mode 100644 index 78eaf1729..000000000 --- a/docs/tr/docs/external-links.md +++ /dev/null @@ -1,33 +0,0 @@ -# Harici Bağlantılar ve Makaleler - -**FastAPI** sürekli büyüyen harika bir topluluğa sahiptir. - -**FastAPI** ile alakalı birçok yazı, makale, araç ve proje bulunmaktadır. - -Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır. - -!!! tip "İpucu" - Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir Pull Request oluşturabilirsiniz. - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projeler - -`fastapi` konulu en son GitHub projeleri: - -
-
diff --git a/docs/tr/docs/fastapi-people.md b/docs/tr/docs/fastapi-people.md deleted file mode 100644 index 6dd4ec061..000000000 --- a/docs/tr/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI Topluluğu - -FastAPI, her kökenden insanı ağırlayan harika bir topluluğa sahip. - -## Yazan - Geliştiren - -Merhaba! 👋 - -İşte bu benim: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Cevaplar: {{ user.answers }}
Pull Request'ler: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Ben **FastAPI**'ın geliştiricisiyim. Bununla ilgili daha fazla bilgiyi şurada okuyabilirsiniz: [FastAPI yardım - yardım al - benimle iletişime geç](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...burada size harika FastAPI topluluğunu göstermek istiyorum. - ---- - -**FastAPI**, topluluğundan çok destek alıyor. Ben de onların katkılarını vurgulamak istiyorum. - -Bu insanlar: - -* [GitHubdaki soruları cevaplayarak diğerlerine yardım ediyor](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Pull Request'ler oluşturuyor](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Pull Request'leri gözden geçiriyorlar, [özellikle çeviriler için bu çok önemli](contributing.md#translations){.internal-link target=_blank}. - -Onları bir alkışlayalım. 👏 🙇 - -## Geçen Ayın En Aktif Kullanıcıları - -Geçtiğimiz ay boyunca [GitHub'da diğerlerine en çok yardımcı olan](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} kullanıcılar. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Cevaplanan soru sayısı: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Uzmanlar - -İşte **FastAPI Uzmanları**. 🤓 - -Uzmanlarımız ise *tüm zamanlar boyunca* [GitHub'da insanların sorularına en çok yardımcı olan](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} insanlar. - -Bir çok kullanıcıya yardım ederek uzman olduklarını kanıtladılar! ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Cevaplanan soru sayısı: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## En Fazla Katkıda Bulunanlar - -Şimdi ise sıra **en fazla katkıda bulunanlar**da. 👷 - -Bu kullanıcılar en fazla [kaynak koduyla birleştirilen Pull Request'lere](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} sahip! - -Kaynak koduna, dökümantasyona, çevirilere ve bir sürü şeye katkıda bulundular. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Request sayısı: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Bunlar dışında katkıda bulunan, yüzden fazla, bir sürü insan var. Hepsini FastAPI GitHub Katkıda Bulunanlar sayfasında görebilirsin. 👷 - -## En Fazla Değerlendirme Yapanlar - -İşte **en çok değerlendirme yapanlar**. 🕵️ - -### Çeviri Değerlendirmeleri - -Yalnızca birkaç dil konuşabiliyorum (ve çok da iyi değilim 😅). Bu yüzden değerlendirme yapanların da döküman çevirilerini [**onaylama yetkisi**](contributing.md#translations){.internal-link target=_blank} var. Onlar olmasaydı çeşitli dillerde dökümantasyon da olmazdı. - ---- - -**En fazla değerlendirme yapanlar** 🕵️ kodun, dökümantasyonun ve özellikle **çevirilerin** Pull Request'lerini inceleyerek kalitesinden emin oldular. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Değerlendirme sayısı: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsorlar - -işte **Sponsorlarımız**. 😎 - -Çoğunlukla GitHub Sponsorları aracılığıyla olmak üzere, **FastAPI** ve diğer projelerdeki çalışmalarımı destekliyorlar. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Altın Sponsorlar - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Gümüş Sponsorlar - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronz Sponsorlar - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Bireysel Sponsorlar - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## Veriler - Teknik detaylar - -Bu sayfanın temel amacı, topluluğun başkalarına yardım etme çabasını vurgulamaktır. - -Özellikle normalde daha az görünür olan ve çoğu durumda daha zahmetli olan, diğerlerine sorularında yardımcı olmak, çevirileri ve Pull Request'leri gözden geçirmek gibi çabalar dahil. - -Veriler ayda bir hesaplanır, kaynak kodu buradan okuyabilirsin. - -Burada sponsorların katkılarını da vurguluyorum. - -Ayrıca algoritmayı, bölümleri, eşikleri vb. güncelleme hakkımı da saklı tutuyorum (her ihtimale karşı 🤷). diff --git a/docs/tr/docs/features.md b/docs/tr/docs/features.md index 1cda8c7fb..5d40b1086 100644 --- a/docs/tr/docs/features.md +++ b/docs/tr/docs/features.md @@ -67,10 +67,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` şu anlama geliyor: +/// info - Key-Value çiftini direkt olarak `second_user_data` dictionarysine kaydet , yaptığın şey buna eşit olacak: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` şu anlama geliyor: + +Key-Value çiftini direkt olarak `second_user_data` dictionarysine kaydet , yaptığın şey buna eşit olacak: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Editor desteği diff --git a/docs/tr/docs/help/index.md b/docs/tr/docs/help/index.md deleted file mode 100644 index cef0914ce..000000000 --- a/docs/tr/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Yardım - -Yardım alın, yardım edin, katkıda bulunun, dahil olun. 🤝 diff --git a/docs/tr/docs/history-design-future.md b/docs/tr/docs/history-design-future.md index 1dd0e637f..8b2662bc3 100644 --- a/docs/tr/docs/history-design-future.md +++ b/docs/tr/docs/history-design-future.md @@ -1,6 +1,6 @@ # Geçmişi, Tasarımı ve Geleceği -Bir süre önce, bir **FastAPI** kullanıcısı sordu: +Bir süre önce, bir **FastAPI** kullanıcısı sordu: > Bu projenin geçmişi nedir? Birkaç hafta içinde hiçbir yerden harika bir şeye dönüşmüş gibi görünüyor [...] diff --git a/docs/tr/docs/how-to/general.md b/docs/tr/docs/how-to/general.md new file mode 100644 index 000000000..cbfa7beb2 --- /dev/null +++ b/docs/tr/docs/how-to/general.md @@ -0,0 +1,39 @@ +# Genel - Nasıl Yapılır - Tarifler + +Bu sayfada genel ve sıkça sorulan sorular için dokümantasyonun diğer sayfalarına yönlendirmeler bulunmaktadır. + +## Veri Filtreleme - Güvenlik + +Döndürmeniz gereken veriden fazlasını döndürmediğinizden emin olmak için, [Tutorial - Response Model - Return Type](../tutorial/response-model.md){.internal-link target=_blank} sayfasını okuyun. + +## Dokümantasyon Etiketleri - OpenAPI + +*Yol operasyonlarınıza* etiketler ekleyerek dokümantasyon arayüzünde gruplar halinde görünmesini sağlamak için, [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank} sayfasını okuyun. + +## Dokümantasyon Özeti ve Açıklaması - OpenAPI + +*Yol operasyonlarınıza* özet ve açıklama ekleyip dokümantasyon arayüzünde görünmesini sağlamak için, [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank} sayfasını okuyun. + +## Yanıt Açıklaması Dokümantasyonu - OpenAPI + +Dokümantasyon arayüzünde yer alan yanıt açıklamasını tanımlamak için, [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank} sayfasını okuyun. + +## *Yol Operasyonunu* Kullanımdan Kaldırma - OpenAPI + +Bir *yol işlemi*ni kullanımdan kaldırmak ve bunu dokümantasyon arayüzünde göstermek için, [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank} sayfasını okuyun. + +## Herhangi Bir Veriyi JSON Uyumlu Hale Getirme + +Herhangi bir veriyi JSON uyumlu hale getirmek için, [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Meta Verileri - Dokümantasyon + +OpenAPI şemanıza lisans, sürüm, iletişim vb. meta veriler eklemek için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Bağlantı Özelleştirme + +OpenAPI bağlantısını özelleştirmek (veya kaldırmak) için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Dokümantasyon Bağlantıları + +Dokümantasyonu arayüzünde kullanılan bağlantıları güncellemek için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls){.internal-link target=_blank} sayfasını okuyun. diff --git a/docs/tr/docs/how-to/index.md b/docs/tr/docs/how-to/index.md index 8ece29515..26dd9026c 100644 --- a/docs/tr/docs/how-to/index.md +++ b/docs/tr/docs/how-to/index.md @@ -6,6 +6,8 @@ Bu fikirlerin büyük bir kısmı aşağı yukarı **bağımsız** olacaktır, Projeniz için ilginç ve yararlı görünen bir şey varsa devam edin ve inceleyin, aksi halde bunları atlayabilirsiniz. -!!! tip "İpucu" +/// tip | İpucu - **FastAPI**'ı düzgün (ve önerilen) şekilde öğrenmek istiyorsanız [Öğretici - Kullanıcı Rehberi](../tutorial/index.md){.internal-link target=_blank}'ni bölüm bölüm okuyun. +**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 afbb27f7d..7ecaf1ba3 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ FastAPI framework, yüksek performanslı, öğrenmesi oldukça kolay, kodlaması hızlı, kullanıma hazır

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +29,11 @@ **Dokümantasyon**: https://fastapi.tiangolo.com -**Kaynak Kod**: https://github.com/tiangolo/fastapi +**Kaynak Kod**: https://github.com/fastapi/fastapi --- -FastAPI, Python 3.8+'nin standart tip belirteçlerine dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür. +FastAPI, Python 'nin standart tip belirteçlerine dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür. Temel özellikleri şunlardır: @@ -63,7 +69,7 @@ Temel özellikleri şunlardır: "_[...] Bugünlerde **FastAPI**'ı çok fazla kullanıyorum. [...] Aslında bunu ekibimin **Microsoft'taki Machine Learning servislerinin** tamamında kullanmayı planlıyorum. Bunlardan bazıları **Windows**'un ana ürünlerine ve **Office** ürünlerine entegre ediliyor._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -115,8 +121,6 @@ Eğer API yerine, terminalde kullanılmak üzere bir Starlette. @@ -134,7 +138,7 @@ $ pip install fastapi -Uygulamamızı kullanılabilir hale getirmek için Uvicorn ya da Hypercorn gibi bir ASGI sunucusuna ihtiyacımız olacak. +Uygulamamızı kullanılabilir hale getirmek için Uvicorn ya da Hypercorn gibi bir ASGI sunucusuna ihtiyacımız olacak.
@@ -331,7 +335,7 @@ Bu işlemi standart modern Python tipleriyle yapıyoruz. Yeni bir sözdizimi yapısını, bir kütüphane özel metod veya sınıfları öğrenmeye gerek yoktur. -Hepsi sadece **Python 3.8+** standartlarına dayalıdır. +Hepsi sadece **Python** standartlarına dayalıdır. Örnek olarak, `int` tanımlamak için: @@ -445,7 +449,7 @@ Daha fazla bilgi için, bu bölüme bir göz at email_validator - email doğrulaması için. +* email-validator - email doğrulaması için. * pydantic-settings - ayar yönetimi için. * pydantic-extra-types - Pydantic ile birlikte kullanılabilecek ek tipler için. @@ -456,12 +460,12 @@ Starlette tarafında kullanılan: * python-multipart - Eğer `request.form()` ile form dönüşümü desteğini kullanacaksanız gereklidir. * itsdangerous - `SessionMiddleware` desteği için gerekli. * pyyaml - `SchemaGenerator` desteği için gerekli (Muhtemelen FastAPI kullanırken ihtiyacınız olmaz). -* ujson - `UJSONResponse` kullanacaksanız gerekli. Hem FastAPI hem de Starlette tarafından kullanılan: * uvicorn - oluşturduğumuz uygulamayı servis edecek web sunucusu görevini üstlenir. * orjson - `ORJSONResponse` kullanacaksanız gereklidir. +* ujson - `UJSONResponse` kullanacaksanız gerekli. Bunların hepsini `pip install fastapi[all]` ile yükleyebilirsin. diff --git a/docs/tr/docs/newsletter.md b/docs/tr/docs/newsletter.md deleted file mode 100644 index 22ca1b1e2..000000000 --- a/docs/tr/docs/newsletter.md +++ /dev/null @@ -1,5 +0,0 @@ -# FastAPI ve Arkadaşları Bülteni - - - - diff --git a/docs/tr/docs/project-generation.md b/docs/tr/docs/project-generation.md index 75e3ae339..c9dc24acc 100644 --- a/docs/tr/docs/project-generation.md +++ b/docs/tr/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: **FastAPI** backend: +* Python **FastAPI** backend: * **Hızlı**: **NodeJS** ve **Go** ile eşit, çok yüksek performans (Starlette ve Pydantic'e teşekkürler). * **Sezgisel**: Editor desteğı. Otomatik tamamlama. Daha az debugging. * **Kolay**: Kolay öğrenip kolay kullanmak için tasarlandı. Daha az döküman okuma daha çok iş. diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index a0d32c86e..308dfa6fb 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -12,15 +12,18 @@ Bu pythonda tip belirteçleri için **hızlı bir başlangıç / bilgi tazeleme **FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var. -!!! not - Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. +/// note | Not + +Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. + +/// ## Motivasyon Basit bir örnek ile başlayalım: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Programın çıktısı: @@ -36,7 +39,7 @@ Fonksiyon sırayla şunları yapar: * Değişkenleri aralarında bir boşlukla beraber Birleştirir. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Düzenle @@ -80,7 +83,7 @@ Bu kadar. İşte bunlar "tip belirteçleri": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir: @@ -110,7 +113,7 @@ Aradığınızı bulana kadar seçenekleri kaydırabilirsiniz: Bu fonksiyon, zaten tür belirteçlerine sahip: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar: @@ -120,7 +123,7 @@ Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama de Artık `age` değişkenini `str(age)` olarak kullanmanız gerektiğini biliyorsunuz: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Tip bildirme @@ -141,7 +144,7 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz. * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Tip parametreleri ile Generic tipler @@ -159,7 +162,7 @@ Bu tür tip belirteçlerini desteklemek için özel olarak mevcuttur. From `typing`, import `List` (büyük harf olan `L` ile): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin. @@ -169,13 +172,16 @@ tip olarak `List` kullanın. Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli parantez içine alırsınız: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` -!!! ipucu - Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. +/// tip | Ipucu + +Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. + +Bu durumda `str`, `List`e iletilen tür parametresidir. - Bu durumda `str`, `List`e iletilen tür parametresidir. +/// Bunun anlamı şudur: "`items` değişkeni bir `list`tir ve bu listedeki öğelerin her biri bir `str`dir". @@ -194,7 +200,7 @@ Ve yine, editör bunun bir `str` ​​olduğunu biliyor ve bunun için destek s `Tuple` ve `set`lerin tiplerini bildirmek için de aynısını yapıyoruz: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Bu şu anlama geliyor: @@ -211,7 +217,7 @@ Bir `dict` tanımlamak için virgülle ayrılmış iki parametre verebilirsiniz. İkinci parametre ise `dict` değerinin `value` değeri içindir: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Bu şu anlama gelir: @@ -225,7 +231,7 @@ Bu şu anlama gelir: `Optional` bir değişkenin `str`gibi bir tipi olabileceğini ama isteğe bağlı olarak tipinin `None` olabileceğini belirtir: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` `str` yerine `Optional[str]` kullanmak editorün bu değerin her zaman `str` tipinde değil bazen `None` tipinde de olabileceğini belirtir ve hataları tespit etmemizde yardımcı olur. @@ -250,13 +256,13 @@ Bir değişkenin tipini bir sınıf ile bildirebilirsiniz. Diyelim ki `name` değerine sahip `Person` sınıfınız var: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Sonra bir değişkeni 'Person' tipinde tanımlayabilirsiniz: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Ve yine bütün editör desteğini alırsınız: @@ -278,11 +284,14 @@ Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız. Resmi Pydantic dokümanlarından alınmıştır: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` -!!! info - Daha fazla şey öğrenmek için Pydantic'i takip edin. +/// info + +Daha fazla şey öğrenmek için Pydantic'i takip edin. + +/// **FastAPI** tamamen Pydantic'e dayanmaktadır. @@ -310,5 +319,8 @@ Bütün bunlar kulağa soyut gelebilir. Merak etme. Tüm bunları çalışırken Önemli olan, standart Python türlerini tek bir yerde kullanarak (daha fazla sınıf, dekoratör vb. eklemek yerine), **FastAPI**'nin bizim için işi yapmasını sağlamak. -!!! info - Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`. +/// info + +Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`. + +/// diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..56bcc0c86 --- /dev/null +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -0,0 +1,135 @@ +# Çerez (Cookie) Parametreleri + +`Query` (Sorgu) ve `Path` (Yol) parametrelerini tanımladığınız şekilde çerez parametreleri tanımlayabilirsiniz. + +## Import `Cookie` + +Öncelikle, `Cookie`'yi projenize dahil edin: + +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | İpucu + +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + +/// + +```Python hl_lines="1" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | İpucu + +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + +/// + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +## `Cookie` Parametrelerini Tanımlayın + +Çerez parametrelerini `Path` veya `Query` tanımlaması yapar gibi tanımlayın. + +İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz: + +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | İpucu + +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | İpucu + +Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +/// note | Teknik Detaylar + +`Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır. + +Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur. + +/// + +/// info | Bilgi + +Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır. + +/// + +## Özet + +Çerez tanımlamalarını `Cookie` sınıfını kullanarak `Query` ve `Path` tanımlar gibi tanımlayın. diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md index e66f73034..da9057204 100644 --- a/docs/tr/docs/tutorial/first-steps.md +++ b/docs/tr/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ En sade FastAPI dosyası şu şekilde görünür: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım. @@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note "Not" - `uvicorn main:app` komutunu şu şekilde açıklayabiliriz: +/// note | Not - * `main`: dosya olan `main.py` (yani Python "modülü"). - * `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. - * `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız. +`uvicorn main:app` komutunu şu şekilde açıklayabiliriz: + +* `main`: dosya olan `main.py` (yani Python "modülü"). +* `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. +* `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız. + +/// Çıktı olarak şöyle bir satır ile karşılaşacaksınız: @@ -131,20 +134,23 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi ### Adım 1: `FastAPI`yı Projemize Dahil Edelim ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır. -!!! note "Teknik Detaylar" - `FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır. +/// note | Teknik Detaylar + +`FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır. - Starlette'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz. +Starlette'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz. + +/// ### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır. @@ -166,7 +172,7 @@ $ uvicorn main:app --reload Uygulamanızı aşağıdaki gibi oluşturursanız: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` Ve bunu `main.py` dosyasına yerleştirirseniz eğer `uvicorn` komutunu şu şekilde çalıştırabilirsiniz: @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Bilgi" - "Yol" genellikle "endpoint" veya "route" olarak adlandırılır. +/// info | Bilgi + +"Yol" genellikle "endpoint" veya "route" olarak adlandırılır. + +/// Bir API oluştururken, "yol", "kaynaklar" ile "endişeleri" ayırmanın ana yöntemidir. @@ -242,7 +251,7 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız. #### Bir *Yol Operasyonu Dekoratörü* Tanımlayalım ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")` dekoratörü, **FastAPI**'a hemen altındaki fonksiyonun aşağıdaki durumlardan sorumlu olduğunu söyler: @@ -250,16 +259,19 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız. * get operasyonu ile * `/` yoluna gelen istekler -!!! info "`@decorator` Bilgisi" - Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır. +/// info | `@decorator` Bilgisi - Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler. +Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır. - Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir. +Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler. - Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler. +Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir. - Bu bir **yol operasyonu dekoratörüdür**. +Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler. + +Bu bir **yol operasyonu dekoratörüdür**. + +/// Ayrıca diğer operasyonları da kullanabilirsiniz: @@ -274,14 +286,17 @@ Daha az kullanılanları da kullanabilirsiniz: * `@app.patch()` * `@app.trace()` -!!! tip "İpucu" - Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz. +/// tip | İpucu + +Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz. - **FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz. +**FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz. - Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır. +Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır. - Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz. +Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz. + +/// ### Adım 4: **Yol Operasyonu Fonksiyonunu** Tanımlayın @@ -292,7 +307,7 @@ Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**: * **fonksiyon**: "dekoratör"ün (`@app.get("/")`'in) altındaki fonksiyondur. ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Bu bir Python fonksiyonudur. @@ -306,16 +321,19 @@ Bu durumda bu fonksiyon bir `async` fonksiyondur. Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirsiniz. ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` -!!! note "Not" - Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz. +/// note | Not + +Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz. + +/// ### Adım 5: İçeriği Geri Döndürün ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz. diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md index c19023645..c883c2f9f 100644 --- a/docs/tr/docs/tutorial/path-params.md +++ b/docs/tr/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Yol "parametrelerini" veya "değişkenlerini" Python string biçimlemede kullanılan sözdizimi ile tanımlayabilirsiniz. ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` Yol parametresi olan `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır. @@ -19,13 +19,16 @@ Eğer bu örneği çalıştırıp Dönüşümü
@@ -35,10 +38,13 @@ Eğer bu örneği çalıştırıp tarayıcınızda "ayrıştırma"
özelliği sağlar. - Bu tanımlamayla birlikte, **FastAPI** size otomatik istek "ayrıştırma" özelliği sağlar. +/// ## Veri Doğrulama @@ -65,12 +71,15 @@ Eğer tarayıcınızda http://127.0.0.1:8000/items/4.2 sayfasında olduğu gibi `int` yerine `float` bir değer verseydik de ortaya çıkardı. -!!! check "Ek bilgi" - Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar. +/// check | Ek bilgi - Dikkatinizi çekerim ki, karşılaştığınız hata, doğrulamanın geçersiz olduğu mutlak noktayı da açık bir şekilde belirtiyor. +Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar. - Bu özellik, API'ınızla iletişime geçen kodu geliştirirken ve ayıklarken inanılmaz derecede yararlı olacaktır. +Dikkatinizi çekerim ki, karşılaştığınız hata, doğrulamanın geçersiz olduğu mutlak noktayı da açık bir şekilde belirtiyor. + +Bu özellik, API'ınızla iletişime geçen kodu geliştirirken ve ayıklarken inanılmaz derecede yararlı olacaktır. + +/// ## Dokümantasyon @@ -78,10 +87,13 @@ Ayrıca, tarayıcınızı -!!! check "Ek bilgi" - Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar. +/// check | Ek bilgi + +Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar. + +Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır. - Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır. +/// ## Standartlara Dayalı Avantajlar, Alternatif Dokümantasyon @@ -112,7 +124,7 @@ Benzer şekilde `/users/{user_id}` gibi tanımlanmış ve belirli bir kullanıc *Yol operasyonları* sıralı bir şekilde gözden geçirildiğinden dolayı `/users/me` yolunun `/users/{user_id}` yolundan önce tanımlanmış olmasından emin olmanız gerekmektedir: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` Aksi halde, `/users/{user_id}` yolu `"me"` değerinin `user_id` parametresi için gönderildiğini "düşünerek" `/users/me` ile de eşleşir. @@ -120,7 +132,7 @@ Aksi halde, `/users/{user_id}` yolu `"me"` değerinin `user_id` parametresi içi Benzer şekilde, bir yol operasyonunu yeniden tanımlamanız mümkün değildir: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003b.py!} +{!../../docs_src/path_params/tutorial003b.py!} ``` Yol, ilk kısım ile eşleştiğinden dolayı her koşulda ilk yol operasyonu kullanılacaktır. @@ -138,21 +150,27 @@ Eğer *yol parametresi* alan bir *yol operasyonunuz* varsa ve alabileceği *yol Sonrasında, sınıf içerisinde, mevcut ve geçerli değerler olacak olan sabit değerli özelliklerini oluşturalım: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! info "Bilgi" - 3.4 sürümünden beri enumerationlar (ya da enumlar) Python'da mevcuttur. +/// info | Bilgi -!!! tip "İpucu" - Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi modellerini temsil eder. +3.4 sürümünden beri enumerationlar (ya da enumlar) Python'da mevcuttur. + +/// + +/// tip | İpucu + +Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi modellerini temsil eder. + +/// ### Bir *Yol Parametresi* Tanımlayalım Sonrasında, yarattığımız enum sınıfını (`ModelName`) kullanarak tip belirteci aracılığıyla bir *yol parametresi* oluşturalım: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### Dokümana Göz Atalım @@ -170,7 +188,7 @@ Sonrasında, yarattığımız enum sınıfını (`ModelName`) kullanarak tip bel Parametreyi, yarattığınız enum olan `ModelName` içerisindeki *enumeration üyesi* ile karşılaştırabilirsiniz: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### *Enumeration Değerini* Edinelim @@ -178,11 +196,14 @@ Parametreyi, yarattığınız enum olan `ModelName` içerisindeki *enumeration `model_name.value` veya genel olarak `your_enum_member.value` tanımlarını kullanarak (bu durumda bir `str` olan) gerçek değere ulaşabilirsiniz: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! tip "İpucu" - `"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz. +/// tip | İpucu + +`"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz. + +/// #### *Enumeration Üyelerini* Döndürelim @@ -191,7 +212,7 @@ JSON gövdesine (örneğin bir `dict`) gömülü olsalar bile *yol operasyonunda Bu üyeler istemciye iletilmeden önce kendilerine karşılık gelen değerlerine (bu durumda string) dönüştürüleceklerdir: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` İstemci tarafında şuna benzer bir JSON yanıtı ile karşılaşırsınız: @@ -232,13 +253,16 @@ Bu durumda, parametrenin adı `file_path` olacaktır ve son kısım olan `:path` Böylece şunun gibi bir kullanım yapabilirsiniz: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` -!!! tip "İpucu" - Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir. +/// tip | İpucu + +Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir. + +Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir. - Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir. +/// ## Özet diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md index aa3915557..b31d13be4 100644 --- a/docs/tr/docs/tutorial/query-params.md +++ b/docs/tr/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Fonksiyonda yol parametrelerinin parçası olmayan diğer tanımlamalar otomatik olarak "sorgu" parametresi olarak yorumlanır. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` Sorgu, bağlantıdaki `?` kısmından sonra gelen ve `&` işareti ile ayrılan anahtar-değer çiftlerinin oluşturduğu bir kümedir. @@ -63,38 +63,49 @@ Fonksiyonunuzdaki parametre değerleri aşağıdaki gibi olacaktır: Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı parametreler tanımlayabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../docs_src/query_params/tutorial002.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +//// Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır. -!!! check "Ek bilgi" - Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. +/// check | Ek bilgi + +Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. + +/// ## Sorgu Parametresi Tip Dönüşümü Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanımlayabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../docs_src/query_params/tutorial003_py310.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +//// Bu durumda, eğer şu adrese giderseniz: @@ -137,17 +148,21 @@ Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. İsimlerine göre belirleneceklerdir: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6 8" +{!> ../../docs_src/query_params/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="8 10" +{!> ../../docs_src/query_params/tutorial004.py!} +``` - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +//// ## Zorunlu Sorgu Parametreleri @@ -158,7 +173,7 @@ Parametre için belirli bir değer atamak istemeyip parametrenin sadece isteğe Fakat, bir sorgu parametresini zorunlu yapmak istiyorsanız varsayılan bir değer atamamanız yeterli olacaktır: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Burada `needy` parametresi `str` tipinden oluşan zorunlu bir sorgu parametresidir. @@ -205,17 +220,21 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve bazılarını tamamen opsiyonel olarak tanımlayabilirsiniz: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +```Python hl_lines="8" +{!> ../../docs_src/query_params/tutorial006_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/query_params/tutorial006.py!} +``` + +//// Bu durumda, 3 tane sorgu parametresi var olacaktır: @@ -223,5 +242,8 @@ Bu durumda, 3 tane sorgu parametresi var olacaktır: * `skip`, varsayılan değeri `0` olan bir `int`. * `limit`, isteğe bağlı bir `int`. -!!! tip "İpucu" - Ayrıca, [Yol Parametrelerinde](path-params.md#predefined-values){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. +/// tip | İpucu + +Ayrıca, [Yol Parametrelerinde](path-params.md#on-tanml-degerler){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. + +/// diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md new file mode 100644 index 000000000..4ed8ac021 --- /dev/null +++ b/docs/tr/docs/tutorial/request-forms.md @@ -0,0 +1,125 @@ +# Form Verisi + +İstek gövdesinde JSON verisi yerine form alanlarını karşılamanız gerketiğinde `Form` sınıfını kullanabilirsiniz. + +/// info | Bilgi + +Formları kullanmak için öncelikle `python-multipart` paketini indirmeniz gerekmektedir. + +Örneğin `pip install python-multipart`. + +/// + +## `Form` Sınıfını Projenize Dahil Edin + +`Form` sınıfını `fastapi`'den projenize dahil edin: + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1" +{!> ../../docs_src/request_forms/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="1" +{!> ../../docs_src/request_forms/tutorial001.py!} +``` + +//// + +## `Form` Parametrelerini Tanımlayın + +Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../docs_src/request_forms/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/request_forms/tutorial001.py!} +``` + +//// + +Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak "username" ve "password" gönderilmesi gerekir. + +Bu spesifikasyon form alanlarını adlandırırken isimlerinin birebir `username` ve `password` olmasını ve JSON verisi yerine form verisi olarak gönderilmesini gerektirir. + +`Form` sınıfıyla tanımlama yaparken `Body`, `Query`, `Path` ve `Cookie` sınıflarında kullandığınız aynı validasyon, örnekler, isimlendirme (örneğin `username` yerine `user-name` kullanımı) ve daha fazla konfigurasyonu kullanabilirsiniz. + +/// info | Bilgi + +`Form` doğrudan `Body` sınıfını miras alan bir sınıftır. + +/// + +/// tip | İpucu + +Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır. + +/// + +## "Form Alanları" Hakkında + +HTML formlarının (`
`) verileri sunucuya gönderirken JSON'dan farklı özel bir kodlama kullanır. + +**FastAPI** bu verilerin JSON yerine doğru şekilde okunmasını sağlayacaktır. + +/// note | Teknik Detaylar + +Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır. + +Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz. + +Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız MDN web docs for POST sayfasını ziyaret edebilirsiniz. + +/// + +/// warning | Uyarı + +*Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur. + +Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır. + +/// + +## Özet + +Form verisi girdi parametreleri tanımlamak için `Form` sınıfını kullanın. diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md new file mode 100644 index 000000000..da8bed86a --- /dev/null +++ b/docs/tr/docs/tutorial/static-files.md @@ -0,0 +1,42 @@ +# Statik Dosyalar + +`StaticFiles`'ı kullanarak statik dosyaları bir yol altında sunabilirsiniz. + +## `StaticFiles` Kullanımı + +* `StaticFiles` sınıfını projenize dahil edin. +* Bir `StaticFiles()` örneğini belirli bir yola bağlayın. + +```Python hl_lines="2 6" +{!../../docs_src/static_files/tutorial001.py!} +``` + +/// note | Teknik Detaylar + +Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz. + +**FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir. + +/// + +### Bağlama (Mounting) Nedir? + +"Bağlamak", belirli bir yola tamamen "bağımsız" bir uygulama eklemek anlamına gelir ve ardından tüm alt yollara gelen istekler bu uygulama tarafından işlenir. + +Bu, bir `APIRouter` kullanmaktan farklıdır çünkü bağlanmış bir uygulama tamamen bağımsızdır. Ana uygulamanızın OpenAPI ve dokümanlar, bağlanmış uygulamadan hiçbir şey içermez, vb. + +[Advanced User Guide](../advanced/index.md){.internal-link target=_blank} bölümünde daha fazla bilgi edinebilirsiniz. + +## Detaylar + +`"/static"` ifadesi, bu "alt uygulamanın" "bağlanacağı" alt yolu belirtir. Bu nedenle, `"/static"` ile başlayan her yol, bu uygulama tarafından işlenir. + +`directory="static"` ifadesi, statik dosyalarınızı içeren dizinin adını belirtir. + +`name="static"` ifadesi, alt uygulamanın **FastAPI** tarafından kullanılacak ismini belirtir. + +Bu parametrelerin hepsi "`static`"den farklı olabilir, bunları kendi uygulamanızın ihtiyaçlarına göre belirleyebilirsiniz. + +## Daha Fazla Bilgi + +Daha fazla detay ve seçenek için Starlette'in Statik Dosyalar hakkındaki dokümantasyonunu incelleyin. diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md index bdb62513e..1acbe237a 100644 --- a/docs/uk/docs/alternatives.md +++ b/docs/uk/docs/alternatives.md @@ -30,12 +30,17 @@ Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**. -!!! Примітка - Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. +/// note | Примітка +Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. -!!! Перегляньте "Надихнуло **FastAPI** на" - Мати автоматичний веб-інтерфейс документації API. +/// + +/// check | Надихнуло **FastAPI** на + +Мати автоматичний веб-інтерфейс документації API. + +/// ### Flask @@ -51,11 +56,13 @@ Flask — це «мікрофреймворк», він не включає ін Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask. -!!! Переглянте "Надихнуло **FastAPI** на" - Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. +/// check | Надихнуло **FastAPI** на - Мати просту та легку у використанні систему маршрутизації. +Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. + Мати просту та легку у використанні систему маршрутизації. + +/// ### Requests @@ -91,11 +98,13 @@ def read_url(): Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`. -!!! Перегляньте "Надихнуло **FastAPI** на" - * Майте простий та інтуїтивно зрозумілий API. - * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. - * Розумні параметри за замовчуванням, але потужні налаштування. +/// check | Надихнуло **FastAPI** на + +* Майте простий та інтуїтивно зрозумілий API. + * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. + * Розумні параметри за замовчуванням, але потужні налаштування. +/// ### Swagger / OpenAPI @@ -109,15 +118,18 @@ def read_url(): Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI». -!!! Перегляньте "Надихнуло **FastAPI** на" - Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. +/// check | Надихнуло **FastAPI** на + +Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. - Інтегрувати інструменти інтерфейсу на основі стандартів: + Інтегрувати інструменти інтерфейсу на основі стандартів: - * Інтерфейс Swagger - * ReDoc + * Інтерфейс Swagger + * ReDoc - Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**). + Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**). + +/// ### Фреймворки REST для Flask @@ -135,8 +147,11 @@ Marshmallow створено для забезпечення цих функці Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow. -!!! Перегляньте "Надихнуло **FastAPI** на" - Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. +/// check | Надихнуло **FastAPI** на + +Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. + +/// ### Webargs @@ -148,11 +163,17 @@ Webargs — це інструмент, створений, щоб забезпе Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**. -!!! Інформація - Webargs був створений тими ж розробниками Marshmallow. +/// info | Інформація + +Webargs був створений тими ж розробниками Marshmallow. + +/// + +/// check | Надихнуло **FastAPI** на -!!! Перегляньте "Надихнуло **FastAPI** на" - Мати автоматичну перевірку даних вхідного запиту. +Мати автоматичну перевірку даних вхідного запиту. + +/// ### APISpec @@ -172,12 +193,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою. -!!! Інформація - APISpec був створений тими ж розробниками Marshmallow. +/// info | Інформація + +APISpec був створений тими ж розробниками Marshmallow. + +/// +/// check | Надихнуло **FastAPI** на -!!! Перегляньте "Надихнуло **FastAPI** на" - Підтримувати відкритий стандарт API, OpenAPI. +Підтримувати відкритий стандарт API, OpenAPI. + +/// ### Flask-apispec @@ -199,11 +225,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}. -!!! Інформація - Flask-apispec був створений тими ж розробниками Marshmallow. +/// info | Інформація + +Flask-apispec був створений тими ж розробниками Marshmallow. + +/// -!!! Перегляньте "Надихнуло **FastAPI** на" - Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. +/// check | Надихнуло **FastAPI** на + +Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. + +/// ### NestJS (та Angular) @@ -219,24 +251,33 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити. -!!! Перегляньте "Надихнуло **FastAPI** на" - Використовувати типи Python, щоб мати чудову підтримку редактора. +/// check | Надихнуло **FastAPI** на + +Використовувати типи Python, щоб мати чудову підтримку редактора. - Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду. + Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду. + +/// ### Sanic Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask. -!!! Примітка "Технічні деталі" - Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. +/// note | Технічні деталі + +Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. - Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах. + Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах. -!!! Перегляньте "Надихнуло **FastAPI** на" - Знайти спосіб отримати божевільну продуктивність. +/// - Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників). +/// check | Надихнуло **FastAPI** на + +Знайти спосіб отримати божевільну продуктивність. + + Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників). + +/// ### Falcon @@ -246,12 +287,15 @@ Falcon — ще один високопродуктивний фреймворк Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри. -!!! Перегляньте "Надихнуло **FastAPI** на" - Знайти способи отримати чудову продуктивність. +/// check | Надихнуло **FastAPI** на - Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях. +Знайти способи отримати чудову продуктивність. - Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану. + Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях. + + Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану. + +/// ### Molten @@ -269,12 +313,15 @@ Falcon — ще один високопродуктивний фреймворк Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані. -!!! Перегляньте "Надихнуло **FastAPI** на" - Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. +/// check | Надихнуло **FastAPI** на + +Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. - Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic). + Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic). -### Hug +/// + +### Hug Hug був одним із перших фреймворків, який реалізував оголошення типів параметрів API за допомогою підказок типу Python. Це була чудова ідея, яка надихнула інші інструменти зробити те саме. @@ -288,15 +335,21 @@ Hug був одним із перших фреймворків, який реа Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність. -!!! Інформація - Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python. +/// info | Інформація + +Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python. + +/// -!!! Перегляньте "Надихнуло **FastAPI** на" - Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. +/// check | Надихнуло **FastAPI** на - Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API. +Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. - Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie. + Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API. + + Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie. + +/// ### APIStar (<= 0,5) @@ -322,21 +375,27 @@ Hug був одним із перших фреймворків, який реа Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк. -!!! Інформація - APIStar створив Том Крісті. Той самий хлопець, який створив: +/// info | Інформація + +APIStar створив Том Крісті. Той самий хлопець, який створив: - * Django REST Framework - * Starlette (на якому базується **FastAPI**) - * Uvicorn (використовується Starlette і **FastAPI**) + * Django REST Framework + * Starlette (на якому базується **FastAPI**) + * Uvicorn (використовується Starlette і **FastAPI**) -!!! Перегляньте "Надихнуло **FastAPI** на" - Існувати. +/// - Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю. +/// check | Надихнуло **FastAPI** на - І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом. +Існувати. - Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів. + Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю. + + І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом. + + Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів. + +/// ## Використовується **FastAPI** @@ -348,10 +407,13 @@ Pydantic — це бібліотека для визначення переві Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова. -!!! Перегляньте "**FastAPI** використовує його для" - Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). +/// check | **FastAPI** використовує його для - Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить. +Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). + + Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить. + +/// ### Starlette @@ -380,17 +442,23 @@ Starlette надає всі основні функції веб-мікрофр Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо. -!!! Примітка "Технічні деталі" - ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. +/// note | Технічні деталі + +ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. - Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`. + Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`. -!!! Перегляньте "**FastAPI** використовує його для" - Керування всіма основними веб-частинами. Додавання функцій зверху. +/// - Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`. +/// check | **FastAPI** використовує його для - Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах. +Керування всіма основними веб-частинами. Додавання функцій зверху. + + Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`. + + Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах. + +/// ### Uvicorn @@ -400,12 +468,15 @@ Uvicorn — це блискавичний сервер ASGI, побудован Це рекомендований сервер для Starlette і **FastAPI**. -!!! Перегляньте "**FastAPI** рекомендує це як" - Основний веб-сервер для запуску програм **FastAPI**. +/// check | **FastAPI** рекомендує це як + +Основний веб-сервер для запуску програм **FastAPI**. + + Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер. - Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер. + Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}. - Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}. +/// ## Орієнтири та швидкість diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md deleted file mode 100644 index f7d0220b5..000000000 --- a/docs/uk/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# Люди FastAPI - -FastAPI має дивовижну спільноту, яка вітає людей різного походження. - -## Творець – Супроводжувач - -Привіт! 👋 - -Це я: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Я - творець і супроводжувач **FastAPI**. Детальніше про це можна прочитати в [Довідка FastAPI - Отримати довідку - Зв'язатися з автором](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Але тут я хочу показати вам спільноту. - ---- - -**FastAPI** отримує велику підтримку від спільноти. І я хочу відзначити їхній внесок. - -Це люди, які: - -* [Допомагають іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Створюють пул реквести](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Переглядають пул реквести, [особливо важливо для перекладів](contributing.md#translations){.internal-link target=_blank}. - -Оплески їм. 👏 🙇 - -## Найбільш активні користувачі минулого місяця - -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} протягом минулого місяця. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Експерти - -Ось **експерти FastAPI**. 🤓 - -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} протягом *всього часу*. - -Вони зарекомендували себе як експерти, допомагаючи багатьом іншим. ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Найкращі контрибютори - -Ось **Найкращі контрибютори**. 👷 - -Ці користувачі [створили найбільшу кількість пул реквестів](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} які були *змержені*. - -Вони надали програмний код, документацію, переклади тощо. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Є багато інших контрибюторів (більше сотні), їх усіх можна побачити на сторінці FastAPI GitHub Contributors. 👷 - -## Найкращі рецензенти - -Ці користувачі є **Найкращими рецензентами**. 🕵️ - -### Рецензенти на переклади - -Я розмовляю лише кількома мовами (і не дуже добре 😅). Отже, рецензенти – це ті, хто має [**повноваження схвалювати переклади**](contributing.md#translations){.internal-link target=_blank} документації. Без них не було б документації кількома іншими мовами. - ---- - -**Найкращі рецензенти** 🕵️ переглянули більшість пул реквестів від інших, забезпечуючи якість коду, документації і особливо **перекладів**. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Спонсори - -Це **Спонсори**. 😎 - -Вони підтримують мою роботу з **FastAPI** (та іншими), переважно через GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Золоті спонсори - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Срібні спонсори - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Бронзові спонсори - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Індивідуальні спонсори - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## Про дані - технічні деталі - -Основна мета цієї сторінки – висвітлити зусилля спільноти, щоб допомогти іншим. - -Особливо враховуючи зусилля, які зазвичай менш помітні, а в багатьох випадках більш важкі, як-от допомога іншим із проблемами та перегляд пул реквестів перекладів. - -Дані розраховуються щомісяця, ви можете ознайомитися з вихідним кодом тут. - -Тут я також підкреслюю внески спонсорів. - -Я також залишаю за собою право оновлювати алгоритми підрахунку, види рейтингів, порогові значення тощо (про всяк випадок 🤷). diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index 32f1f544a..012bac2e2 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -5,11 +5,11 @@ Готовий до продакшину, високопродуктивний, простий у вивченні та швидкий для написання коду фреймворк

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +23,11 @@ **Документація**: https://fastapi.tiangolo.com -**Програмний код**: https://github.com/tiangolo/fastapi +**Програмний код**: https://github.com/fastapi/fastapi --- -FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python 3.8+,в основі якого лежить стандартна анотація типів Python. +FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python,в основі якого лежить стандартна анотація типів Python. Ключові особливості: @@ -64,7 +64,7 @@ FastAPI - це сучасний, швидкий (високопродуктив "_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -88,7 +88,7 @@ FastAPI - це сучасний, швидкий (високопродуктив "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -110,8 +110,6 @@ FastAPI - це сучасний, швидкий (високопродуктив ## Вимоги -Python 3.8+ - FastAPI стоїть на плечах гігантів: * Starlette для web частини. @@ -129,7 +127,7 @@ $ pip install fastapi -Вам також знадобиться сервер ASGI для продакшину, наприклад Uvicorn або Hypercorn. +Вам також знадобиться сервер ASGI для продакшину, наприклад Uvicorn або Hypercorn.
@@ -326,7 +324,7 @@ def update_item(item_id: int, item: Item): Вам не потрібно вивчати новий синтаксис, методи чи класи конкретної бібліотеки тощо. -Використовуючи стандартний **Python 3.8+**. +Використовуючи стандартний **Python**. Наприклад, для `int`: @@ -439,7 +437,7 @@ item: Item Pydantic використовує: -* email_validator - для валідації електронної пошти. +* email-validator - для валідації електронної пошти. * pydantic-settings - для управління налаштуваннями. * pydantic-extra-types - для додаткових типів, що можуть бути використані з Pydantic. @@ -451,12 +449,12 @@ Starlette використовує: * python-multipart - Необхідно, якщо Ви хочете підтримувати "розбір" форми за допомогою `request.form()`. * itsdangerous - Необхідно для підтримки `SessionMiddleware`. * pyyaml - Необхідно для підтримки Starlette `SchemaGenerator` (ймовірно, вам це не потрібно з FastAPI). -* ujson - Необхідно, якщо Ви хочете використовувати `UJSONResponse`. FastAPI / Starlette використовують: * uvicorn - для сервера, який завантажує та обслуговує вашу програму. * orjson - Необхідно, якщо Ви хочете використовувати `ORJSONResponse`. +* ujson - Необхідно, якщо Ви хочете використовувати `UJSONResponse`. Ви можете встановити все це за допомогою `pip install fastapi[all]`. diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index e767db2fb..573b5372c 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -12,15 +12,18 @@ Python підтримує додаткові "підказки типу" ("type Але навіть якщо ви ніколи не використаєте **FastAPI**, вам буде корисно дізнатись трохи про них. -!!! note - Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу. +/// note + +Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу. + +/// ## Мотивація Давайте почнемо з простого прикладу: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Виклик цієї програми виводить: @@ -36,7 +39,7 @@ John Doe * Конкатенує їх разом із пробілом по середині. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Редагуйте це @@ -80,7 +83,7 @@ John Doe Це "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Це не те саме, що оголошення значень за замовчуванням, як це було б з: @@ -110,7 +113,7 @@ John Doe Перевірте цю функцію, вона вже має анотацію типу: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок: @@ -120,7 +123,7 @@ John Doe Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Оголошення типів @@ -141,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generic-типи з параметрами типів @@ -164,45 +167,55 @@ John Doe Наприклад, давайте визначимо змінну, яка буде `list` із `str`. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +З модуля `typing`, імпортуємо `List` (з великої літери `L`): + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). - З модуля `typing`, імпортуємо `List` (з великої літери `L`): +Як тип вкажемо `List`, який ви імпортували з `typing`. - ``` Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: - Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +//// - Як тип вкажемо `List`, який ви імпортували з `typing`. +//// tab | Python 3.9 і вище - Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: +Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Як тип вкажемо `list`. -=== "Python 3.9 і вище" +Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: - Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` - Як тип вкажемо `list`. +//// - Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: +/// info - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +Ці внутрішні типи в квадратних дужках називаються "параметрами типу". -!!! info - Ці внутрішні типи в квадратних дужках називаються "параметрами типу". +У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище). - У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище). +/// Це означає: "змінна `items` це `list`, і кожен з елементів у цьому списку - `str`". -!!! tip - Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`. +/// tip + +Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`. + +/// Зробивши це, ваш редактор може надати підтримку навіть під час обробки елементів зі списку: @@ -218,17 +231,21 @@ John Doe Ви повинні зробити те ж саме, щоб оголосити `tuple` і `set`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// -=== "Python 3.9 і вище" +//// tab | Python 3.9 і вище - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// Це означає: @@ -243,17 +260,21 @@ John Doe Другий параметр типу для значення у `dict`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// tab | Python 3.9 і вище -=== "Python 3.9 і вище" +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// Це означає: @@ -269,17 +290,21 @@ John Doe У Python 3.10 також є **альтернативний синтаксис**, у якому ви можете розділити можливі типи за допомогою вертикальної смуги (`|`). -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// tab | Python 3.10 і вище -=== "Python 3.10 і вище" +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +//// В обох випадках це означає, що `item` може бути `int` або `str`. @@ -290,7 +315,7 @@ John Doe У Python 3.6 і вище (включаючи Python 3.10) ви можете оголосити його, імпортувавши та використовуючи `Optional` з модуля `typing`. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Використання `Optional[str]` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`. @@ -299,69 +324,81 @@ John Doe Це також означає, що в Python 3.10 ви можете використовувати `Something | None`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// tab | Python 3.8 і вище - альтернатива -=== "Python 3.8 і вище - альтернатива" +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// #### Generic типи Ці типи, які приймають параметри типу у квадратних дужках, називаються **Generic types** or **Generics**, наприклад: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...та інші. + +//// - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...та інші. +//// tab | Python 3.9 і вище -=== "Python 3.9 і вище" +Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): - Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +І те саме, що й у Python 3.8, із модуля `typing`: - І те саме, що й у Python 3.8, із модуля `typing`: +* `Union` +* `Optional` +* ...та інші. - * `Union` - * `Optional` - * ...та інші. +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): +Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - І те саме, що й у Python 3.8, із модуля `typing`: +І те саме, що й у Python 3.8, із модуля `typing`: - * `Union` - * `Optional` (так само як у Python 3.8) - * ...та інші. +* `Union` +* `Optional` (так само як у Python 3.8) +* ...та інші. - У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів. +У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів. + +//// ### Класи як типи @@ -370,13 +407,13 @@ John Doe Скажімо, у вас є клас `Person` з імʼям: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Потім ви можете оголосити змінну типу `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` І знову ж таки, ви отримуєте всю підтримку редактора: @@ -397,26 +434,35 @@ John Doe Приклад з документації Pydantic: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +//// tab | Python 3.9 і вище + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +//// -=== "Python 3.9 і вище" +//// tab | Python 3.10 і вище - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` -=== "Python 3.10 і вище" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +/// info -!!! info - Щоб дізнатись більше про Pydantic, перегляньте його документацію. +Щоб дізнатись більше про Pydantic, перегляньте його документацію. + +/// **FastAPI** повністю базується на Pydantic. @@ -444,5 +490,8 @@ John Doe Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас. -!!! info - Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`. +/// info + +Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`. + +/// diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md index eee993cbe..c286744a8 100644 --- a/docs/uk/docs/tutorial/body-fields.md +++ b/docs/uk/docs/tutorial/body-fields.md @@ -6,98 +6,139 @@ Спочатку вам потрібно імпортувати це: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо. +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо. +/// tip - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +Варто користуватись `Annotated` версією, якщо це можливо. -!!! warning - Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо). +/// + +```Python hl_lines="2" +{!> ../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Варто користуватись `Annotated` версією, якщо це можливо. + +/// + +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning + +Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо). + +/// ## Оголошення атрибутів моделі Ви можете використовувати `Field` з атрибутами моделі: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +```Python hl_lines="12-15" +{!> ../../docs_src/body_fields/tutorial001_an.py!} +``` -=== "Python 3.10+ non-Annotated" +//// - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо.. +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +Варто користуватись `Annotated` версією, якщо це можливо.. - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо.. +/// - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +```Python hl_lines="9-12" +{!> ../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Варто користуватись `Annotated` версією, якщо це можливо.. + +/// + +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001.py!} +``` + +//// `Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. -!!! note "Технічні деталі" - Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. +/// note | Технічні деталі - І `Field` від Pydantic також повертає екземпляр `FieldInfo`. +Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. - `Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body. +І `Field` від Pydantic також повертає екземпляр `FieldInfo`. - Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи. +`Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body. -!!! tip - Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`. +Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи. + +/// + +/// tip + +Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`. + +/// ## Додавання додаткової інформації @@ -105,9 +146,12 @@ Ви дізнаєтеся більше про додавання додаткової інформації пізніше у документації, коли вивчатимете визначення прикладів. -!!! warning - Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка. - Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою. +/// warning + +Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка. +Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою. + +/// ## Підсумок diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md index 11e94e929..1e4188831 100644 --- a/docs/uk/docs/tutorial/body.md +++ b/docs/uk/docs/tutorial/body.md @@ -8,28 +8,35 @@ Щоб оголосити тіло **запиту**, ви використовуєте Pydantic моделі з усією їх потужністю та перевагами. -!!! info - Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`. +/// info - Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання. +Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`. - Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її. +Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання. + +Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її. + +/// ## Імпортуйте `BaseModel` від Pydantic Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="4" +{!> ../../docs_src/body/tutorial001.py!} +``` + +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.10 і вище -=== "Python 3.10 і вище" +```Python hl_lines="2" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// ## Створіть свою модель даних @@ -37,17 +44,21 @@ Використовуйте стандартні типи Python для всіх атрибутів: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="7-11" +{!> ../../docs_src/body/tutorial001.py!} +``` -=== "Python 3.10 і вище" +//// - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.10 і вище + +```Python hl_lines="5-9" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` + +//// Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим. @@ -75,17 +86,21 @@ Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +```Python hl_lines="18" +{!> ../../docs_src/body/tutorial001.py!} +``` -=== "Python 3.10 і вище" +//// - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.10 і вище + +```Python hl_lines="16" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` + +//// ...і вкажіть її тип як модель, яку ви створили, `Item`. @@ -134,32 +149,39 @@ -!!! tip - Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin. +/// tip + +Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin. - Він покращує підтримку редакторів для моделей Pydantic за допомогою: +Він покращує підтримку редакторів для моделей Pydantic за допомогою: - * автозаповнення - * перевірки типу - * рефакторингу - * пошуку - * інспекції +* автозаповнення +* перевірки типу +* рефакторингу +* пошуку +* інспекції + +/// ## Використовуйте модель Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="21" +{!> ../../docs_src/body/tutorial002.py!} +``` + +//// - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// tab | Python 3.10 і вище -=== "Python 3.10 і вище" +```Python hl_lines="19" +{!> ../../docs_src/body/tutorial002_py310.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +//// ## Тіло запиту + параметри шляху @@ -167,17 +189,21 @@ **FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="17-18" +{!> ../../docs_src/body/tutorial003.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +```Python hl_lines="15-16" +{!> ../../docs_src/body/tutorial003_py310.py!} +``` + +//// ## Тіло запиту + шлях + параметри запиту @@ -185,17 +211,21 @@ **FastAPI** розпізнає кожен з них і візьме дані з потрібного місця. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="18" +{!> ../../docs_src/body/tutorial004.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +//// -=== "Python 3.10 і вище" +//// tab | Python 3.10 і вище - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../docs_src/body/tutorial004_py310.py!} +``` + +//// Параметри функції будуть розпізнаватися наступним чином: @@ -203,10 +233,13 @@ * Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**. * Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** запиту. -!!! note - FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None". +/// note + +FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None". + +`Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки. - `Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки. +/// ## Без Pydantic diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md index 199b93839..229f81b63 100644 --- a/docs/uk/docs/tutorial/cookie-params.md +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ Спочатку імпортуйте `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// tip - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="1" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## Визначення параметрів `Cookie` @@ -48,48 +64,70 @@ Перше значення це значення за замовчуванням, ви можете також передати всі додаткові параметри валідації чи анотації: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Бажано використовувати `Annotated` версію, якщо це можливо. - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +//// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | Технічні Деталі -=== "Python 3.8+ non-Annotated" +`Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`. +Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи. - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// info -!!! note "Технічні Деталі" - `Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`. - Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи. +Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту. -!!! info - Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту. +/// ## Підсумки diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index b6583341f..77b0baf4d 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../docs_src/encoder/tutorial001.py!} +``` + +//// У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`. @@ -38,5 +42,8 @@ Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON. -!!! Примітка - `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. +/// note | Примітка + +`jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. + +/// diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md index 01852803a..5e6c364e4 100644 --- a/docs/uk/docs/tutorial/extra-data-types.md +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +```Python hl_lines="1 3 13-17" +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Бажано використовувати `Annotated` версію, якщо це можливо. + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +Бажано використовувати `Annotated` версію, якщо це можливо. - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +Бажано використовувати `Annotated` версію, якщо це можливо. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md new file mode 100644 index 000000000..63fec207d --- /dev/null +++ b/docs/uk/docs/tutorial/first-steps.md @@ -0,0 +1,342 @@ +# Перші кроки + +Найпростіший файл FastAPI може виглядати так: + +```Python +{!../../docs_src/first_steps/tutorial001.py!} +``` + +Скопіюйте це до файлу `main.py`. + +Запустіть сервер: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +У консолі буде рядок приблизно такого змісту: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Цей рядок показує URL, за яким додаток запускається на вашій локальній машині. + +### Перевірте + +Відкрийте браузер та введіть адресу http://127.0.0.1:8000. + +Ви побачите у відповідь таке повідомлення у форматі JSON: + +```JSON +{"message": "Hello World"} +``` + +### Інтерактивна API документація + +Перейдемо сюди http://127.0.0.1:8000/docs. + +Ви побачите автоматичну інтерактивну API документацію (створену завдяки Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Альтернативна API документація + +Тепер перейдемо сюди http://127.0.0.1:8000/redoc. + +Ви побачите альтернативну автоматичну документацію (створену завдяки ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI** генерує "схему" з усім вашим API, використовуючи стандарт **OpenAPI** для визначення API. + +#### "Схема" + +"Схема" - це визначення або опис чогось. Це не код, який його реалізує, а просто абстрактний опис. + +#### API "схема" + +У цьому випадку, OpenAPI є специфікацією, яка визначає, як описати схему вашого API. + +Це визначення схеми включає шляхи (paths) вашого API, можливі параметри, які вони приймають тощо. + +#### "Схема" даних + +Термін "схема" також може відноситися до структури даних, наприклад, JSON. + +У цьому випадку це означає - атрибути JSON і типи даних, які вони мають тощо. + +#### OpenAPI і JSON Schema + +OpenAPI описує схему для вашого API. І ця схема включає визначення (або "схеми") даних, що надсилаються та отримуються вашим API за допомогою **JSON Schema**, стандарту для схем даних JSON. + +#### Розглянемо `openapi.json` + +Якщо вас цікавить, як виглядає вихідна схема OpenAPI, то FastAPI автоматично генерує JSON-схему з усіма описами API. + +Ознайомитися можна за посиланням: http://127.0.0.1:8000/openapi.json. + +Ви побачите приблизно такий JSON: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### Для чого потрібний OpenAPI + +Схема OpenAPI є основою для обох систем інтерактивної документації. + +Існують десятки альтернативних інструментів, заснованих на OpenAPI. Ви можете легко додати будь-який з них до **FastAPI** додатку. + +Ви також можете використовувати OpenAPI для автоматичної генерації коду для клієнтів, які взаємодіють з API. Наприклад, для фронтенд-, мобільних або IoT-додатків + +## А тепер крок за кроком + +### Крок 1: імпортуємо `FastAPI` + +```Python hl_lines="1" +{!../../docs_src/first_steps/tutorial001.py!} +``` + +`FastAPI` це клас у Python, який надає всю функціональність для API. + +/// note | Технічні деталі + +`FastAPI` це клас, який успадковується безпосередньо від `Starlette`. + +Ви також можете використовувати всю функціональність Starlette у `FastAPI`. + +/// + +### Крок 2: створюємо екземпляр `FastAPI` + +```Python hl_lines="3" +{!../../docs_src/first_steps/tutorial001.py!} +``` +Змінна `app` є екземпляром класу `FastAPI`. + +Це буде головна точка для створення і взаємодії з API. + +### Крок 3: визначте операцію шляху (path operation) + +#### Шлях (path) + +"Шлях" це частина URL, яка йде одразу після символу `/`. + +Отже, у такому URL, як: + +``` +https://example.com/items/foo +``` + +...шлях буде: + +``` +/items/foo +``` + +/// info | Додаткова інформація + +"Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route). + +/// + +При створенні API, "шлях" є основним способом розділення "завдань" і "ресурсів". +#### Operation + +"Операція" (operation) тут означає один з "методів" HTTP. + +Один з: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +...та більш екзотичних: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +У HTTP-протоколі можна спілкуватися з кожним шляхом, використовуючи один (або кілька) з цих "методів". + +--- + +При створенні API зазвичай використовуються конкретні методи HTTP для виконання певних дій. + +Як правило, використовують: + +* `POST`: для створення даних. +* `GET`: для читання даних. +* `PUT`: для оновлення даних. +* `DELETE`: для видалення даних. + +В OpenAPI кожен HTTP метод називається "операція". + +Ми також будемо дотримуватися цього терміна. + +#### Визначте декоратор операції шляху (path operation decorator) + +```Python hl_lines="6" +{!../../docs_src/first_steps/tutorial001.py!} +``` +Декоратор `@app.get("/")` вказує **FastAPI**, що функція нижче, відповідає за обробку запитів, які надходять до неї: + +* шлях `/` +* використовуючи get операцію + +/// info | `@decorator` Додаткова інформація + +Синтаксис `@something` у Python називається "декоратором". + +Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін). + +"Декоратор" приймає функцію нижче і виконує з нею якусь дію. + +У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`. + +Це і є "декоратор операції шляху (path operation decorator)". + +/// + +Можна також використовувати операції: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +І більш екзотичні: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +/// tip | Порада + +Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд. + +**FastAPI** не нав'язує жодного певного значення для кожного методу. + +Наведена тут інформація є рекомендацією, а не обов'язковою вимогою. + +Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій. + +/// + +### Крок 4: визначте **функцію операції шляху (path operation function)** + +Ось "**функція операції шляху**": + +* **шлях**: це `/`. +* **операція**: це `get`. +* **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`). + +```Python hl_lines="7" +{!../../docs_src/first_steps/tutorial001.py!} +``` + +Це звичайна функція Python. + +FastAPI викликатиме її щоразу, коли отримає запит до URL із шляхом "/", використовуючи операцію `GET`. + +У даному випадку це асинхронна функція. + +--- + +Ви також можете визначити її як звичайну функцію замість `async def`: + +```Python hl_lines="7" +{!../../docs_src/first_steps/tutorial003.py!} +``` + +/// note | Примітка + +Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// + +### Крок 5: поверніть результат + +```Python hl_lines="8" +{!../../docs_src/first_steps/tutorial001.py!} +``` + +Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд. + +Також можна повернути моделі Pydantic (про це ви дізнаєтесь пізніше). + +Існує багато інших об'єктів і моделей, які будуть автоматично конвертовані в JSON (зокрема ORM тощо). Спробуйте використати свої улюблені, велика ймовірність, що вони вже підтримуються. + +## Підіб'ємо підсумки + +* Імпортуємо `FastAPI`. +* Створюємо екземпляр `app`. +* Пишемо **декоратор операції шляху** як `@app.get("/")`. +* Пишемо **функцію операції шляху**; наприклад, `def root(): ...`. +* Запускаємо сервер у режимі розробки `fastapi dev`. diff --git a/docs/uk/docs/tutorial/index.md b/docs/uk/docs/tutorial/index.md index e5bae74bc..92c3e77a3 100644 --- a/docs/uk/docs/tutorial/index.md +++ b/docs/uk/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...який також включає `uvicorn`, який ви можете використовувати як сервер, який запускає ваш код. -!!! note - Ви також можете встановити його частина за частиною. +/// note - Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі: +Ви також можете встановити його частина за частиною. - ``` - pip install fastapi - ``` +Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі: - Також встановіть `uvicorn`, щоб він працював як сервер: +``` +pip install fastapi +``` + +Також встановіть `uvicorn`, щоб він працював як сервер: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +І те саме для кожної з опціональних залежностей, які ви хочете використовувати. - І те саме для кожної з опціональних залежностей, які ви хочете використовувати. +/// ## Розширений посібник користувача diff --git a/docs/ur/docs/benchmarks.md b/docs/ur/docs/benchmarks.md index 9fc793e6f..8d583de2f 100644 --- a/docs/ur/docs/benchmarks.md +++ b/docs/ur/docs/benchmarks.md @@ -1,5 +1,4 @@ # بینچ مارکس - انڈیپنڈنٹ ٹیک امپور بینچ مارک **FASTAPI** Uvicorn کے تحت چلنے والی ایپلی کیشنز کو ایک تیز رفتار Python فریم ورک میں سے ایک ، صرف Starlette اور Uvicorn کے نیچے ( FASTAPI کے ذریعہ اندرونی طور پر استعمال کیا جاتا ہے ) (*) لیکن جب بینچ مارک اور موازنہ کی جانچ پڑتال کرتے ہو تو آپ کو مندرجہ ذیل بات ذہن میں رکھنی چاہئے. @@ -14,39 +13,39 @@ درجہ بندی کی طرح ہے: -
    -
  • ASGI :Uvicorn سرور
  • +
      +
    • سرور ASGI :Uvicorn
      • -
      • Starlette: (Uvicorn استعمال کرتا ہے) ایک ویب مائیکرو فریم ورک
      • +
      • Starlette: (Uvicorn استعمال کرتا ہے) ایک ویب مائیکرو فریم ورک
        • -
        • FastAPI: (Starlette کا استعمال کرتا ہے) ایک API مائکرو فریم ورک جس میں APIs بنانے کے لیے کئی اضافی خصوصیات ہیں، ڈیٹا کی توثیق وغیرہ کے ساتھ۔
        • +
        • FastAPI: (Starlette کا استعمال کرتا ہے) ایک API مائکرو فریم ورک جس میں APIs بنانے کے لیے کئی اضافی خصوصیات ہیں، ڈیٹا کی توثیق وغیرہ کے ساتھ۔
    -
      -
    • Uvicorn:
    • +
        +
      • Uvicorn:
        • -
        • بہترین کارکردگی ہوگی، کیونکہ اس میں سرور کے علاوہ زیادہ اضافی کوڈ نہیں ہے۔
        • -
        • آپ براہ راست Uvicorn میں درخواست نہیں لکھیں گے۔ اس کا مطلب یہ ہوگا کہ آپ کے کوڈ میں کم و بیش، کم از کم، Starlette (یا FastAPI) کی طرف سے فراہم کردہ تمام کوڈ شامل کرنا ہوں گے۔ اور اگر آپ نے ایسا کیا تو، آپ کی حتمی ایپلیکیشن کا وہی اوور ہیڈ ہوگا جیسا کہ ایک فریم ورک استعمال کرنے اور آپ کے ایپ کوڈ اور کیڑے کو کم سے کم کرنا۔
        • -
        • اگر آپ Uvicorn کا موازنہ کر رہے ہیں تو اس کا موازنہ Daphne، Hypercorn، uWSGI وغیرہ ایپلیکیشن سرورز سے کریں۔
        • +
        • بہترین کارکردگی ہوگی، کیونکہ اس میں سرور کے علاوہ زیادہ اضافی کوڈ نہیں ہے۔
        • +
        • آپ براہ راست Uvicorn میں درخواست نہیں لکھیں گے۔ اس کا مطلب یہ ہوگا کہ آپ کے کوڈ میں کم و بیش، کم از کم، Starlette (یا FastAPI) کی طرف سے فراہم کردہ تمام کوڈ شامل کرنا ہوں گے۔ اور اگر آپ نے ایسا کیا تو، آپ کی حتمی ایپلیکیشن کا وہی اوور ہیڈ ہوگا جیسا کہ ایک فریم ورک استعمال کرنے اور آپ کے ایپ کوڈ اور کیڑے کو کم سے کم کرنا۔
        • +
        • اگر آپ Uvicorn کا موازنہ کر رہے ہیں تو اس کا موازنہ Daphne، Hypercorn، uWSGI وغیرہ ایپلیکیشن سرورز سے کریں۔
      -
        -
      • Starlette:
      • +
          +
        • Starlette:
          • -
          • Uvicorn کے بعد اگلی بہترین کارکردگی ہوگی۔ درحقیقت، Starlette چلانے کے لیے Uvicorn کا استعمال کرتی ہے۔ لہذا، یہ شاید زیادہ کوڈ پر عمل درآمد کرکے Uvicorn سے "سست" ہوسکتا ہے۔
          • -
          • لیکن یہ آپ کو آسان ویب ایپلیکیشنز بنانے کے لیے ٹولز فراہم کرتا ہے، راستوں پر مبنی روٹنگ کے ساتھ، وغیرہ۔
          • -
          • اگر آپ سٹارلیٹ کا موازنہ کر رہے ہیں تو اس کا موازنہ Sanic، Flask، Django وغیرہ سے کریں۔ ویب فریم ورکس (یا مائیکرو فریم ورکس)
          • +
          • Uvicorn کے بعد اگلی بہترین کارکردگی ہوگی۔ درحقیقت، Starlette چلانے کے لیے Uvicorn کا استعمال کرتی ہے۔ لہذا، یہ شاید زیادہ کوڈ پر عمل درآمد کرکے Uvicorn سے "سست" ہوسکتا ہے۔
          • +
          • لیکن یہ آپ کو آسان ویب ایپلیکیشنز بنانے کے لیے ٹولز فراہم کرتا ہے، راستوں پر مبنی روٹنگ کے ساتھ، وغیرہ۔>
          • +
          • اگر آپ سٹارلیٹ کا موازنہ کر رہے ہیں تو اس کا موازنہ Sanic، Flask، Django وغیرہ سے کریں۔ ویب فریم ورکس (یا مائیکرو فریم ورکس)
        -
          -
        • FastAPI:
        • +
            +
          • FastAPI:
            • -
            • جس طرح سے Uvicorn Starlette کا استعمال کرتا ہے اور اس سے تیز نہیں ہو سکتا، Starlette FastAPI کا استعمال کرتا ہے، اس لیے یہ اس سے تیز نہیں ہو سکتا۔
            • -
            • Starlette FastAPI کے اوپری حصے میں مزید خصوصیات فراہم کرتا ہے۔ وہ خصوصیات جن کی آپ کو APIs بناتے وقت تقریباً ہمیشہ ضرورت ہوتی ہے، جیسے ڈیٹا کی توثیق اور سیریلائزیشن۔ اور اسے استعمال کرنے سے، آپ کو خودکار دستاویزات مفت میں مل جاتی ہیں (خودکار دستاویزات چلنے والی ایپلی کیشنز میں اوور ہیڈ کو بھی شامل نہیں کرتی ہیں، یہ اسٹارٹ اپ پر تیار ہوتی ہیں)۔
            • -
            • اگر آپ نے FastAPI کا استعمال نہیں کیا ہے اور Starlette کو براہ راست استعمال کیا ہے (یا کوئی دوسرا ٹول، جیسے Sanic، Flask، Responder، وغیرہ) آپ کو تمام ڈیٹا کی توثیق اور سیریلائزیشن کو خود نافذ کرنا ہوگا۔ لہذا، آپ کی حتمی ایپلیکیشن اب بھی وہی اوور ہیڈ ہوگی جیسا کہ اسے FastAPI کا استعمال کرتے ہوئے بنایا گیا تھا۔ اور بہت سے معاملات میں، یہ ڈیٹا کی توثیق اور سیریلائزیشن ایپلی کیشنز میں لکھے گئے کوڈ کی سب سے بڑی مقدار ہے۔
            • -
            • لہذا، FastAPI کا استعمال کرکے آپ ترقیاتی وقت، Bugs، کوڈ کی لائنوں کی بچت کر رہے ہیں، اور شاید آپ کو وہی کارکردگی (یا بہتر) ملے گی اگر آپ اسے استعمال نہیں کرتے (جیسا کہ آپ کو یہ سب اپنے کوڈ میں لاگو کرنا ہوگا۔ )
            • -
            • اگر آپ FastAPI کا موازنہ کر رہے ہیں، تو اس کا موازنہ ویب ایپلیکیشن فریم ورک (یا ٹولز کے سیٹ) سے کریں جو ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات فراہم کرتا ہے، جیسے Flask-apispec، NestJS، Molten، وغیرہ۔ مربوط خودکار ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات کے ساتھ فریم ورک۔
            • +
            • جس طرح سے Uvicorn Starlette کا استعمال کرتا ہے اور اس سے تیز نہیں ہو سکتا، Starlette FastAPI کا استعمال کرتا ہے، اس لیے یہ اس سے تیز نہیں ہو سکتا۔
            • +
            • Starlette FastAPI کے اوپری حصے میں مزید خصوصیات فراہم کرتا ہے۔ وہ خصوصیات جن کی آپ کو APIs بناتے وقت تقریباً ہمیشہ ضرورت ہوتی ہے، جیسے ڈیٹا کی توثیق اور سیریلائزیشن۔ اور اسے استعمال کرنے سے، آپ کو خودکار دستاویزات مفت میں مل جاتی ہیں (خودکار دستاویزات چلنے والی ایپلی کیشنز میں اوور ہیڈ کو بھی شامل نہیں کرتی ہیں، یہ اسٹارٹ اپ پر تیار ہوتی ہیں)۔
            • +
            • اگر آپ نے FastAPI کا استعمال نہیں کیا ہے اور Starlette کو براہ راست استعمال کیا ہے (یا کوئی دوسرا ٹول، جیسے Sanic، Flask، Responder، وغیرہ) آپ کو تمام ڈیٹا کی توثیق اور سیریلائزیشن کو خود نافذ کرنا ہوگا۔ لہذا، آپ کی حتمی ایپلیکیشن اب بھی وہی اوور ہیڈ ہوگی جیسا کہ اسے FastAPI کا استعمال کرتے ہوئے بنایا گیا تھا۔ اور بہت سے معاملات میں، یہ ڈیٹا کی توثیق اور سیریلائزیشن ایپلی کیشنز میں لکھے گئے کوڈ کی سب سے بڑی مقدار ہے۔
            • +
            • لہذا، FastAPI کا استعمال کرکے آپ ترقیاتی وقت، Bugs، کوڈ کی لائنوں کی بچت کر رہے ہیں، اور شاید آپ کو وہی کارکردگی (یا بہتر) ملے گی اگر آپ اسے استعمال نہیں کرتے (جیسا کہ آپ کو یہ سب اپنے کوڈ میں لاگو کرنا ہوگا۔ )>
            • +
            • اگر آپ FastAPI کا موازنہ کر رہے ہیں، تو اس کا موازنہ ویب ایپلیکیشن فریم ورک (یا ٹولز کے سیٹ) سے کریں جو ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات فراہم کرتا ہے، جیسے Flask-apispec، NestJS، Molten، وغیرہ۔ مربوط خودکار ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات کے ساتھ فریم ورک۔
          diff --git a/docs/vi/docs/features.md b/docs/vi/docs/features.md index 9edb1c8fa..2220d9fa5 100644 --- a/docs/vi/docs/features.md +++ b/docs/vi/docs/features.md @@ -64,10 +64,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` nghĩa là: +/// info - Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` nghĩa là: + +Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Được hỗ trợ từ các trình soạn thảo diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 3ade853e2..5e346ded8 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

          FastAPI

          @@ -5,11 +11,11 @@ FastAPI framework, hiệu năng cao, dễ học, dễ code, sẵn sàng để tạo ra sản phẩm

          - - Test + + Test - - Coverage + + Coverage Package version @@ -23,15 +29,15 @@ **Tài liệu**: https://fastapi.tiangolo.com -**Mã nguồn**: https://github.com/tiangolo/fastapi +**Mã nguồn**: https://github.com/fastapi/fastapi --- -FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python 3.8+ dựa trên tiêu chuẩn Python type hints. +FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python dựa trên tiêu chuẩn Python type hints. Những tính năng như: -* **Nhanh**: Hiệu năng rất cao khi so sánh với **NodeJS** và **Go** (cảm ơn Starlette và Pydantic). [Một trong những Python framework nhanh nhất](#performance). +* **Nhanh**: Hiệu năng rất cao khi so sánh với **NodeJS** và **Go** (cảm ơn Starlette và Pydantic). [Một trong những Python framework nhanh nhất](#hieu-nang). * **Code nhanh**: Tăng tốc độ phát triển tính năng từ 200% tới 300%. * * **Ít lỗi hơn**: Giảm khoảng 40% những lỗi phát sinh bởi con người (nhà phát triển). * * **Trực giác tốt hơn**: Được các trình soạn thảo hỗ tuyệt vời. Completion mọi nơi. Ít thời gian gỡ lỗi. @@ -63,7 +69,7 @@ Những tính năng như: "_[...] Tôi đang sử dụng **FastAPI** vô cùng nhiều vào những ngày này. [...] Tôi thực sự đang lên kế hoạch sử dụng nó cho tất cả các nhóm **dịch vụ ML tại Microsoft**. Một vài trong số đó đang tích hợp vào sản phẩm lõi của **Window** và một vài sản phẩm cho **Office**._" -

          Kabir Khan - Microsoft (ref)
          +
          Kabir Khan - Microsoft (ref)
          --- @@ -87,7 +93,7 @@ Những tính năng như: "_Thành thật, những gì bạn đã xây dựng nhìn siêu chắc chắn và bóng bẩy. Theo nhiều cách, nó là những gì tôi đã muốn Hug trở thành - thật sự truyền cảm hứng để thấy ai đó xây dựng nó._" -
          Timothy Crosley - người tạo ra Hug (ref)
          +
          Timothy Crosley - người tạo ra Hug (ref)
          --- @@ -116,8 +122,6 @@ Nếu bạn đang xây dựng một CLIStarlette cho phần web. @@ -332,7 +336,7 @@ Bạn định nghĩa bằng cách sử dụng các kiểu dữ liệu chuẩn c Bạn không phải học một cú pháp mới, các phương thức và class của một thư viện cụ thể nào. -Chỉ cần sử dụng các chuẩn của **Python 3.8+**. +Chỉ cần sử dụng các chuẩn của **Python**. Ví dụ, với một tham số kiểu `int`: @@ -448,8 +452,7 @@ Independent TechEmpower benchmarks cho thấy các ứng dụng **FastAPI** ch Sử dụng bởi Pydantic: -* ujson - "Parse" JSON nhanh hơn. -* email_validator - cho email validation. +* email-validator - cho email validation. Sử dụng Starlette: @@ -458,12 +461,12 @@ Sử dụng Starlette: * python-multipart - Bắt buộc nếu bạn muốn hỗ trợ "parsing", form với `request.form()`. * itsdangerous - Bắt buộc để hỗ trợ `SessionMiddleware`. * pyyaml - Bắt buộc để hỗ trợ `SchemaGenerator` cho Starlette (bạn có thể không cần nó trong FastAPI). -* ujson - Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`. Sử dụng bởi FastAPI / Starlette: * uvicorn - Server để chạy ứng dụng của bạn. * orjson - Bắt buộc nếu bạn muốn sử dụng `ORJSONResponse`. +* ujson - Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`. Bạn có thể cài đặt tất cả những dependency trên với `pip install "fastapi[all]"`. diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index b2a399aa5..275b0eb39 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -12,15 +12,18 @@ Bằng việc khai báo kiểu dữ liệu cho các biến của bạn, các tr Nhưng thậm chí nếu bạn không bao giờ sử dụng **FastAPI**, bạn sẽ được lợi từ việc học một ít về chúng. -!!! note - Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo. +/// note + +Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo. + +/// ## Động lực Hãy bắt đầu với một ví dụ đơn giản: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Kết quả khi gọi chương trình này: @@ -36,7 +39,7 @@ Hàm thực hiện như sau: * Nối chúng lại với nhau bằng một kí tự trắng ở giữa. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Sửa đổi @@ -80,7 +83,7 @@ Chính là nó. Những thứ đó là "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Đó không giống như khai báo những giá trị mặc định giống như: @@ -110,7 +113,7 @@ Với cái đó, bạn có thể cuộn, nhìn thấy các lựa chọn, cho đ Kiểm tra hàm này, nó đã có gợi ý kiểu dữ liệu: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạn không chỉ có được completion, bạn cũng được kiểm tra lỗi: @@ -120,7 +123,7 @@ Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạ Bây giờ bạn biết rằng bạn phải sửa nó, chuyển `age` sang một xâu với `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Khai báo các kiểu dữ liệu @@ -141,7 +144,7 @@ Bạn có thể sử dụng, ví dụ: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu @@ -170,45 +173,55 @@ Nếu bạn có thể sử dụng **phiên bản cuối cùng của Python**, s Ví dụ, hãy định nghĩa một biến là `list` các `str`. -=== "Python 3.9+" +//// tab | Python 3.9+ - Khai báo biến với cùng dấu hai chấm (`:`). +Khai báo biến với cùng dấu hai chấm (`:`). - Tương tự kiểu dữ liệu `list`. +Tương tự kiểu dữ liệu `list`. - Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: +Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - Từ `typing`, import `List` (với chữ cái `L` viết hoa): +//// tab | Python 3.8+ - ``` Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Từ `typing`, import `List` (với chữ cái `L` viết hoa): - Khai báo biến với cùng dấu hai chấm (`:`). +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +Khai báo biến với cùng dấu hai chấm (`:`). - Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. +Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. - Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: +Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: + +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -!!! info - Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu". +/// info - Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên). +Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu". + +Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên). + +/// Có nghĩa là: "biến `items` là một `list`, và mỗi phần tử trong danh sách này là một `str`". -!!! tip - Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế. +/// tip + +Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế. + +/// Bằng cách này, trình soạn thảo của bạn có thể hỗ trợ trong khi xử lí các phần tử trong danh sách: @@ -224,17 +237,21 @@ Và do vậy, trình soạn thảo biết nó là một `str`, và cung cấp s Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` + +//// Điều này có nghĩa là: @@ -249,17 +266,21 @@ Tham số kiểu dữ liệu đầu tiên dành cho khóa của `dict`. Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// Điều này có nghĩa là: @@ -278,17 +299,21 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt những kiểu giá trị khả thi phân cách bởi một dấu sổ dọc (`|`). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// Trong cả hai trường hợp có nghĩa là `item` có thể là một `int` hoặc `str`. @@ -299,7 +324,7 @@ Bạn có thể khai báo một giá trị có thể có một kiểu dữ liệ Trong Python 3.6 hoặc lớn hơn (bao gồm Python 3.10) bạn có thể khai báo nó bằng các import và sử dụng `Optional` từ mô đun `typing`. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo giúp bạn phát hiện các lỗi mà bạn có thể gặp như một giá trị luôn là một `str`, trong khi thực tế nó rất có thể là `None`. @@ -308,23 +333,29 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g Điều này cũng có nghĩa là trong Python 3.10, bạn có thể sử dụng `Something | None`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+ alternative" +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// #### Sử dụng `Union` hay `Optional` @@ -344,7 +375,7 @@ Nó chỉ là về các từ và tên. Nhưng những từ đó có thể ảnh Cho một ví dụ, hãy để ý hàm này: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` Tham số `name` được định nghĩa là `Optional[str]`, nhưng nó **không phải là tùy chọn**, bạn không thể gọi hàm mà không có tham số: @@ -362,7 +393,7 @@ say_hi(name=None) # This works, None is valid 🎉 Tin tốt là, khi bạn sử dụng Python 3.10, bạn sẽ không phải lo lắng về điều đó, bạn sẽ có thể sử dụng `|` để định nghĩa hợp của các kiểu dữ liệu một cách đơn giản: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎 @@ -372,47 +403,53 @@ Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optiona Những kiểu dữ liệu này lấy tham số kiểu dữ liệu trong dấu ngoặc vuông được gọi là **Kiểu dữ liệu tổng quát**, cho ví dụ: -=== "Python 3.10+" +//// tab | Python 3.10+ + +Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong): - Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +Và tương tự với Python 3.6, từ mô đun `typing`: - Và tương tự với Python 3.6, từ mô đun `typing`: +* `Union` +* `Optional` (tương tự như Python 3.6) +* ...và các kiểu dữ liệu khác. - * `Union` - * `Optional` (tương tự như Python 3.6) - * ...và các kiểu dữ liệu khác. +Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng sổ dọc ('|') để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều. - Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng sổ dọc ('|') để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều. +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong): +Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - Và tương tự với Python 3.6, từ mô đun `typing`: +Và tương tự với Python 3.6, từ mô đun `typing`: - * `Union` - * `Optional` - * ...and others. +* `Union` +* `Optional` +* ...and others. -=== "Python 3.8+" +//// - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...và các kiểu khác. +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...và các kiểu khác. + +//// ### Lớp như kiểu dữ liệu @@ -421,13 +458,13 @@ Bạn cũng có thể khai báo một lớp như là kiểu dữ liệu của m Hãy nói rằng bạn muốn có một lớp `Person` với một tên: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Sau đó bạn có thể khai báo một biến có kiểu là `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo: @@ -452,56 +489,71 @@ Và bạn nhận được tất cả sự hỗ trợ của trình soạn thảo Một ví dụ từ tài liệu chính thức của Pydantic: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó. -!!! info - Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó. +/// **FastAPI** được dựa hoàn toàn trên Pydantic. Bạn sẽ thấy nhiều ví dụ thực tế hơn trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}. -!!! tip - Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về Required Optional fields. +/// tip + +Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về Required Optional fields. +/// ## Type Hints với Metadata Annotations Python cũng có một tính năng cho phép đặt **metadata bổ sung** trong những gợi ý kiểu dữ liệu này bằng cách sử dụng `Annotated`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` - Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`. - Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`. +Nó đã được cài đặt sẵng cùng với **FastAPI**. - Nó đã được cài đặt sẵng cùng với **FastAPI**. +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013.py!} - ``` +//// Python bản thân nó không làm bất kì điều gì với `Annotated`. Với các trình soạn thảo và các công cụ khác, kiểu dữ liệu vẫn là `str`. @@ -514,10 +566,13 @@ Bây giờ, bạn chỉ cần biết rằng `Annotated` tồn tại, và nó là Sau đó, bạn sẽ thấy sự **mạnh mẽ** mà nó có thể làm. -!!! tip - Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨ +/// tip - Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀 +Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨ + +Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀 + +/// ## Các gợi ý kiểu dữ liệu trong **FastAPI** @@ -541,5 +596,8 @@ Với **FastAPI**, bạn khai báo các tham số với gợi ý kiểu và bạ Điều quan trọng là bằng việc sử dụng các kiểu dữ liệu chuẩn của Python (thay vì thêm các lớp, decorators,...), **FastAPI** sẽ thực hiện nhiều công việc cho bạn. -!!! info - Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như "cheat sheet" từ `mypy`. +/// info + +Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như "cheat sheet" từ `mypy`. + +/// diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md index 712f00852..934527b8e 100644 --- a/docs/vi/docs/tutorial/first-steps.md +++ b/docs/vi/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Tệp tin FastAPI đơn giản nhất có thể trông như này: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Sao chép sang một tệp tin `main.py`. @@ -24,12 +24,15 @@ $ uvicorn main:app --reload
-!!! note - Câu lệnh `uvicorn main:app` được giải thích như sau: +/// note - * `main`: tệp tin `main.py` (một Python "mô đun"). - * `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`. - * `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển. +Câu lệnh `uvicorn main:app` được giải thích như sau: + +* `main`: tệp tin `main.py` (một Python "mô đun"). +* `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`. +* `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển. + +/// Trong output, có một dòng giống như: @@ -131,20 +134,23 @@ Bạn cũng có thể sử dụng nó để sinh code tự động, với các c ### Bước 1: import `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn. -!!! note "Chi tiết kĩ thuật" - `FastAPI` là một class kế thừa trực tiếp `Starlette`. +/// note | Chi tiết kĩ thuật + +`FastAPI` là một class kế thừa trực tiếp `Starlette`. - Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`. +Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`. + +/// ### Bước 2: Tạo một `FastAPI` "instance" ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Biến `app` này là một "instance" của class `FastAPI`. @@ -166,7 +172,7 @@ $ uvicorn main:app --reload Nếu bạn tạo ứng dụng của bạn giống như: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` Và đặt nó trong một tệp tin `main.py`, sau đó bạn sẽ gọi `uvicorn` giống như: @@ -199,8 +205,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route". +/// info + +Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route". + +/// Trong khi xây dựng một API, "đường dẫn" là các chính để phân tách "mối quan hệ" và "tài nguyên". @@ -242,7 +251,7 @@ Chúng ta cũng sẽ gọi chúng là "**các toán tử**". #### Định nghĩa moojt *decorator cho đường dẫn toán tử* ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")` nói **FastAPI** rằng hàm bên dưới có trách nhiệm xử lí request tới: @@ -250,16 +259,19 @@ Chúng ta cũng sẽ gọi chúng là "**các toán tử**". * đường dẫn `/` * sử dụng một toán tửget -!!! info Thông tin về "`@decorator`" - Cú pháp `@something` trong Python được gọi là một "decorator". +/// info | Thông tin về "`@decorator`" - Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời). +Cú pháp `@something` trong Python được gọi là một "decorator". - Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó. +Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời). - Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`. +Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó. - Nó là một "**decorator đường dẫn toán tử**". +Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`. + +Nó là một "**decorator đường dẫn toán tử**". + +/// Bạn cũng có thể sử dụng với các toán tử khác: @@ -274,14 +286,17 @@ Và nhiều hơn với các toán tử còn lại: * `@app.patch()` * `@app.trace()` -!!! tip - Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước. +/// tip + +Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước. - **FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào. +**FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào. - Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc. +Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc. - Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`. +Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`. + +/// ### Step 4: Định nghĩa **hàm cho đường dẫn toán tử** @@ -292,7 +307,7 @@ Và nhiều hơn với các toán tử còn lại: * **hàm**: là hàm bên dưới "decorator" (bên dưới `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Đây là một hàm Python. @@ -306,16 +321,19 @@ Trong trường hợp này, nó là một hàm `async`. Bạn cũng có thể định nghĩa nó như là một hàm thông thường thay cho `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note + +Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Bước 5: Nội dung trả về ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Bạn có thể trả về một `dict`, `list`, một trong những giá trị đơn như `str`, `int`,... diff --git a/docs/vi/docs/tutorial/index.md b/docs/vi/docs/tutorial/index.md index e8a93fe40..dfeeed8c5 100644 --- a/docs/vi/docs/tutorial/index.md +++ b/docs/vi/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...dó cũng bao gồm `uvicorn`, bạn có thể sử dụng như một server để chạy code của bạn. -!!! note - Bạn cũng có thể cài đặt nó từng phần. +/// note - Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production: +Bạn cũng có thể cài đặt nó từng phần. - ``` - pip install fastapi - ``` +Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production: - Cũng cài đặt `uvicorn` để làm việc như một server: +``` +pip install fastapi +``` + +Cũng cài đặt `uvicorn` để làm việc như một server: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng. - Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng. +/// ## Hướng dẫn nâng cao diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index 5684f0a6a..3ad1483de 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ Ìlànà wẹ́ẹ́bù FastAPI, iṣẹ́ gíga, ó rọrùn láti kọ̀, o yára láti kóòdù, ó sì ṣetán fún iṣelọpọ ní lílo

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,15 +29,15 @@ **Àkọsílẹ̀**: https://fastapi.tiangolo.com -**Orisun Kóòdù**: https://github.com/tiangolo/fastapi +**Orisun Kóòdù**: https://github.com/fastapi/fastapi --- -FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python 3.8+ èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python. +FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python. Àwọn ẹya pàtàkì ni: -* **Ó yára**: Iṣẹ tí ó ga púpọ̀, tí ó wa ni ibamu pẹ̀lú **NodeJS** àti **Go** (ọpẹ si Starlette àti Pydantic). [Ọkan nínú àwọn ìlànà Python ti o yára jùlọ ti o wa](#performance). +* **Ó yára**: Iṣẹ tí ó ga púpọ̀, tí ó wa ni ibamu pẹ̀lú **NodeJS** àti **Go** (ọpẹ si Starlette àti Pydantic). [Ọkan nínú àwọn ìlànà Python ti o yára jùlọ ti o wa](#isesi). * **Ó yára láti kóòdù**: O mu iyara pọ si láti kọ àwọn ẹya tuntun kóòdù nipasẹ "Igba ìdá ọgọ́rùn-ún" (i.e. 200%) si "ọ̀ọ́dúrún ìdá ọgọ́rùn-ún" (i.e. 300%). * **Àìtọ́ kékeré**: O n din aṣiṣe ku bi ọgbon ìdá ọgọ́rùn-ún (i.e. 40%) ti eda eniyan (oṣiṣẹ kóòdù) fa. * * **Ọgbọ́n àti ìmọ̀**: Atilẹyin olootu nla. Ìparí nibi gbogbo. Àkókò díẹ̀ nipa wíwá ibi tí ìṣòro kóòdù wà. @@ -63,7 +69,7 @@ FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́b "_[...] Mò ń lo **FastAPI** púpọ̀ ní lẹ́nu àìpẹ́ yìí. [...] Mo n gbero láti lo o pẹ̀lú àwọn ẹgbẹ mi fún gbogbo iṣẹ **ML wa ni Microsoft**. Diẹ nínú wọn ni afikun ti ifilelẹ àwọn ẹya ara ti ọja **Windows** wa pẹ̀lú àwọn ti **Office**._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -87,7 +93,7 @@ FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́b "_Ní tòótọ́, ohun tí o kọ dára ó sì tún dán. Ní ọ̀pọ̀lọpọ̀ ọ̀nà, ohun tí mo fẹ́ kí **Hug** jẹ́ nìyẹn - ó wúni lórí gan-an láti rí ẹnìkan tí ó kọ́ nǹkan bí èyí._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -115,8 +121,6 @@ Ti o ba n kọ ohun èlò CLI láti ## Èròjà -Python 3.8+ - FastAPI dúró lórí àwọn èjìká tí àwọn òmíràn: * Starlette fún àwọn ẹ̀yà ayélujára. @@ -331,7 +335,7 @@ O ṣe ìyẹn pẹ̀lú irúfẹ́ àmì ìtọ́kasí ìgbàlódé Python. O ò nílò láti kọ́ síńtáàsì tuntun, ìlànà tàbí ọ̀wọ́ kíláàsì kan pàtó, abbl (i.e. àti bẹbẹ lọ). -Ìtọ́kasí **Python 3.8+** +Ìtọ́kasí **Python** Fún àpẹẹrẹ, fún `int`: @@ -445,7 +449,7 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn email_validator - fún ifọwọsi ímeèlì. +* email-validator - fún ifọwọsi ímeèlì. * pydantic-settings - fún ètò ìsàkóso. * pydantic-extra-types - fún àfikún oríṣi láti lọ pẹ̀lú Pydantic. @@ -456,12 +460,12 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn python-multipart - Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún "àyẹ̀wò" fọọmu, pẹ̀lú `request.form()`. * itsdangerous - Nílò fún àtìlẹ́yìn `SessionMiddleware`. * pyyaml - Nílò fún àtìlẹ́yìn Starlette's `SchemaGenerator` (ó ṣe ṣe kí ó má nílò rẹ̀ fún FastAPI). -* ujson - Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`. Èyí tí FastAPI / Starlette ń lò: * uvicorn - Fún olupin tí yóò sẹ́ àmúyẹ àti tí yóò ṣe ìpèsè fún iṣẹ́ rẹ tàbí ohun èlò rẹ. * orjson - Nílò tí ó bá fẹ́ láti lọ `ORJSONResponse`. +* ujson - Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`. Ó lè fi gbogbo àwọn wọ̀nyí sórí ẹrọ pẹ̀lú `pip install "fastapi[all]"`. diff --git a/docs/zh-hant/docs/about/index.md b/docs/zh-hant/docs/about/index.md new file mode 100644 index 000000000..5dcee68f2 --- /dev/null +++ b/docs/zh-hant/docs/about/index.md @@ -0,0 +1,3 @@ +# 關於 FastAPI + +關於 FastAPI、其設計、靈感來源等更多資訊。 🤓 diff --git a/docs/zh-hant/docs/benchmarks.md b/docs/zh-hant/docs/benchmarks.md new file mode 100644 index 000000000..c59e8e71c --- /dev/null +++ b/docs/zh-hant/docs/benchmarks.md @@ -0,0 +1,34 @@ +# 基準測試 + +由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 最快的 Python 可用框架之一,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。 + +但是在查看基準得分和對比時,請注意以下幾點。 + +## 基準測試和速度 + +當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。 + +具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。 + +該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。 + +層次結構如下: + +* **Uvicorn**:ASGI 伺服器 + * **Starlette**:(使用 Uvicorn)一個網頁微框架 + * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。 + +* **Uvicorn**: + * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。 + * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。 + * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。 +* **Starlette**: + * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。 + * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。 + * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。 +* **FastAPI**: + * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。 + * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。 + * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。 + * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。 + * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。 diff --git a/docs/zh-hant/docs/deployment/cloud.md b/docs/zh-hant/docs/deployment/cloud.md new file mode 100644 index 000000000..29ebe3ff5 --- /dev/null +++ b/docs/zh-hant/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# 在雲端部署 FastAPI + +你幾乎可以使用**任何雲端供應商**來部署你的 FastAPI 應用程式。 + +在大多數情況下,主要的雲端供應商都有部署 FastAPI 的指南。 + +## 雲端供應商 - 贊助商 + +一些雲端供應商 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,這確保了 FastAPI 及其**生態系統**持續健康地**發展**。 + +這也展現了他們對 FastAPI 和其**社群**(包括你)的真正承諾,他們不僅希望為你提供**優質的服務**,還希望確保你擁有一個**良好且健康的框架**:FastAPI。🙇 + +你可能會想嘗試他們的服務,以下有他們的指南: + +* Platform.sh +* Porter +* Coherence diff --git a/docs/zh-hant/docs/deployment/index.md b/docs/zh-hant/docs/deployment/index.md new file mode 100644 index 000000000..1726562b4 --- /dev/null +++ b/docs/zh-hant/docs/deployment/index.md @@ -0,0 +1,21 @@ +# 部署 + +部署 **FastAPI** 應用程式相對容易。 + +## 部署是什麼意思 + +**部署**應用程式指的是執行一系列必要的步驟,使其能夠**讓使用者存取和使用**。 + +對於一個 **Web API**,部署通常涉及將其放置在**遠端伺服器**上,並使用性能優良且穩定的**伺服器程式**,確保使用者能夠高效、無中斷地存取應用程式,且不會遇到問題。 + +這與**開發**階段形成鮮明對比,在**開發**階段,你會不斷更改程式碼、破壞程式碼、修復程式碼,然後停止和重新啟動伺服器等。 + +## 部署策略 + +根據你的使用場景和使用工具,有多種方法可以實現此目的。 + +你可以使用一些工具自行**部署伺服器**,你也可以使用能為你完成部分工作的**雲端服務**,或其他可能的選項。 + +我將向你展示在部署 **FastAPI** 應用程式時你可能應該記住的一些主要概念(儘管其中大部分適用於任何其他類型的 Web 應用程式)。 + +在接下來的部分中,你將看到更多需要記住的細節以及一些技巧。 ✨ diff --git a/docs/zh-hant/docs/environment-variables.md b/docs/zh-hant/docs/environment-variables.md new file mode 100644 index 000000000..a1598fc01 --- /dev/null +++ b/docs/zh-hant/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 環境變數 + +/// tip + +如果你已經知道什麼是「環境變數」並且知道如何使用它們,你可以放心跳過這一部分。 + +/// + +環境變數(也稱為「**env var**」)是一個獨立於 Python 程式碼**之外**的變數,它存在於**作業系統**中,可以被你的 Python 程式碼(或其他程式)讀取。 + +環境變數對於處理應用程式**設定**(作為 Python **安裝**的一部分等方面)非常有用。 + +## 建立和使用環境變數 + +你在 **shell(終端機)**中就可以**建立**和使用環境變數,並不需要用到 Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 你可以使用以下指令建立一個名為 MY_NAME 的環境變數 +$ export MY_NAME="Wade Wilson" + +// 然後,你可以在其他程式中使用它,例如 +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 建立一個名為 MY_NAME 的環境變數 +$ $Env:MY_NAME = "Wade Wilson" + +// 在其他程式中使用它,例如 +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 在 Python 中讀取環境變數 + +你也可以在 Python **之外**的終端機中建立環境變數(或使用其他方法),然後在 Python 中**讀取**它們。 + +例如,你可以建立一個名為 `main.py` 的檔案,其中包含以下內容: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +第二個參數是 `os.getenv()` 的預設回傳值。 + +如果沒有提供,預設值為 `None`,這裡我們提供 `"World"` 作為預設值。 + +/// + +然後你可以呼叫這個 Python 程式: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 這裡我們還沒有設定環境變數 +$ python main.py + +// 因為我們沒有設定環境變數,所以我們得到的是預設值 + +Hello World from Python + +// 但是如果我們事先建立過一個環境變數 +$ export MY_NAME="Wade Wilson" + +// 然後再次呼叫程式 +$ python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 這裡我們還沒有設定環境變數 +$ python main.py + +// 因為我們沒有設定環境變數,所以我們得到的是預設值 + +Hello World from Python + +// 但是如果我們事先建立過一個環境變數 +$ $Env:MY_NAME = "Wade Wilson" + +// 然後再次呼叫程式 +$ python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +由於環境變數可以在程式碼之外設定,但可以被程式碼讀取,並且不必與其他檔案一起儲存(提交到 `git`),因此通常用於配置或**設定**。 + +你還可以為**特定的程式呼叫**建立特定的環境變數,該環境變數僅對該程式可用,且僅在其執行期間有效。 + +要實現這一點,只需在同一行內(程式本身之前)建立它: + +
+ +```console +// 在這個程式呼叫的同一行中建立一個名為 MY_NAME 的環境變數 +$ MY_NAME="Wade Wilson" python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python + +// 在此之後這個環境變數將不再存在 +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +你可以在 The Twelve-Factor App: 配置中了解更多資訊。 + +/// + +## 型別和驗證 + +這些環境變數只能處理**文字字串**,因為它們是位於 Python 範疇之外的,必須與其他程式和作業系統的其餘部分相容(甚至與不同的作業系統相容,如 Linux、Windows、macOS)。 + +這意味著從環境變數中讀取的**任何值**在 Python 中都將是一個 `str`,任何型別轉換或驗證都必須在程式碼中完成。 + +你將在[進階使用者指南 - 設定和環境變數](./advanced/settings.md)中了解更多關於使用環境變數處理**應用程式設定**的資訊。 + +## `PATH` 環境變數 + +有一個**特殊的**環境變數稱為 **`PATH`**,作業系統(Linux、macOS、Windows)用它來查找要執行的程式。 + +`PATH` 變數的值是一個長字串,由 Linux 和 macOS 上的冒號 `:` 分隔的目錄組成,而在 Windows 上則是由分號 `;` 分隔的。 + +例如,`PATH` 環境變數可能如下所示: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +這意味著系統應該在以下目錄中查找程式: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +這意味著系統應該在以下目錄中查找程式: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +當你在終端機中輸入一個**指令**時,作業系統會在 `PATH` 環境變數中列出的**每個目錄**中**查找**程式。 + +例如,當你在終端機中輸入 `python` 時,作業系統會在該列表中的**第一個目錄**中查找名為 `python` 的程式。 + +如果找到了,那麼作業系統將**使用它**;否則,作業系統會繼續在**其他目錄**中查找。 + +### 安裝 Python 並更新 `PATH` + +安裝 Python 時,可能會詢問你是否要更新 `PATH` 環境變數。 + +//// tab | Linux, macOS + +假設你安裝了 Python,並將其安裝在目錄 `/opt/custompython/bin` 中。 + +如果你選擇更新 `PATH` 環境變數,那麼安裝程式會將 `/opt/custompython/bin` 加入到 `PATH` 環境變數中。 + +它看起來大致會是這樣: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +如此一來,當你在終端機輸入 `python` 時,系統會在 `/opt/custompython/bin` 中找到 Python 程式(最後一個目錄)並使用它。 + +//// + +//// tab | Windows + +假設你安裝了 Python,並將其安裝在目錄 `C:\opt\custompython\bin` 中。 + +如果你選擇更新 `PATH` 環境變數(在 Python 安裝程式中,這個選項是名為 `Add Python x.xx to PATH` 的勾選框——譯者註),那麼安裝程式會將 `C:\opt\custompython\bin` 加入到 `PATH` 環境變數中。 + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +如此一來,當你在終端機輸入 `python` 時,系統會在 `C:\opt\custompython\bin` 中找到 Python 程式(最後一個目錄)並使用它。 + +//// + +因此,如果你輸入: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +系統會在 `/opt/custompython/bin` 中**找到** `python` 程式並執行它。 + +這大致等同於輸入以下指令: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +系統會在 `C:\opt\custompython\bin\python` 中**找到** `python` 程式並執行它。 + +這大致等同於輸入以下指令: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +當學習[虛擬環境](virtual-environments.md)時,這些資訊將會很有用。 + +## 結論 + +透過這個教學,你應該對**環境變數**是什麼以及如何在 Python 中使用它們有了基本的了解。 + +你也可以在環境變數 - 維基百科 (Wikipedia for Environment Variable) 中了解更多關於它們的資訊。 + +在許多情況下,環境變數的用途和適用性可能不會立刻顯現。但是在開發過程中,它們會在許多不同的場景中出現,因此瞭解它們是非常必要的。 + +例如,你在接下來的[虛擬環境](virtual-environments.md)章節中將需要這些資訊。 diff --git a/docs/zh-hant/docs/fastapi-cli.md b/docs/zh-hant/docs/fastapi-cli.md new file mode 100644 index 000000000..3c644ce46 --- /dev/null +++ b/docs/zh-hant/docs/fastapi-cli.md @@ -0,0 +1,83 @@ +# FastAPI CLI + +**FastAPI CLI** 是一個命令列程式,能用來運行你的 FastAPI 應用程式、管理你的 FastAPI 專案等。 + +當你安裝 FastAPI(例如使用 `pip install "fastapi[standard]"`),它會包含一個叫做 `fastapi-cli` 的套件,這個套件提供了 `fastapi` 命令。 + +要運行你的 FastAPI 應用程式來進行開發,你可以使用 `fastapi dev` 命令: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +`fastapi` 命令列程式就是 **FastAPI CLI**。 + +FastAPI CLI 接收你的 Python 程式路徑(例如 `main.py`),並自動檢測 FastAPI 實例(通常命名為 `app`),確定正確的引入模組流程,然後運行該應用程式。 + +在生產環境,你應該使用 `fastapi run` 命令。 🚀 + +**FastAPI CLI** 內部使用了 Uvicorn,這是一個高效能、適合生產環境的 ASGI 伺服器。 😎 + +## `fastapi dev` + +執行 `fastapi dev` 會啟動開發模式。 + +預設情況下,**auto-reload** 功能是啟用的,當你對程式碼進行修改時,伺服器會自動重新載入。這會消耗較多資源,並且可能比禁用時更不穩定。因此,你應該只在開發環境中使用此功能。它也會在 IP 位址 `127.0.0.1` 上監聽,這是用於你的機器與自身通訊的 IP 位址(`localhost`)。 + +## `fastapi run` + +執行 `fastapi run` 會以生產模式啟動 FastAPI。 + +預設情況下,**auto-reload** 功能是禁用的。它也會在 IP 位址 `0.0.0.0` 上監聽,表示會監聽所有可用的 IP 地址,這樣任何能與該機器通訊的人都可以公開存取它。這通常是你在生產環境中運行應用程式的方式,例如在容器中運行時。 + +在大多數情況下,你會(也應該)有一個「終止代理」來處理 HTTPS,這取決於你如何部署你的應用程式,你的服務供應商可能會為你做這件事,或者你需要自己設置它。 + +/// tip + +你可以在[部署文件](deployment/index.md){.internal-link target=_blank}中了解更多相關資訊。 + +/// diff --git a/docs/zh-hant/docs/how-to/index.md b/docs/zh-hant/docs/how-to/index.md new file mode 100644 index 000000000..db740140d --- /dev/null +++ b/docs/zh-hant/docs/how-to/index.md @@ -0,0 +1,13 @@ +# 使用指南 - 範例集 + +在這裡,你將會看到**不同主題**的範例或「如何使用」的指南。 + +大多數這些想法都是**獨立**的,在大多數情況下,你只需要研究那些直接適用於**你的專案**的東西。 + +如果有些東西看起來很有趣且對你的專案很有用的話再去讀它,否則你可能可以跳過它們。 + +/// tip + +如果你想要以結構化的方式**學習 FastAPI**(推薦),請前往[教學 - 使用者指南](../tutorial/index.md){.internal-link target=_blank}逐章閱讀。 + +/// diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index 9859d3c51..137a17284 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -5,11 +5,11 @@ FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +23,11 @@ **文件**: https://fastapi.tiangolo.com -**程式碼**: https://github.com/tiangolo/fastapi +**程式碼**: https://github.com/fastapi/fastapi --- -FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3.8+ 並採用標準 Python 型別提示。 +FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 並採用標準 Python 型別提示。 主要特點包含: @@ -63,7 +63,7 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3. "_[...] 近期大量的使用 **FastAPI**。 [...] 目前正在計畫在**微軟**團隊的**機器學習**服務中導入。其中一些正在整合到核心的 **Windows** 產品和一些 **Office** 產品。_" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -87,7 +87,7 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3. "_老實說,你建造的東西看起來非常堅固和精緻。在很多方面,這就是我想要的,看到有人建造它真的很鼓舞人心。_" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -115,8 +115,6 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3. ## 安裝需求 -Python 3.8+ - FastAPI 是站在以下巨人的肩膀上: - Starlette 負責網頁的部分 @@ -331,7 +329,7 @@ def update_item(item_id: int, item: Item): 你不需要學習新的語法、類別、方法或函式庫等等。 -只需要使用 **Python 3.8 以上的版本**。 +只需要使用 **Python 以上的版本**。 舉個範例,比如宣告 int 的型別: @@ -445,7 +443,7 @@ item: Item 用於 Pydantic: -- email_validator - 用於電子郵件驗證。 +- email-validator - 用於電子郵件驗證。 - pydantic-settings - 用於設定管理。 - pydantic-extra-types - 用於與 Pydantic 一起使用的額外型別。 @@ -456,12 +454,12 @@ item: Item - python-multipart - 需要使用 `request.form()` 對表單進行 "解析" 時安裝。 - itsdangerous - 需要使用 `SessionMiddleware` 支援時安裝。 - pyyaml - 用於支援 Starlette 的 `SchemaGenerator` (如果你使用 FastAPI,可能不需要它)。 -- ujson - 使用 `UJSONResponse` 時必須安裝。 用於 FastAPI / Starlette: - uvicorn - 用於加載和運行應用程式的服務器。 - orjson - 使用 `ORJSONResponse`時必須安裝。 +- ujson - 使用 `UJSONResponse` 時必須安裝。 你可以使用 `pip install "fastapi[all]"` 來安裝這些所有依賴套件。 diff --git a/docs/zh-hant/docs/resources/index.md b/docs/zh-hant/docs/resources/index.md new file mode 100644 index 000000000..f4c70a3a0 --- /dev/null +++ b/docs/zh-hant/docs/resources/index.md @@ -0,0 +1,3 @@ +# 資源 + +額外的資源、外部連結、文章等。 ✈️ diff --git a/docs/zh-hant/docs/tutorial/index.md b/docs/zh-hant/docs/tutorial/index.md new file mode 100644 index 000000000..2aaa78b22 --- /dev/null +++ b/docs/zh-hant/docs/tutorial/index.md @@ -0,0 +1,102 @@ +# 教學 - 使用者指南 + +本教學將一步一步展示如何使用 **FastAPI** 及其大多數功能。 + +每個部分都是在前一部分的基礎上逐步建置的,但內容結構是按主題分開的,因此你可以直接跳到任何特定的部分,解決你具體的 API 需求。 + +它也被設計成可作為未來的參考,讓你隨時回來查看所需的內容。 + +## 運行程式碼 + +所有程式碼區塊都可以直接複製和使用(它們實際上是經過測試的 Python 檔案)。 + +要運行任何範例,請將程式碼複製到 `main.py` 檔案,並使用以下命令啟動 `fastapi dev`: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. + +``` + +
+ +**強烈建議**你編寫或複製程式碼、進行修改並在本地端運行。 + +在編輯器中使用它,才能真正體會到 FastAPI 的好處,可以看到你只需編寫少量程式碼,以及所有的型別檢查、自動補齊等功能。 + +--- + +## 安裝 FastAPI + +第一步是安裝 FastAPI。 + +確保你建立一個[虛擬環境](../virtual-environments.md){.internal-link target=_blank},啟用它,然後**安裝 FastAPI**: + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +/// note + +當你使用 `pip install "fastapi[standard]"` 安裝時,會包含一些預設的可選標準相依項。 + +如果你不想包含那些可選的相依項,你可以使用 `pip install fastapi` 來安裝。 + +/// + +## 進階使用者指南 + +還有一個**進階使用者指南**你可以稍後閱讀。 + +**進階使用者指南**建立在這個教學之上,使用相同的概念,並教你一些額外的功能。 + +但首先你應該閱讀**教學 - 使用者指南**(你正在閱讀的內容)。 + +它被設計成你可以使用**教學 - 使用者指南**來建立一個完整的應用程式,然後根據你的需求,使用一些額外的想法來擴展它。 diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md index 2a1e1ed89..362ef9460 100644 --- a/docs/zh/docs/advanced/additional-responses.md +++ b/docs/zh/docs/advanced/additional-responses.md @@ -16,23 +16,25 @@ **FastAPI**将采用该模型,生成其`JSON Schema`并将其包含在`OpenAPI`中的正确位置。 例如,要声明另一个具有状态码 `404` 和`Pydantic`模型 `Message` 的响应,可以写: -```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note + +请记住,您必须直接返回 `JSONResponse` 。 +/// -!!! Note - 请记住,您必须直接返回 `JSONResponse` 。 +/// info -!!! Info - `model` 密钥不是OpenAPI的一部分。 - **FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。 - - 正确的位置是: - - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含: - - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含: - - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。 - - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。 +`model` 密钥不是OpenAPI的一部分。 +**FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。 +- 正确的位置是: + - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含: + - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含: + - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。 + - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。 +/// **在OpenAPI中为该路径操作生成的响应将是:** @@ -159,16 +161,20 @@ 例如,您可以添加一个额外的媒体类型` image/png` ,声明您的路径操作可以返回JSON对象(媒体类型 `application/json` )或PNG图像: -```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note -!!! Note - - 请注意,您必须直接使用 `FileResponse` 返回图像。 +- 请注意,您必须直接使用 `FileResponse` 返回图像。 -!!! Info - - 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。 - - 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。 +/// + +/// info + +- 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。 +- 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。 + +/// ## 组合信息 您还可以联合接收来自多个位置的响应信息,包括 `response_model `、 `status_code` 和 `responses `参数。 @@ -181,9 +187,7 @@ 以及一个状态码为 `200` 的响应,它使用您的 `response_model` ,但包含自定义的 `example` : -```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} 所有这些都将被合并并包含在您的OpenAPI中,并在API文档中显示: @@ -209,9 +213,7 @@ new_dict = {**old_dict, "new key": "new value"} ``` 您可以使用该技术在路径操作中重用一些预定义的响应,并将它们与其他自定义响应相结合。 **例如:** -```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## 有关OpenAPI响应的更多信息 要了解您可以在响应中包含哪些内容,您可以查看OpenAPI规范中的以下部分: diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md index 54ec9775b..b8f9b0837 100644 --- a/docs/zh/docs/advanced/additional-status-codes.md +++ b/docs/zh/docs/advanced/additional-status-codes.md @@ -15,20 +15,26 @@ 要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为为你要的值。 ```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} +{!../../docs_src/additional_status_codes/tutorial001.py!} ``` -!!! warning "警告" - 当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。 +/// warning | 警告 - FastAPI 不会用模型等对该响应进行序列化。 +当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。 - 确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。 +FastAPI 不会用模型等对该响应进行序列化。 -!!! note "技术细节" - 你也可以使用 `from starlette.responses import JSONResponse`。  +确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。 - 出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。 +/// + +/// note | 技术细节 + +你也可以使用 `from starlette.responses import JSONResponse`。  + +出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。 + +/// ## OpenAPI 和 API 文档 diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md index b2f6e3559..bd37ecebb 100644 --- a/docs/zh/docs/advanced/advanced-dependencies.md +++ b/docs/zh/docs/advanced/advanced-dependencies.md @@ -19,7 +19,7 @@ Python 可以把类实例变为**可调用项**。 为此,需要声明 `__call__` 方法: ```Python hl_lines="10" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` 本例中,**FastAPI** 使用 `__call__` 检查附加参数及子依赖项,稍后,还要调用它向*路径操作函数*传递值。 @@ -29,7 +29,7 @@ Python 可以把类实例变为**可调用项**。 接下来,使用 `__init__` 声明用于**参数化**依赖项的实例参数: ```Python hl_lines="7" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` 本例中,**FastAPI** 不使用 `__init__`,我们要直接在代码中使用。 @@ -39,7 +39,7 @@ Python 可以把类实例变为**可调用项**。 使用以下代码创建类实例: ```Python hl_lines="16" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` 这样就可以**参数化**依赖项,它包含 `checker.fixed_content` 的属性 - `"bar"`。 @@ -57,15 +57,17 @@ checker(q="somequery") ……并用*路径操作函数*的参数 `fixed_content_included` 返回依赖项的值: ```Python hl_lines="20" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` -!!! tip "提示" +/// tip | 提示 - 本章示例有些刻意,也看不出有什么用处。 +本章示例有些刻意,也看不出有什么用处。 - 这个简例只是为了说明高级依赖项的运作机制。 +这个简例只是为了说明高级依赖项的运作机制。 - 在有关安全的章节中,工具函数将以这种方式实现。 +在有关安全的章节中,工具函数将以这种方式实现。 - 只要能理解本章内容,就能理解安全工具背后的运行机制。 +只要能理解本章内容,就能理解安全工具背后的运行机制。 + +/// diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md index 738bd7119..5ed6baa82 100644 --- a/docs/zh/docs/advanced/behind-a-proxy.md +++ b/docs/zh/docs/advanced/behind-a-proxy.md @@ -37,9 +37,11 @@ browser --> proxy proxy --> server ``` -!!! tip "提示" +/// tip | 提示 - IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。 +IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。 + +/// API 文档还需要 OpenAPI 概图声明 API `server` 位于 `/api/v1`(使用代理时的 URL)。例如: @@ -76,11 +78,13 @@ $ uvicorn main:app --root-path /api/v1 Hypercorn 也支持 `--root-path `选项。 -!!! note "技术细节" +/// note | 技术细节 + +ASGI 规范定义的 `root_path` 就是为了这种用例。 - ASGI 规范定义的 `root_path` 就是为了这种用例。 +并且 `--root-path` 命令行选项支持 `root_path`。 - 并且 `--root-path` 命令行选项支持 `root_path`。 +/// ### 查看当前的 `root_path` @@ -89,7 +93,7 @@ Hypercorn 也支持 `--root-path `选项。 我们在这里的信息里包含 `roo_path` 只是为了演示。 ```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` 然后,用以下命令启动 Uvicorn: @@ -118,7 +122,7 @@ $ uvicorn main:app --root-path /api/v1 还有一种方案,如果不能提供 `--root-path` 或等效的命令行选项,则在创建 FastAPI 应用时要设置 `root_path` 参数。 ```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} +{!../../docs_src/behind_a_proxy/tutorial002.py!} ``` 传递 `root_path` 给 `FastAPI` 与传递 `--root-path` 命令行选项给 Uvicorn 或 Hypercorn 一样。 @@ -168,9 +172,11 @@ Uvicorn 预期代理在 `http://127.0.0.1:8000/app` 访问 Uvicorn,而在顶 这个文件把 Traefik 监听端口设置为 `9999`,并设置要使用另一个文件 `routes.toml`。 -!!! tip "提示" +/// tip | 提示 - 使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。 +使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。 + +/// 接下来,创建 `routes.toml`: @@ -236,9 +242,11 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip "提示" +/// tip | 提示 + +注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。 - 注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。 +/// 打开含 Traefik 端口的 URL,包含路径前缀:http://127.0.0.1:9999/api/v1/app。 @@ -281,9 +289,11 @@ $ uvicorn main:app --root-path /api/v1 ## 附加的服务器 -!!! warning "警告" +/// warning | 警告 - 此用例较难,可以跳过。 +此用例较难,可以跳过。 + +/// 默认情况下,**FastAPI** 使用 `root_path` 的链接在 OpenAPI 概图中创建 `server`。 @@ -294,7 +304,7 @@ $ uvicorn main:app --root-path /api/v1 例如: ```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} +{!../../docs_src/behind_a_proxy/tutorial003.py!} ``` 这段代码生产如下 OpenAPI 概图: @@ -322,30 +332,34 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip "提示" +/// tip | 提示 + +注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。 - 注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。 +/// http://127.0.0.1:9999/api/v1/docs 的 API 文档所示如下: -!!! tip "提示" +/// tip | 提示 + +API 文档与所选的服务器进行交互。 - API 文档与所选的服务器进行交互。 +/// ### 从 `root_path` 禁用自动服务器 如果不想让 **FastAPI** 包含使用 `root_path` 的自动服务器,则要使用参数 `root_path_in_servers=False`: ```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} +{!../../docs_src/behind_a_proxy/tutorial004.py!} ``` 这样,就不会在 OpenAPI 概图中包含服务器了。 ## 挂载子应用 -如需挂载子应用(详见 [子应用 - 挂载](./sub-applications.md){.internal-link target=_blank}),也要通过 `root_path` 使用代理,这与正常应用一样,别无二致。 +如需挂载子应用(详见 [子应用 - 挂载](sub-applications.md){.internal-link target=_blank}),也要通过 `root_path` 使用代理,这与正常应用一样,别无二致。 FastAPI 在内部使用 `root_path`,因此子应用也可以正常运行。✨ diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md index 155ce2882..85ca1d06d 100644 --- a/docs/zh/docs/advanced/custom-response.md +++ b/docs/zh/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ 并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。 -!!! note "说明" - 如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。 +/// note | 说明 + +如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。 + +/// ## 使用 `ORJSONResponse` @@ -22,20 +25,24 @@ 导入你想要使用的 `Response` 类(子类)然后在 *路径操作装饰器* 中声明它。 ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` -!!! info "提示" - 参数 `response_class` 也会用来定义响应的「媒体类型」。 +/// info | 提示 + +参数 `response_class` 也会用来定义响应的「媒体类型」。 - 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。 +在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。 - 并且在 OpenAPI 文档中也会这样记录。 +并且在 OpenAPI 文档中也会这样记录。 -!!! tip "小贴士" - `ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。 +/// +/// tip | 小贴士 +`ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。 + +/// ## HTML 响应 @@ -45,15 +52,18 @@ * 将 `HTMLResponse` 作为你的 *路径操作* 的 `response_class` 参数传入。 ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` -!!! info "提示" - 参数 `response_class` 也会用来定义响应的「媒体类型」。 +/// info | 提示 + +参数 `response_class` 也会用来定义响应的「媒体类型」。 - 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。 +在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。 - 并且在 OpenAPI 文档中也会这样记录。 +并且在 OpenAPI 文档中也会这样记录。 + +/// ### 返回一个 `Response` @@ -62,14 +72,20 @@ 和上面一样的例子,返回一个 `HTMLResponse` 看起来可能是这样: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` -!!! warning "警告" - *路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。 +/// warning | 警告 + +*路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。 + +/// + +/// info | 提示 -!!! info "提示" - 当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。 +当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。 + +/// ### OpenAPI 中的文档和重载 `Response` @@ -82,7 +98,7 @@ 比如像这样: ```Python hl_lines="7 23 21" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` 在这个例子中,函数 `generate_html_response()` 已经生成并返回 `Response` 对象而不是在 `str` 中返回 HTML。 @@ -99,10 +115,13 @@ 要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。 -!!! note "技术细节" - 你也可以使用 `from starlette.responses import HTMLResponse`。 +/// note | 技术细节 + +你也可以使用 `from starlette.responses import HTMLResponse`。 + +**FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。 - **FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。 +/// ### `Response` @@ -121,7 +140,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -133,7 +152,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 接受文本或字节并返回纯文本响应。 ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -151,22 +170,28 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 `UJSONResponse` 是一个使用 `ujson` 的可选 JSON 响应。 -!!! warning "警告" - 在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。 +/// warning | 警告 + +在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。 + +/// ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} +{!../../docs_src/custom_response/tutorial001.py!} ``` -!!! tip "小贴士" - `ORJSONResponse` 可能是一个更快的选择。 +/// tip | 小贴士 + +`ORJSONResponse` 可能是一个更快的选择。 + +/// ### `RedirectResponse` 返回 HTTP 重定向。默认情况下使用 307 状态代码(临时重定向)。 ```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} +{!../../docs_src/custom_response/tutorial006.py!} ``` ### `StreamingResponse` @@ -174,7 +199,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 采用异步生成器或普通生成器/迭代器,然后流式传输响应主体。 ```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} +{!../../docs_src/custom_response/tutorial007.py!} ``` #### 对类似文件的对象使用 `StreamingResponse` @@ -184,11 +209,14 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 包括许多与云存储,视频处理等交互的库。 ```Python hl_lines="2 10-12 14" -{!../../../docs_src/custom_response/tutorial008.py!} +{!../../docs_src/custom_response/tutorial008.py!} ``` -!!! tip "小贴士" - 注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。 +/// tip | 小贴士 + +注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。 + +/// ### `FileResponse` @@ -204,7 +232,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 文件响应将包含适当的 `Content-Length`,`Last-Modified` 和 `ETag` 的响应头。 ```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} +{!../../docs_src/custom_response/tutorial009.py!} ``` ## 额外文档 diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md index 5a93877cc..7d977a0c7 100644 --- a/docs/zh/docs/advanced/dataclasses.md +++ b/docs/zh/docs/advanced/dataclasses.md @@ -5,7 +5,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 但 FastAPI 还可以使用数据类(`dataclasses`): ```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} +{!../../docs_src/dataclasses/tutorial001.py!} ``` 这还是借助于 **Pydantic** 及其内置的 `dataclasses`。 @@ -20,20 +20,22 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。 -!!! info "说明" +/// info | 说明 - 注意,数据类不支持 Pydantic 模型的所有功能。 +注意,数据类不支持 Pydantic 模型的所有功能。 - 因此,开发时仍需要使用 Pydantic 模型。 +因此,开发时仍需要使用 Pydantic 模型。 - 但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓 +但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓 + +/// ## `response_model` 使用数据类 在 `response_model` 参数中使用 `dataclasses`: ```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} +{!../../docs_src/dataclasses/tutorial002.py!} ``` 本例把数据类自动转换为 Pydantic 数据类。 @@ -51,7 +53,7 @@ API 文档中也会显示相关概图: 本例把标准的 `dataclasses` 直接替换为 `pydantic.dataclasses`: ```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} +{!../../docs_src/dataclasses/tutorial003.py!} ``` 1. 本例依然要从标准的 `dataclasses` 中导入 `field`; diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index 6017b8ef0..a34c03f3f 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -4,16 +4,18 @@ 事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。 -!!! warning "警告" +/// warning | 警告 - **FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](./sub-applications.md){.internal-link target=_blank}中的事件处理器。 +**FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。 + +/// ## `startup` 事件 使用 `startup` 事件声明 `app` 启动前运行的函数: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` 本例中,`startup` 事件处理器函数为项目数据库(只是**字典**)提供了一些初始值。 @@ -27,25 +29,31 @@ 使用 `shutdown` 事件声明 `app` 关闭时运行的函数: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` 此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 -!!! info "说明" +/// info | 说明 + +`open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。 + +/// + +/// tip | 提示 - `open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。 +注意,本例使用 Python `open()` 标准函数与文件交互。 -!!! tip "提示" +这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。 - 注意,本例使用 Python `open()` 标准函数与文件交互。 +但 `open()` 函数不支持使用 `async` 与 `await`。 - 这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。 +因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。 - 但 `open()` 函数不支持使用 `async` 与 `await`。 +/// - 因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。 +/// info | 说明 -!!! info "说明" +有关事件处理器的详情,请参阅 Starlette 官档 - 事件。 - 有关事件处理器的详情,请参阅 Starlette 官档 - 事件。 +/// diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md index e222e479c..baf131361 100644 --- a/docs/zh/docs/advanced/generate-clients.md +++ b/docs/zh/docs/advanced/generate-clients.md @@ -10,23 +10,27 @@ 一个常见的工具是 OpenAPI Generator。 -如果您正在开发**前端**,一个非常有趣的替代方案是 openapi-typescript-codegen。 +如果您正在开发**前端**,一个非常有趣的替代方案是 openapi-ts。 ## 生成一个 TypeScript 前端客户端 让我们从一个简单的 FastAPI 应用开始: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +```Python hl_lines="7-9 12-13 16-17 21" +{!> ../../docs_src/generate_clients/tutorial001_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9-11 14-15 18 19 23" +{!> ../../docs_src/generate_clients/tutorial001.py!} +``` - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +//// 请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。 @@ -46,14 +50,14 @@ OpenAPI中所包含的模型里有相同的信息可以用于 **生成客户端 现在我们有了带有模型的应用,我们可以为前端生成客户端代码。 -#### 安装 `openapi-typescript-codegen` +#### 安装 `openapi-ts` -您可以使用以下工具在前端代码中安装 `openapi-typescript-codegen`: +您可以使用以下工具在前端代码中安装 `openapi-ts`:
```console -$ npm install openapi-typescript-codegen --save-dev +$ npm install @hey-api/openapi-ts --save-dev ---> 100% ``` @@ -62,7 +66,7 @@ $ npm install openapi-typescript-codegen --save-dev #### 生成客户端代码 -要生成客户端代码,您可以使用现在将要安装的命令行应用程序 `openapi`。 +要生成客户端代码,您可以使用现在将要安装的命令行应用程序 `openapi-ts`。 因为它安装在本地项目中,所以您可能无法直接使用此命令,但您可以将其放在 `package.json` 文件中。 @@ -75,12 +79,12 @@ $ npm install openapi-typescript-codegen --save-dev "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios" + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -94,7 +98,7 @@ $ npm install openapi-typescript-codegen --save-dev $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios ```
@@ -111,8 +115,11 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app -!!! tip - 请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。 +/// tip + +请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。 + +/// 如果发送的数据字段不符,你也会看到编辑器的错误提示: @@ -128,17 +135,21 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="21 26 34" +{!> ../../docs_src/generate_clients/tutorial002_py39.py!} +``` + +//// - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="23 28 36" +{!> ../../docs_src/generate_clients/tutorial002.py!} +``` - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +//// ### 生成带有标签的 TypeScript 客户端 @@ -185,17 +196,21 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +```Python hl_lines="6-7 10" +{!> ../../docs_src/generate_clients/tutorial003_py39.py!} +``` -=== "Python 3.8+" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8-9 12" +{!> ../../docs_src/generate_clients/tutorial003.py!} +``` - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +//// ### 使用自定义操作ID生成TypeScript客户端 @@ -218,7 +233,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 我们可以将 OpenAPI JSON 下载到一个名为`openapi.json`的文件中,然后使用以下脚本**删除此前缀的标签**: ```Python -{!../../../docs_src/generate_clients/tutorial004.py!} +{!../../docs_src/generate_clients/tutorial004.py!} ``` 通过这样做,操作ID将从类似于 `items-get_items` 的名称重命名为 `get_items` ,这样客户端生成器就可以生成更简洁的方法名称。 @@ -234,12 +249,12 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios" + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } diff --git a/docs/zh/docs/advanced/index.md b/docs/zh/docs/advanced/index.md index e39eed805..6525802fc 100644 --- a/docs/zh/docs/advanced/index.md +++ b/docs/zh/docs/advanced/index.md @@ -6,10 +6,13 @@ 你会在接下来的章节中了解到其他的选项、配置以及额外的特性。 -!!! tip - 接下来的章节**并不一定是**「高级的」。 +/// tip - 而且对于你的使用场景来说,解决方案很可能就在其中。 +接下来的章节**并不一定是**「高级的」。 + +而且对于你的使用场景来说,解决方案很可能就在其中。 + +/// ## 先阅读教程 diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 06232fe17..78a7d559c 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -43,11 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。 -!!! note "技术细节" +/// note | 技术细节 - 以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 +以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 - **FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。 +**FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。 + +/// ## `HTTPSRedirectMiddleware` @@ -56,7 +58,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。 ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} +{!../../docs_src/advanced_middleware/tutorial001.py!} ``` ## `TrustedHostMiddleware` @@ -64,7 +66,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。 ```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} +{!../../docs_src/advanced_middleware/tutorial002.py!} ``` 支持以下参数: @@ -80,7 +82,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 中间件会处理标准响应与流响应。 ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} +{!../../docs_src/advanced_middleware/tutorial003.py!} ``` 支持以下参数: @@ -93,7 +95,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 例如: -* Sentry * Uvicorn 的 `ProxyHeadersMiddleware` * MessagePack diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md index e2dadbfb0..601cbdb5d 100644 --- a/docs/zh/docs/advanced/openapi-callbacks.md +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -32,12 +32,14 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建 这部分代码很常规,您对绝大多数代码应该都比较熟悉了: ```Python hl_lines="10-14 37-54" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "提示" +/// tip | 提示 - `callback_url` 查询参数使用 Pydantic 的 URL 类型。 +`callback_url` 查询参数使用 Pydantic 的 URL 类型。 + +/// 此处唯一比较新的内容是*路径操作装饰器*中的 `callbacks=invoices_callback_router.routes` 参数,下文介绍。 @@ -62,11 +64,13 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 本例没有实现回调本身(只是一行代码),只有文档部分。 -!!! tip "提示" +/// tip | 提示 + +实际的回调只是 HTTP 请求。 - 实际的回调只是 HTTP 请求。 +实现回调时,要使用 HTTPXRequests。 - 实现回调时,要使用 HTTPXRequests。 +/// ## 编写回调文档代码 @@ -76,18 +80,20 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。 -!!! tip "提示" +/// tip | 提示 + +编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 - 编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 +临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。 - 临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。 +/// ### 创建回调的 `APIRouter` 首先,新建包含一些用于回调的 `APIRouter`。 ```Python hl_lines="5 26" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### 创建回调*路径操作* @@ -100,7 +106,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) * 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived` ```Python hl_lines="17-19 22-23 29-33" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` 回调*路径操作*与常规*路径操作*有两点主要区别: @@ -157,9 +163,11 @@ JSON 请求体包含如下内容: } ``` -!!! tip "提示" +/// tip | 提示 - 注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 +注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 + +/// ### 添加回调路由 @@ -168,12 +176,14 @@ JSON 请求体包含如下内容: 现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**): ```Python hl_lines="36" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` -!!! tip "提示" +/// tip | 提示 + +注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 - 注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 +/// ### 查看文档 diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md index 7da9f251e..0d77dd69e 100644 --- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md @@ -2,15 +2,18 @@ ## OpenAPI 的 operationId -!!! warning - 如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。 +/// warning + +如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。 + +/// 你可以在路径操作中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。 务必确保每个操作路径的 `operation_id` 都是唯一的。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### 使用 *路径操作函数* 的函数名作为 operationId @@ -20,23 +23,29 @@ 你应该在添加了所有 *路径操作* 之后执行此操作。 ```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -!!! tip - 如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。 +/// tip + +如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。 + +/// + +/// warning + +如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。 -!!! warning - 如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。 +即使它们在不同的模块中(Python 文件)。 - 即使它们在不同的模块中(Python 文件)。 +/// ## 从 OpenAPI 中排除 使用参数 `include_in_schema` 并将其设置为 `False` ,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了)。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## docstring 的高级描述 @@ -49,5 +58,5 @@ ```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md index a289cf201..c38f80f1f 100644 --- a/docs/zh/docs/advanced/response-change-status-code.md +++ b/docs/zh/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ 然后你可以在这个*临时*响应对象中设置`status_code`。 ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md index 3e53c5319..2d56c6e9b 100644 --- a/docs/zh/docs/advanced/response-cookies.md +++ b/docs/zh/docs/advanced/response-cookies.md @@ -5,7 +5,7 @@ 你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。 ```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} +{!../../docs_src/response_cookies/tutorial002.py!} ``` 而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。 @@ -25,23 +25,29 @@ 然后设置Cookies,并返回: ```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} +{!../../docs_src/response_cookies/tutorial001.py!} ``` -!!! tip - 需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。 +/// tip - 所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。 +需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。 - 同时,你也应当仅反馈通过`response_model`过滤过的数据。 +所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。 + +同时,你也应当仅反馈通过`response_model`过滤过的数据。 + +/// ### 更多信息 -!!! note "技术细节" - 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 +/// note | 技术细节 + +你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 + +为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。 - 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。 +因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。 - 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。 +/// 如果你想查看所有可用的参数和选项,可以参考 Starlette帮助文档 diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md index 797a878eb..934f60ef6 100644 --- a/docs/zh/docs/advanced/response-directly.md +++ b/docs/zh/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。 -!!! tip "小贴士" - `JSONResponse` 本身是一个 `Response` 的子类。 +/// tip | 小贴士 + +`JSONResponse` 本身是一个 `Response` 的子类。 + +/// 当你返回一个 `Response` 时,**FastAPI** 会直接传递它。 @@ -33,13 +36,16 @@ ```Python hl_lines="4 6 20 21" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` -!!! note "技术细节" - 你也可以使用 `from starlette.responses import JSONResponse`。 +/// note | 技术细节 + +你也可以使用 `from starlette.responses import JSONResponse`。 + +出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。 - 出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。 +/// ## 返回自定义 `Response` @@ -52,7 +58,7 @@ 你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。 ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ## 说明 diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index 85dab15ac..e7861ad0c 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -6,7 +6,7 @@ 然后你可以在这个*临时*响应对象中设置头部。 ```Python hl_lines="1 7-8" -{!../../../docs_src/response_headers/tutorial002.py!} +{!../../docs_src/response_headers/tutorial002.py!} ``` 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 @@ -21,16 +21,19 @@ 按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递: ```Python hl_lines="10-12" -{!../../../docs_src/response_headers/tutorial001.py!} +{!../../docs_src/response_headers/tutorial001.py!} ``` -!!! 注意 "技术细节" - 你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 +/// note | 技术细节 - **FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。 +你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 - 由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。 +**FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。 + +由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。 + +/// ## 自定义头部 diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md index 1f251ca45..06c6dbbab 100644 --- a/docs/zh/docs/advanced/security/http-basic-auth.md +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -14,16 +14,42 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 ## 简单的 HTTP 基础授权 -* 导入 `HTTPBsic` 与 `HTTPBasicCredentials` -* 使用 `HTTPBsic` 创建**安全概图** +* 导入 `HTTPBasic` 与 `HTTPBasicCredentials` +* 使用 `HTTPBasic` 创建**安全概图** * 在*路径操作*的依赖项中使用 `security` * 返回类型为 `HTTPBasicCredentials` 的对象: * 包含发送的 `username` 与 `password` +//// tab | Python 3.9+ + +```Python hl_lines="4 8 12" +{!> ../../docs_src/security/tutorial006_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 7 11" +{!> ../../docs_src/security/tutorial006_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + ```Python hl_lines="2 6 10" -{!../../../docs_src/security/tutorial006.py!} +{!> ../../docs_src/security/tutorial006.py!} ``` +//// + 第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: @@ -34,13 +60,45 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 使用依赖项检查用户名与密码是否正确。 -为此要使用 Python 标准模块 `secrets` 检查用户名与密码: +为此要使用 Python 标准模块 `secrets` 检查用户名与密码。 + +`secrets.compare_digest()` 需要仅包含 ASCII 字符(英语字符)的 `bytes` 或 `str`,这意味着它不适用于像`á`一样的字符,如 `Sebastián`。 + +为了解决这个问题,我们首先将 `username` 和 `password` 转换为使用 UTF-8 编码的 `bytes` 。 + +然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。 + +//// tab | Python 3.9+ + +```Python hl_lines="1 12-24" +{!> ../../docs_src/security/tutorial007_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -```Python hl_lines="1 11-13" -{!../../../docs_src/security/tutorial007.py!} +```Python hl_lines="1 12-24" +{!> ../../docs_src/security/tutorial007_an.py!} ``` -这段代码确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。与以下代码类似: +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1 11-21" +{!> ../../docs_src/security/tutorial007.py!} +``` + +//// + +这类似于: ```Python if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): @@ -102,6 +160,32 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": 检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: -```Python hl_lines="15-19" -{!../../../docs_src/security/tutorial007.py!} +//// tab | Python 3.9+ + +```Python hl_lines="26-30" +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="26-30" +{!> ../../docs_src/security/tutorial007_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="23-27" +{!> ../../docs_src/security/tutorial007.py!} +``` + +//// diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md index e2bef4765..267e7ced7 100644 --- a/docs/zh/docs/advanced/security/index.md +++ b/docs/zh/docs/advanced/security/index.md @@ -4,10 +4,13 @@ 除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性. -!!! tip "小贴士" - 接下来的章节 **并不一定是 "高级的"**. +/// tip | 小贴士 - 而且对于你的使用场景来说,解决方案很可能就在其中。 +接下来的章节 **并不一定是 "高级的"**. + +而且对于你的使用场景来说,解决方案很可能就在其中。 + +/// ## 先阅读教程 diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md index e5eeffb0a..b26522113 100644 --- a/docs/zh/docs/advanced/security/oauth2-scopes.md +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -10,19 +10,21 @@ OAuth2 也是脸书、谷歌、GitHub、微软、推特等第三方身份验证 本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。 -!!! warning "警告" +/// warning | 警告 - 本章内容较难,刚接触 FastAPI 的新手可以跳过。 +本章内容较难,刚接触 FastAPI 的新手可以跳过。 - OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。 +OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。 - 但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。 +但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。 - 不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。 +不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。 - 很多情况下,OAuth2 作用域就像一把牛刀。 +很多情况下,OAuth2 作用域就像一把牛刀。 - 但如果您确定要使用作用域,或对它有兴趣,请继续阅读。 +但如果您确定要使用作用域,或对它有兴趣,请继续阅读。 + +/// ## OAuth2 作用域与 OpenAPI @@ -44,22 +46,24 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 * 脸书和 Instagram 使用 `instagram_basic` * 谷歌使用 `https://www.googleapis.com/auth/drive` -!!! info "说明" +/// info | 说明 + +OAuth2 中,**作用域**只是声明特定权限的字符串。 - OAuth2 中,**作用域**只是声明特定权限的字符串。 +是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 - 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 +这些细节只是特定的实现方式。 - 这些细节只是特定的实现方式。 +对 OAuth2 来说,它们都只是字符串而已。 - 对 OAuth2 来说,它们都只是字符串而已。 +/// ## 全局纵览 首先,快速浏览一下以下代码与**用户指南**中 [OAuth2 实现密码哈希与 Bearer JWT 令牌验证](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}一章中代码的区别。以下代码使用 OAuth2 作用域: ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` 下面,我们逐步说明修改的代码内容。 @@ -71,7 +75,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 `scopes` 参数接收**字典**,键是作用域、值是作用域的描述: ```Python hl_lines="62-65" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` 因为声明了作用域,所以登录或授权时会在 API 文档中显示。 @@ -90,14 +94,16 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 这样,返回的 JWT 令牌中就包含了作用域。 -!!! danger "危险" +/// danger | 危险 - 为了简明起见,本例把接收的作用域直接添加到了令牌里。 +为了简明起见,本例把接收的作用域直接添加到了令牌里。 - 但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。 +但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。 + +/// ```Python hl_lines="153" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 在*路径操作*与依赖项中声明作用域 @@ -116,23 +122,27 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 本例要求使用作用域 `me`(还可以使用更多作用域)。 -!!! note "笔记" +/// note | 笔记 + +不必在不同位置添加不同的作用域。 - 不必在不同位置添加不同的作用域。 +本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。 - 本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。 +/// ```Python hl_lines="4 139 166" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` -!!! info "技术细节" +/// info | 技术细节 - `Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 +`Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 - 但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。 +但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。 - 但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。 +但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。 + +/// ## 使用 `SecurityScopes` @@ -149,7 +159,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 `SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。 ```Python hl_lines="8 105" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 使用 `scopes` @@ -165,7 +175,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。 ```Python hl_lines="105 107-115" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 校验 `username` 与数据形状 @@ -183,7 +193,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。 ```Python hl_lines="46 116-127" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 校验 `scopes` @@ -193,7 +203,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。 ```Python hl_lines="128-134" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 依赖项树与作用域 @@ -221,11 +231,13 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 * `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明 * `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope` -!!! tip "提示" +/// tip | 提示 + +此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 - 此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 +所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。 - 所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。 +/// ## `SecurityScopes` 的更多细节 @@ -263,11 +275,13 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。 -!!! note "笔记" +/// note | 笔记 + +每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 - 每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 +但归根结底,它们使用的都是 OAuth2 标准。 - 但归根结底,它们使用的都是 OAuth2 标准。 +/// **FastAPI** 的 `fastapi.security.oauth2` 里包含了所有 OAuth2 身份验证流工具。 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index d793b9c7f..4d35731cb 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -8,44 +8,51 @@ ## 环境变量 -!!! tip - 如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。 +/// tip + +如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。 + +/// 环境变量(也称为"env var")是一种存在于 Python 代码之外、存在于操作系统中的变量,可以被您的 Python 代码(或其他程序)读取。 您可以在 shell 中创建和使用环境变量,而无需使用 Python: -=== "Linux、macOS、Windows Bash" +//// tab | Linux、macOS、Windows Bash + +
+ +```console +// 您可以创建一个名为 MY_NAME 的环境变量 +$ export MY_NAME="Wade Wilson" -
+// 然后您可以与其他程序一起使用它,例如 +$ echo "Hello $MY_NAME" - ```console - // 您可以创建一个名为 MY_NAME 的环境变量 - $ export MY_NAME="Wade Wilson" +Hello Wade Wilson +``` - // 然后您可以与其他程序一起使用它,例如 - $ echo "Hello $MY_NAME" +
- Hello Wade Wilson - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +// 创建一个名为 MY_NAME 的环境变量 +$ $Env:MY_NAME = "Wade Wilson" - ```console - // 创建一个名为 MY_NAME 的环境变量 - $ $Env:MY_NAME = "Wade Wilson" +// 与其他程序一起使用它,例如 +$ echo "Hello $Env:MY_NAME" - // 与其他程序一起使用它,例如 - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +
-
+//// ### 在 Python 中读取环境变量 @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip - `os.getenv()` 的第二个参数是要返回的默认值。 +/// tip + +`os.getenv()` 的第二个参数是要返回的默认值。 - 如果没有提供默认值,默认为 `None`,此处我们提供了 `"World"` 作为要使用的默认值。 +如果没有提供默认值,默认为 `None`,此处我们提供了 `"World"` 作为要使用的默认值。 + +/// 然后,您可以调用该 Python 程序: @@ -116,8 +126,11 @@ Hello World from Python -!!! tip - 您可以在 Twelve-Factor App: Config 中阅读更多相关信息。 +/// tip + +您可以在 Twelve-Factor App: Config 中阅读更多相关信息。 + +/// ### 类型和验证 @@ -138,11 +151,14 @@ Hello World from Python 您可以使用与 Pydantic 模型相同的验证功能和工具,比如不同的数据类型和使用 `Field()` 进行附加验证。 ```Python hl_lines="2 5-8 11" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` -!!! tip - 如果您需要一个快速的复制粘贴示例,请不要使用此示例,而应使用下面的最后一个示例。 +/// tip + +如果您需要一个快速的复制粘贴示例,请不要使用此示例,而应使用下面的最后一个示例。 + +/// 然后,当您创建该 `Settings` 类的实例(在此示例中是 `settings` 对象)时,Pydantic 将以不区分大小写的方式读取环境变量,因此,大写的变量 `APP_NAME` 仍将为属性 `app_name` 读取。 @@ -153,7 +169,7 @@ Hello World from Python 然后,您可以在应用程序中使用新的 `settings` 对象: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### 运行服务器 @@ -170,8 +186,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app -!!! tip - 要为单个命令设置多个环境变量,只需用空格分隔它们,并将它们全部放在命令之前。 +/// tip + +要为单个命令设置多个环境变量,只需用空格分隔它们,并将它们全部放在命令之前。 + +/// 然后,`admin_email` 设置将为 `"deadpool@example.com"`。 @@ -186,16 +205,20 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 例如,您可以创建一个名为 `config.py` 的文件,其中包含以下内容: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` 然后在一个名为 `main.py` 的文件中使用它: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` -!!! tip - 您还需要一个名为 `__init__.py` 的文件,就像您在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。 + +/// tip + +您还需要一个名为 `__init__.py` 的文件,就像您在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。 + +/// ## 在依赖项中使用设置 @@ -208,7 +231,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 根据前面的示例,您的 `config.py` 文件可能如下所示: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` 请注意,现在我们不创建默认实例 `settings = Settings()`。 @@ -217,61 +240,82 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 现在我们创建一个依赖项,返回一个新的 `config.Settings()`。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6 12-13" +{!> ../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +```Python hl_lines="6 12-13" +{!> ../../docs_src/settings/app02_an/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ 非注解版本 - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// tip -=== "Python 3.8+ 非注解版本" +如果可能,请尽量使用 `Annotated` 版本。 - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +/// + +```Python hl_lines="5 11-12" +{!> ../../docs_src/settings/app02/main.py!} +``` - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +//// -!!! tip - 我们稍后会讨论 `@lru_cache`。 +/// tip - 目前,您可以将 `get_settings()` 视为普通函数。 +我们稍后会讨论 `@lru_cache`。 + +目前,您可以将 `get_settings()` 视为普通函数。 + +/// 然后,我们可以将其作为依赖项从“路径操作函数”中引入,并在需要时使用它。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="17 19-21" +{!> ../../docs_src/settings/app02_an_py39/main.py!} +``` + +//// - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 19-21" +{!> ../../docs_src/settings/app02_an/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +//// tab | Python 3.8+ 非注解版本 -=== "Python 3.8+ 非注解版本" +/// tip - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +如果可能,请尽量使用 `Annotated` 版本。 + +/// + +```Python hl_lines="16 18-20" +{!> ../../docs_src/settings/app02/main.py!} +``` - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +//// ### 设置和测试 然后,在测试期间,通过创建 `get_settings` 的依赖项覆盖,很容易提供一个不同的设置对象: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` 在依赖项覆盖中,我们在创建新的 `Settings` 对象时为 `admin_email` 设置了一个新值,然后返回该新对象。 @@ -284,15 +328,21 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 这种做法相当常见,有一个名称,这些环境变量通常放在一个名为 `.env` 的文件中,该文件被称为“dotenv”。 -!!! tip - 以点 (`.`) 开头的文件是 Unix-like 系统(如 Linux 和 macOS)中的隐藏文件。 +/// tip - 但是,dotenv 文件实际上不一定要具有确切的文件名。 +以点 (`.`) 开头的文件是 Unix-like 系统(如 Linux 和 macOS)中的隐藏文件。 + +但是,dotenv 文件实际上不一定要具有确切的文件名。 + +/// Pydantic 支持使用外部库从这些类型的文件中读取。您可以在Pydantic 设置: Dotenv (.env) 支持中阅读更多相关信息。 -!!! tip - 要使其工作,您需要执行 `pip install python-dotenv`。 +/// tip + +要使其工作,您需要执行 `pip install python-dotenv`。 + +/// ### `.env` 文件 @@ -308,13 +358,16 @@ APP_NAME="ChimichangApp" 然后,您可以使用以下方式更新您的 `config.py`: ```Python hl_lines="9-10" -{!../../../docs_src/settings/app03/config.py!} +{!../../docs_src/settings/app03/config.py!} ``` 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 -!!! tip - `Config` 类仅用于 Pydantic 配置。您可以在Pydantic Model Config中阅读更多相关信息。 +/// tip + +`Config` 类仅用于 Pydantic 配置。您可以在Pydantic Model Config中阅读更多相关信息。 + +/// ### 使用 `lru_cache` 仅创建一次 `Settings` @@ -339,26 +392,35 @@ def get_settings(): 但是,由于我们在顶部使用了 `@lru_cache` 装饰器,因此只有在第一次调用它时,才会创建 `Settings` 对象一次。 ✔️ -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="1 11" +{!> ../../docs_src/settings/app03_an_py39/main.py!} +``` + +//// - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 11" +{!> ../../docs_src/settings/app03_an/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` +//// tab | Python 3.8+ 非注解版本 -=== "Python 3.8+ 非注解版本" +/// tip - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +如果可能,请尽量使用 `Annotated` 版本。 + +/// + +```Python hl_lines="1 10" +{!> ../../docs_src/settings/app03/main.py!} +``` - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +//// 然后,在下一次请求的依赖项中对 `get_settings()` 进行任何后续调用时,它不会执行 `get_settings()` 的内部代码并创建新的 `Settings` 对象,而是返回在第一次调用时返回的相同对象,一次又一次。 diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md index 55651def5..f93ab1d24 100644 --- a/docs/zh/docs/advanced/sub-applications.md +++ b/docs/zh/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ 首先,创建主(顶层)**FastAPI** 应用及其*路径操作*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 子应用 @@ -21,7 +21,7 @@ 子应用只是另一个标准 FastAPI 应用,但这个应用是被**挂载**的应用: ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 挂载子应用 @@ -31,7 +31,7 @@ 本例的子应用挂载在 `/subapi` 路径下: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 查看文档 @@ -70,4 +70,4 @@ $ uvicorn main:app --reload 并且子应用还可以再挂载子应用,一切都会正常运行,FastAPI 可以自动处理所有 `root_path`。 -关于 `root_path` 及如何显式使用 `root_path` 的内容,详见[使用代理](./behind-a-proxy.md){.internal-link target=_blank}一章。 +关于 `root_path` 及如何显式使用 `root_path` 的内容,详见[使用代理](behind-a-proxy.md){.internal-link target=_blank}一章。 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index d735f1697..7692aa47b 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -20,75 +20,108 @@ $ pip install jinja2 -如需使用静态文件,还要安装 `aiofiles`: - -
- -```console -$ pip install aiofiles - ----> 100% -``` - -
- ## 使用 `Jinja2Templates` * 导入 `Jinja2Templates` * 创建可复用的 `templates` 对象 * 在返回模板的*路径操作*中声明 `Request` 参数 -* 使用 `templates` 渲染并返回 `TemplateResponse`, 以键值对方式在 Jinja2 的 **context** 中传递 `request` +* 使用 `templates` 渲染并返回 `TemplateResponse`, 传递模板的名称、request对象以及一个包含多个键值对(用于Jinja2模板)的"context"字典, ```Python hl_lines="4 11 15-16" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` -!!! note "笔记" +/// note | 笔记 + +在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。 +并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。 + +/// + +/// tip | 提示 - 注意,必须为 Jinja2 以键值对方式在上下文中传递 `request`。因此,还要在*路径操作*中声明。 +通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 -!!! tip "提示" +/// - 通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 +/// note | 技术细节 -!!! note "技术细节" +您还可以使用 `from starlette.templating import Jinja2Templates`。 - 您还可以使用 `from starlette.templating import Jinja2Templates`。 +**FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。 - **FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。 +/// ## 编写模板 编写模板 `templates/item.html`,代码如下: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} +``` + +### 模板上下文 + +在包含如下语句的html中: + +{% raw %} + +```jinja +Item ID: {{ id }} ``` -它会显示从 **context** 字典中提取的 `id`: +{% endraw %} + +...这将显示你从"context"字典传递的 `id`: ```Python -{"request": request, "id": id} +{"id": id} +``` + +例如。当ID为 `42`时, 会渲染成: + +```html +Item ID: 42 +``` + +### 模板 `url_for` 参数 + +你还可以在模板内使用 `url_for()`,其参数与*路径操作函数*的参数相同. + +所以,该部分: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...将生成一个与处理*路径操作函数* `read_item(id=id)`的URL相同的链接 + +例如。当ID为 `42`时, 会渲染成: + +```html + ``` ## 模板与静态文件 -在模板内部使用 `url_for()`,例如,与挂载的 `StaticFiles` 一起使用。 +你还可以在模板内部将 `url_for()`用于静态文件,例如你挂载的 `name="static"`的 `StaticFiles`。 ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` -本例中,使用 `url_for()` 为模板添加 CSS 文件 `static/styles.css` 链接: +本例中,它将链接到 `static/styles.css`中的CSS文件: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` -因为使用了 `StaticFiles`, **FastAPI** 应用自动提供位于 URL `/static/styles.css` - -的 CSS 文件。 +因为使用了 `StaticFiles`, **FastAPI** 应用会自动提供位于 URL `/static/styles.css`的 CSS 文件。 ## 更多说明 -包括测试模板等更多详情,请参阅 Starlette 官档 - 模板。 +包括测试模板等更多详情,请参阅 Starlette 官方文档 - 模板。 diff --git a/docs/zh/docs/advanced/testing-database.md b/docs/zh/docs/advanced/testing-database.md deleted file mode 100644 index 8dc95c25f..000000000 --- a/docs/zh/docs/advanced/testing-database.md +++ /dev/null @@ -1,97 +0,0 @@ -# 测试数据库 - -您还可以使用[测试依赖项](testing-dependencies.md){.internal-link target=_blank}中的覆盖依赖项方法变更测试的数据库。 - -实现设置其它测试数据库、在测试后回滚数据、或预填测试数据等操作。 - -本章的主要思路与上一章完全相同。 - -## 为 SQL 应用添加测试 - -为了使用测试数据库,我们要升级 [SQL 关系型数据库](../tutorial/sql-databases.md){.internal-link target=_blank} 一章中的示例。 - -应用的所有代码都一样,直接查看那一章的示例代码即可。 - -本章只是新添加了测试文件。 - -正常的依赖项 `get_db()` 返回数据库会话。 - -测试时使用覆盖依赖项返回自定义数据库会话代替正常的依赖项。 - -本例中,要创建仅用于测试的临时数据库。 - -## 文件架构 - -创建新文件 `sql_app/tests/test_sql_app.py`。 - -因此,新的文件架构如下: - -``` hl_lines="9-11" -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - ├── schemas.py - └── tests - ├── __init__.py - └── test_sql_app.py -``` - -## 创建新的数据库会话 - -首先,为新建数据库创建新的数据库会话。 - -测试时,使用 `test.db` 替代 `sql_app.db`。 - -但其余的会话代码基本上都是一样的,只要复制就可以了。 - -```Python hl_lines="8-13" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -!!! tip "提示" - - 为减少代码重复,最好把这段代码写成函数,在 `database.py` 与 `tests/test_sql_app.py`中使用。 - - 为了把注意力集中在测试代码上,本例只是复制了这段代码。 - -## 创建数据库 - -因为现在是想在新文件中使用新数据库,所以要使用以下代码创建数据库: - -```Python -Base.metadata.create_all(bind=engine) -``` - -一般是在 `main.py` 中调用这行代码,但在 `main.py` 里,这行代码用于创建 `sql_app.db`,但是现在要为测试创建 `test.db`。 - -因此,要在测试代码中添加这行代码创建新的数据库文件。 - -```Python hl_lines="16" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -## 覆盖依赖项 - -接下来,创建覆盖依赖项,并为应用添加覆盖内容。 - -```Python hl_lines="19-24 27" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -!!! tip "提示" - - `overrider_get_db()` 与 `get_db` 的代码几乎完全一样,只是 `overrider_get_db` 中使用测试数据库的 `TestingSessionLocal`。 - -## 测试应用 - -然后,就可以正常测试了。 - -```Python hl_lines="32-47" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -测试期间,所有在数据库中所做的修改都在 `test.db` 里,不会影响主应用的 `sql_app.db`。 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index dc0f88b33..b4b5b32df 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -22,23 +22,25 @@ ### 使用 `app.dependency_overrides` 属性 -对于这些用例,**FastAPI** 应用支持 `app.dependcy_overrides` 属性,该属性就是**字典**。 +对于这些用例,**FastAPI** 应用支持 `app.dependency_overrides` 属性,该属性就是**字典**。 要在测试时覆盖原有依赖项,这个字典的键应当是原依赖项(函数),值是覆盖依赖项(另一个函数)。 这样一来,**FastAPI** 就会调用覆盖依赖项,不再调用原依赖项。 ```Python hl_lines="26-27 30" -{!../../../docs_src/dependency_testing/tutorial001.py!} +{!../../docs_src/dependency_testing/tutorial001.py!} ``` -!!! tip "提示" +/// tip | 提示 - **FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 +**FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 - 原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。 +原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。 - FastAPI 可以覆盖这些位置的依赖项。 +FastAPI 可以覆盖这些位置的依赖项。 + +/// 然后,使用 `app.dependency_overrides` 把覆盖依赖项重置为空**字典**: @@ -46,6 +48,8 @@ app.dependency_overrides = {} ``` -!!! tip "提示" +/// tip | 提示 + +如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 - 如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 +/// diff --git a/docs/zh/docs/advanced/testing-events.md b/docs/zh/docs/advanced/testing-events.md index 222a67c8c..00e661cd2 100644 --- a/docs/zh/docs/advanced/testing-events.md +++ b/docs/zh/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ 使用 `TestClient` 和 `with` 语句,在测试中运行事件处理器(`startup` 与 `shutdown`)。 ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md index f303e1d67..b30939b97 100644 --- a/docs/zh/docs/advanced/testing-websockets.md +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -5,9 +5,11 @@ 为此,要在 `with` 语句中使用 `TestClient` 连接 WebSocket。 ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` -!!! note "笔记" +/// note | 笔记 - 更多细节详见 Starlette 官档 - 测试 WebSockets。 +更多细节详见 Starlette 官档 - 测试 WebSockets。 + +/// diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md index 1842c2e27..f01644de6 100644 --- a/docs/zh/docs/advanced/using-request-directly.md +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -30,25 +30,29 @@ 此时,需要直接访问请求。 ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` 把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 -!!! tip "提示" +/// tip | 提示 - 注意,本例除了声明请求参数之外,还声明了路径参数。 +注意,本例除了声明请求参数之外,还声明了路径参数。 - 因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。 +因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。 - 同样,您也可以正常声明其它参数,而且还可以提取 `Request`。 +同样,您也可以正常声明其它参数,而且还可以提取 `Request`。 + +/// ## `Request` 文档 更多细节详见 Starlette 官档 - `Request` 对象。 -!!! note "技术细节" +/// note | 技术细节 + +您也可以使用 `from starlette.requests import Request`。 - 您也可以使用 `from starlette.requests import Request`。 +**FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。 - **FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。 +/// diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index a5cbdd965..dcd4cd5a9 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -35,7 +35,7 @@ $ pip install websockets 但这是一种专注于 WebSockets 的服务器端并提供一个工作示例的最简单方式: ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## 创建 `websocket` @@ -43,20 +43,23 @@ $ pip install websockets 在您的 **FastAPI** 应用程序中,创建一个 `websocket`: ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` -!!! note "技术细节" - 您也可以使用 `from starlette.websockets import WebSocket`。 +/// note | 技术细节 - **FastAPI** 直接提供了相同的 `WebSocket`,只是为了方便开发人员。但它直接来自 Starlette。 +您也可以使用 `from starlette.websockets import WebSocket`。 + +**FastAPI** 直接提供了相同的 `WebSocket`,只是为了方便开发人员。但它直接来自 Starlette。 + +/// ## 等待消息并发送消息 在您的 WebSocket 路由中,您可以使用 `await` 等待消息并发送消息。 ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` 您可以接收和发送二进制、文本和 JSON 数据。 @@ -106,46 +109,65 @@ $ uvicorn main:app --reload 它们的工作方式与其他 FastAPI 端点/ *路径操作* 相同: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="68-69 82" +{!> ../../docs_src/websockets/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="68-69 82" +{!> ../../docs_src/websockets/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="69-70 83" +{!> ../../docs_src/websockets/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ 非带注解版本 -=== "Python 3.9+" +/// tip - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` +如果可能,请尽量使用 `Annotated` 版本。 -=== "Python 3.8+" +/// - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` +```Python hl_lines="66-67 79" +{!> ../../docs_src/websockets/tutorial002_py310.py!} +``` + +//// -=== "Python 3.10+ 非带注解版本" +//// tab | Python 3.8+ 非带注解版本 - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +/// tip - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +如果可能,请尽量使用 `Annotated` 版本。 -=== "Python 3.8+ 非带注解版本" +/// + +```Python hl_lines="68-69 81" +{!> ../../docs_src/websockets/tutorial002.py!} +``` - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +//// - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` +/// info -!!! info - 由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。 +由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。 - 您可以使用规范中定义的有效代码。 +您可以使用规范中定义的有效代码。 + +/// ### 尝试带有依赖项的 WebSockets @@ -164,8 +186,11 @@ $ uvicorn main:app --reload * "Item ID",用于路径。 * "Token",作为查询参数。 -!!! tip - 注意,查询参数 `token` 将由依赖项处理。 +/// tip + +注意,查询参数 `token` 将由依赖项处理。 + +/// 通过这样,您可以连接 WebSocket,然后发送和接收消息: @@ -175,17 +200,21 @@ $ uvicorn main:app --reload 当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。 -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` +```Python hl_lines="79-81" +{!> ../../docs_src/websockets/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="81-83" +{!> ../../docs_src/websockets/tutorial003.py!} +``` - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +//// 尝试以下操作: @@ -199,12 +228,15 @@ $ uvicorn main:app --reload Client #1596980209979 left the chat ``` -!!! tip - 上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。 +/// tip + +上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。 + +但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。 - 但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。 +如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。 - 如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。 +/// ## 更多信息 diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md index ad71280fc..92bd998d0 100644 --- a/docs/zh/docs/advanced/wsgi.md +++ b/docs/zh/docs/advanced/wsgi.md @@ -1,6 +1,6 @@ # 包含 WSGI - Flask,Django,其它 -您可以挂载多个 WSGI 应用,正如您在 [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank} 中所看到的那样。 +您可以挂载多个 WSGI 应用,正如您在 [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank} 中所看到的那样。 为此, 您可以使用 `WSGIMiddleware` 来包装你的 WSGI 应用,如:Flask,Django,等等。 @@ -13,7 +13,7 @@ 之后将其挂载到某一个路径下。 ```Python hl_lines="2-3 22" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## 检查 diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md index ed0e6e497..822ceeee4 100644 --- a/docs/zh/docs/async.md +++ b/docs/zh/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - 你只能在被 `async def` 创建的函数内使用 `await` +/// note + +你只能在被 `async def` 创建的函数内使用 `await` + +/// --- @@ -136,8 +139,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 -!!! info - 漂亮的插画来自 Ketrina Thompson. 🎨 +/// info + +漂亮的插画来自 Ketrina Thompson. 🎨 + +/// --- @@ -199,8 +205,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。 -!!! info - 漂亮的插画来自 Ketrina Thompson. 🎨 +/// info + +漂亮的插画来自 Ketrina Thompson. 🎨 + +/// --- @@ -392,12 +401,15 @@ Starlette (和 **FastAPI**) 是基于 I/O 的代码。 -在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](index.md#performance){.internal-link target=_blank}。 +在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](index.md#_11){.internal-link target=_blank}。 ### 依赖 -这同样适用于[依赖](./tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。 +这同样适用于[依赖](tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。 ### 子依赖 -你可以拥有多个相互依赖的依赖以及[子依赖](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。 +你可以拥有多个相互依赖的依赖以及[子依赖](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。 ### 其他函数 diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md index 3dfc3db7c..cad093c2a 100644 --- a/docs/zh/docs/contributing.md +++ b/docs/zh/docs/contributing.md @@ -24,63 +24,73 @@ $ python -m venv env 使用以下方法激活新环境: -=== "Linux, macOS" +//// tab | Linux, macOS -
+
- ```console - $ source ./env/bin/activate - ``` +```console +$ source ./env/bin/activate +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ .\env\Scripts\Activate.ps1 - ``` +
-
+```console +$ .\env\Scripts\Activate.ps1 +``` -=== "Windows Bash" +
+ +//// + +//// tab | Windows Bash - Or if you use Bash for Windows (e.g.
Git Bash): +Or if you use Bash for Windows (e.g. Git Bash): -
+
+ +```console +$ source ./env/Scripts/activate +``` - ```console - $ source ./env/Scripts/activate - ``` +
-
+//// 要检查操作是否成功,运行: -=== "Linux, macOS, Windows Bash" +//// tab | Linux, macOS, Windows Bash -
+
- ```console - $ which pip +```console +$ which pip - some/directory/fastapi/env/bin/pip - ``` +some/directory/fastapi/env/bin/pip +``` -
+
-=== "Windows PowerShell" +//// -
+//// tab | Windows PowerShell - ```console - $ Get-Command pip +
- some/directory/fastapi/env/bin/pip - ``` +```console +$ Get-Command pip + +some/directory/fastapi/env/bin/pip +``` -
+
+ +//// 如果显示 `pip` 程序文件位于 `env/bin/pip` 则说明激活成功。 🎉 @@ -96,10 +106,13 @@ $ python -m pip install --upgrade pip -!!! tip - 每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 +/// tip + +每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 - 这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。 +这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。 + +/// ### pip @@ -125,10 +138,13 @@ $ pip install -r requirements.txt 这样,你不必再去重新"安装"你的本地版本即可测试所有更改。 -!!! note "技术细节" - 仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 +/// note | 技术细节 + +仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 - 这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的 +这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的 + +/// ### 格式化 @@ -170,20 +186,23 @@ $ python ./scripts/docs.py live 这样,你可以编辑文档 / 源文件并实时查看更改。 -!!! tip - 或者你也可以手动执行和该脚本一样的操作 +/// tip - 进入语言目录,如果是英文文档,目录则是 `docs/en/`: +或者你也可以手动执行和该脚本一样的操作 - ```console - $ cd docs/en/ - ``` +进入语言目录,如果是英文文档,目录则是 `docs/en/`: - 在该目录执行 `mkdocs` 命令 +```console +$ cd docs/en/ +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +在该目录执行 `mkdocs` 命令 + +```console +$ mkdocs serve --dev-addr 8008 +``` + +/// #### Typer CLI (可选) @@ -210,8 +229,11 @@ Completion will take effect once you restart the terminal. 在 `./scripts/docs.py` 中还有额外工具 / 脚本来处理翻译。 -!!! tip - 你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 +/// tip + +你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 + +/// 所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。 @@ -254,22 +276,25 @@ $ uvicorn tutorial001:app --reload #### 建议和指南 -* 在当前 已有的 pull requests 中查找你使用的语言,添加要求修改或同意合并的评审意见。 +* 在当前 已有的 pull requests 中查找你使用的语言,添加要求修改或同意合并的评审意见。 + +/// tip + +你可以为已有的 pull requests 添加包含修改建议的评论。 -!!! tip - 你可以为已有的 pull requests 添加包含修改建议的评论。 +详情可查看关于 添加 pull request 评审意见 以同意合并或要求修改的文档。 - 详情可查看关于 添加 pull request 评审意见 以同意合并或要求修改的文档。 +/// -* 检查在 GitHub Discussion 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。 +* 检查在 GitHub Discussion 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。 * 每翻译一个页面新增一个 pull request。这将使其他人更容易对其进行评审。 对于我(译注:作者使用西班牙语和英语)不懂的语言,我将在等待其他人评审翻译之后将其合并。 * 你还可以查看是否有你所用语言的翻译,并对其进行评审,这将帮助我了解翻译是否正确以及能否将其合并。 - * 可以在 GitHub Discussions 中查看。 - * 也可以在现有 PR 中通过你使用的语言标签来筛选对应的 PR,举个例子,对于西班牙语,标签是 `lang-es`。 + * 可以在 GitHub Discussions 中查看。 + * 也可以在现有 PR 中通过你使用的语言标签来筛选对应的 PR,举个例子,对于西班牙语,标签是 `lang-es`。 * 请使用相同的 Python 示例,且只需翻译文档中的文本,不用修改其它东西。 @@ -283,8 +308,11 @@ $ uvicorn tutorial001:app --reload 对于西班牙语来说,它的两位字母代码是 `es`。所以西班牙语翻译的目录位于 `docs/es/`。 -!!! tip - 默认语言是英语,位于 `docs/en/`目录。 +/// tip + +默认语言是英语,位于 `docs/en/`目录。 + +/// 现在为西班牙语文档运行实时服务器: @@ -301,20 +329,23 @@ $ python ./scripts/docs.py live es -!!! tip - 或者你也可以手动执行和该脚本一样的操作 +/// tip + +或者你也可以手动执行和该脚本一样的操作 - 进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`: +进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`: + +```console +$ cd docs/es/ +``` - ```console - $ cd docs/es/ - ``` +在该目录执行 `mkdocs` 命令 - 在该目录执行 `mkdocs` 命令 +```console +$ mkdocs serve --dev-addr 8008 +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +/// 现在你可以访问 http://127.0.0.1:8008 实时查看你所做的更改。 @@ -334,8 +365,11 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - 注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。 +/// tip + +注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。 + +/// 回到浏览器你就可以看到刚刚更新的章节了。🎉 @@ -370,8 +404,11 @@ Successfully initialized: docs/ht INHERIT: ../en/mkdocs.yml ``` -!!! tip - 你也可以自己手动创建包含这些内容的文件。 +/// tip + +你也可以自己手动创建包含这些内容的文件。 + +/// 这条命令还会生成一个文档主页 `docs/ht/index.md`,你可以从这个文件开始翻译。 diff --git a/docs/zh/docs/deployment/concepts.md b/docs/zh/docs/deployment/concepts.md index 9c4aaa64b..7a0b6c3d2 100644 --- a/docs/zh/docs/deployment/concepts.md +++ b/docs/zh/docs/deployment/concepts.md @@ -25,7 +25,7 @@ ## 安全性 - HTTPS -在[上一章有关 HTTPS](./https.md){.internal-link target=_blank} 中,我们了解了 HTTPS 如何为您的 API 提供加密。 +在[上一章有关 HTTPS](https.md){.internal-link target=_blank} 中,我们了解了 HTTPS 如何为您的 API 提供加密。 我们还看到,HTTPS 通常由应用程序服务器的**外部**组件(**TLS 终止代理**)提供。 @@ -154,11 +154,13 @@ 但在那些严重错误导致正在运行的**进程**崩溃的情况下,您需要一个外部组件来负责**重新启动**进程,至少尝试几次...... -!!! tip +/// tip - ...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。 +...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。 - 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。 + 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。 + +/// 您可能希望让这个东西作为 **外部组件** 负责重新启动您的应用程序,因为到那时,使用 Uvicorn 和 Python 的同一应用程序已经崩溃了,因此同一应用程序的相同代码中没有东西可以对此做出什么。 @@ -191,7 +193,7 @@ ### 工作进程和端口 -还记得文档 [About HTTPS](./https.md){.internal-link target=_blank} 中只有一个进程可以侦听服务器中的端口和 IP 地址的一种组合吗? +还记得文档 [About HTTPS](https.md){.internal-link target=_blank} 中只有一个进程可以侦听服务器中的端口和 IP 地址的一种组合吗? 现在仍然是对的。 @@ -245,11 +247,13 @@ -!!! tip +/// tip + +如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。 - 如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。 + 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 - 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 +/// ## 启动之前的步骤 @@ -265,12 +269,13 @@ 当然,也有一些情况,多次运行前面的步骤也没有问题,这样的话就好办多了。 -!!! tip +/// tip - 另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。 +另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。 - 在这种情况下,您就不必担心这些。 🤷 + 在这种情况下,您就不必担心这些。 🤷 +/// ### 前面步骤策略的示例 @@ -282,9 +287,11 @@ * 一个 bash 脚本,运行前面的步骤,然后启动您的应用程序 * 您仍然需要一种方法来启动/重新启动 bash 脚本、检测错误等。 -!!! tip +/// tip + +我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 - 我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 +/// ## 资源利用率 diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md index 0f8906704..f120ebfb8 100644 --- a/docs/zh/docs/deployment/docker.md +++ b/docs/zh/docs/deployment/docker.md @@ -4,9 +4,11 @@ 使用 Linux 容器有几个优点,包括**安全性**、**可复制性**、**简单性**等。 -!!! tip - 赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#为-fastapi-构建-docker-镜像)。 +/// tip +赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。 + +///
Dockerfile Preview 👀 @@ -114,7 +116,7 @@ Docker 一直是创建和管理**容器镜像**和**容器**的主要工具之 最常见的方法是创建一个`requirements.txt`文件,其中每行包含一个包名称和它的版本。 -你当然也可以使用在[关于 FastAPI 版本](./versions.md){.internal-link target=_blank} 中讲到的方法来设置版本范围。 +你当然也可以使用在[关于 FastAPI 版本](versions.md){.internal-link target=_blank} 中讲到的方法来设置版本范围。 例如,你的`requirements.txt`可能如下所示: @@ -137,10 +139,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info - 还有其他文件格式和工具来定义和安装依赖项。 +/// info + +还有其他文件格式和工具来定义和安装依赖项。 + + 我将在下面的部分中向你展示一个使用 Poetry 的示例。 👇 - 我将在下面的部分中向你展示一个使用 Poetry 的示例。 👇 +/// ### 创建 **FastAPI** 代码 @@ -208,8 +213,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 选项告诉 `pip` 不要在本地保存下载的包,因为只有当 `pip` 再次运行以安装相同的包时才会这样,但在与容器一起工作时情况并非如此。 - !!! 笔记 - `--no-cache-dir` 仅与 `pip` 相关,与 Docker 或容器无关。 + /// note | 笔记 + + `--no-cache-dir` 仅与 `pip` 相关,与 Docker 或容器无关。 + + /// `--upgrade` 选项告诉 `pip` 升级软件包(如果已经安装)。 @@ -232,8 +240,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 因为程序将从`/code`启动,并且其中包含你的代码的目录`./app`,所以**Uvicorn**将能够从`app.main`中查看并**import**`app`。 -!!! tip - 通过单击代码中的每个数字气泡来查看每行的作用。 👆 +/// tip + +通过单击代码中的每个数字气泡来查看每行的作用。 👆 + +/// 你现在应该具有如下目录结构: ``` @@ -306,10 +317,13 @@ $ docker build -t myimage . -!!! tip - 注意最后的 `.`,它相当于`./`,它告诉 Docker 用于构建容器镜像的目录。 +/// tip + +注意最后的 `.`,它相当于`./`,它告诉 Docker 用于构建容器镜像的目录。 + +在本例中,它是相同的当前目录(`.`)。 - 在本例中,它是相同的当前目录(`.`)。 +/// ### 启动 Docker 容器 @@ -387,7 +401,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## 部署概念 -我们再谈谈容器方面的一些相同的[部署概念](./concepts.md){.internal-link target=_blank}。 +我们再谈谈容器方面的一些相同的[部署概念](concepts.md){.internal-link target=_blank}。 容器主要是一种简化**构建和部署**应用程序的过程的工具,但它们并不强制执行特定的方法来处理这些**部署概念**,并且有几种可能的策略。 @@ -409,8 +423,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 它可以是另一个容器,例如使用 Traefik,处理 **HTTPS** 和 **自动**获取**证书**。 -!!! tip - Traefik可以与 Docker、Kubernetes 等集成,因此使用它为容器设置和配置 HTTPS 非常容易。 +/// tip + +Traefik可以与 Docker、Kubernetes 等集成,因此使用它为容器设置和配置 HTTPS 非常容易。 + +/// 或者,HTTPS 可以由云服务商作为其服务之一进行处理(同时仍在容器中运行应用程序)。 @@ -439,8 +456,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 由于该组件将接受请求的**负载**并(希望)以**平衡**的方式在worker之间分配该请求,因此它通常也称为**负载均衡器**。 -!!! tip - 用于 HTTPS **TLS 终止代理** 的相同组件也可能是 **负载均衡器**。 +/// tip + +用于 HTTPS **TLS 终止代理** 的相同组件也可能是 **负载均衡器**。 + +/// 当使用容器时,你用来启动和管理容器的同一系统已经具有内部工具来传输来自该**负载均衡器**(也可以是**TLS 终止代理**) 的**网络通信**(例如HTTP请求)到你的应用程序容器。 @@ -526,8 +546,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 如果你有 **多个容器**,可能每个容器都运行一个 **单个进程**(例如,在 **Kubernetes** 集群中),那么你可能希望有一个 **单独的容器** 执行以下操作: 在单个容器中运行单个进程执行**先前步骤**,即运行复制的worker容器之前。 -!!! info - 如果你使用 Kubernetes,这可能是 Init Container。 +/// info + +如果你使用 Kubernetes,这可能是 Init Container。 + +/// 如果在你的用例中,运行前面的步骤**并行多次**没有问题(例如,如果你没有运行数据库迁移,而只是检查数据库是否已准备好),那么你也可以将它们放在开始主进程之前在每个容器中。 @@ -537,7 +560,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## 带有 Gunicorn 的官方 Docker 镜像 - Uvicorn -有一个官方 Docker 镜像,其中包含与 Uvicorn worker一起运行的 Gunicorn,如上一章所述:[服务器工作线程 - Gunicorn 与 Uvicorn](./server-workers.md){.internal-link target=_blank}。 +有一个官方 Docker 镜像,其中包含与 Uvicorn worker一起运行的 Gunicorn,如上一章所述:[服务器工作线程 - Gunicorn 与 Uvicorn](server-workers.md){.internal-link target=_blank}。 该镜像主要在上述情况下有用:[具有多个进程和特殊情况的容器](#containers-with-multiple-processes-and-special-cases)。 @@ -546,8 +569,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning - 你很有可能不需要此基础镜像或任何其他类似的镜像,最好从头开始构建镜像,如[上面所述:为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。 +/// warning + +你很有可能不需要此基础镜像或任何其他类似的镜像,最好从头开始构建镜像,如[上面所述:为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。 + +/// 该镜像包含一个**自动调整**机制,用于根据可用的 CPU 核心设置**worker进程数**。 @@ -555,8 +581,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 它还支持通过一个脚本运行**开始前的先前步骤** 。 -!!! tip - 要查看所有配置和选项,请转到 Docker 镜像页面: tiangolo/uvicorn-gunicorn-fastapi。 +/// tip + +要查看所有配置和选项,请转到 Docker 镜像页面: tiangolo/uvicorn-gunicorn-fastapi。 + +/// ### 官方 Docker 镜像上的进程数 @@ -686,8 +715,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. 运行`uvicorn`命令,告诉它使用从`app.main`导入的`app`对象。 -!!! tip - 单击气泡数字可查看每行的作用。 +/// tip + +单击气泡数字可查看每行的作用。 + +/// **Docker stage** 是 `Dockerfile` 的一部分,用作 **临时容器镜像**,仅用于生成一些稍后使用的文件。 diff --git a/docs/zh/docs/deployment/https.md b/docs/zh/docs/deployment/https.md index cf01a4585..9c963d587 100644 --- a/docs/zh/docs/deployment/https.md +++ b/docs/zh/docs/deployment/https.md @@ -4,8 +4,11 @@ 但实际情况比这复杂得多。 -!!!提示 - 如果你很赶时间或不在乎,请继续阅读下一部分,下一部分会提供一个step-by-step的教程,告诉你怎么使用不同技术来把一切都配置好。 +/// note | 提示 + +如果你很赶时间或不在乎,请继续阅读下一部分,下一部分会提供一个step-by-step的教程,告诉你怎么使用不同技术来把一切都配置好。 + +/// 要从用户的视角**了解 HTTPS 的基础知识**,请查看 https://howhttps.works/。 @@ -69,8 +72,11 @@ 这个操作一般只需要在最开始执行一次。 -!!! tip - 域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。 +/// tip + +域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。 + +/// ### DNS @@ -116,8 +122,11 @@ TLS 终止代理可以访问一个或多个 **TLS 证书**(HTTPS 证书)。 这就是 **HTTPS**,它只是 **安全 TLS 连接** 内的普通 **HTTP**,而不是纯粹的(未加密的)TCP 连接。 -!!! tip - 请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。 +/// tip + +请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。 + +/// ### HTTPS 请求 diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md index 15588043f..30ee7a1e9 100644 --- a/docs/zh/docs/deployment/manually.md +++ b/docs/zh/docs/deployment/manually.md @@ -5,7 +5,7 @@ 有 3 个主要可选方案: * Uvicorn:高性能 ASGI 服务器。 -* Hypercorn:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。 +* Hypercorn:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。 * Daphne:为 Django Channels 构建的 ASGI 服务器。 ## 服务器主机和服务器程序 @@ -23,77 +23,89 @@ 您可以使用以下命令安装 ASGI 兼容服务器: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 +* Uvicorn,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 -
+
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` - ```console - $ pip install "uvicorn[standard]" +
+ +/// tip - ---> 100% - ``` +通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 -
+其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 - !!! tip - 通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 +/// - 其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 +//// -=== "Hypercorn" +//// tab | Hypercorn - * Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。 +* Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。 -
+
- ```console - $ pip install hypercorn +```console +$ pip install hypercorn - ---> 100% - ``` +---> 100% +``` -
+
- ...或任何其他 ASGI 服务器。 +...或任何其他 ASGI 服务器。 +//// ## 运行服务器程序 您可以按照之前教程中的相同方式运行应用程序,但不使用`--reload`选项,例如: -=== "Uvicorn" +//// tab | Uvicorn + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +//// - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// tab | Hypercorn -
+
+```console +$ hypercorn main:app --bind 0.0.0.0:80 -=== "Hypercorn" +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` -
+
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning -
+如果您正在使用`--reload`选项,请记住删除它。 -!!! warning - 如果您正在使用`--reload`选项,请记住删除它。 + `--reload` 选项消耗更多资源,并且更不稳定。 - `--reload` 选项消耗更多资源,并且更不稳定。 + 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 - 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 +/// ## Hypercorn with Trio diff --git a/docs/zh/docs/deployment/server-workers.md b/docs/zh/docs/deployment/server-workers.md index ee3de9b5d..eb0252a5c 100644 --- a/docs/zh/docs/deployment/server-workers.md +++ b/docs/zh/docs/deployment/server-workers.md @@ -13,16 +13,17 @@ 部署应用程序时,您可能希望进行一些**进程复制**,以利用**多核**并能够处理更多请求。 -正如您在上一章有关[部署概念](./concepts.md){.internal-link target=_blank}中看到的,您可以使用多种策略。 +正如您在上一章有关[部署概念](concepts.md){.internal-link target=_blank}中看到的,您可以使用多种策略。 在这里我将向您展示如何将 **Gunicorn** 与 **Uvicorn worker 进程** 一起使用。 -!!! info - 如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 +/// info - 特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 +如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 +特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 +/// ## Gunicorn with Uvicorn Workers @@ -169,7 +170,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## 容器和 Docker -在关于 [容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他 **部署概念** 的策略。 +在关于 [容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他 **部署概念** 的策略。 我还将向您展示 **官方 Docker 镜像**,其中包括 **Gunicorn 和 Uvicorn worker** 以及一些对简单情况有用的默认配置。 diff --git a/docs/zh/docs/deployment/versions.md b/docs/zh/docs/deployment/versions.md index 75b870139..228bb0765 100644 --- a/docs/zh/docs/deployment/versions.md +++ b/docs/zh/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI 还遵循这样的约定:任何`PATCH`版本更改都是为了bug修复和non-breaking changes。 -!!! tip - "PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。 +/// tip + +"PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。 + +/// 因此,你应该能够固定到如下版本: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 "MINOR"版本中会添加breaking changes和新功能。 -!!! tip - "MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。 +/// tip + +"MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。 + +/// ## 升级FastAPI版本 diff --git a/docs/zh/docs/environment-variables.md b/docs/zh/docs/environment-variables.md new file mode 100644 index 000000000..812278051 --- /dev/null +++ b/docs/zh/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 环境变量 + +/// tip + +如果你已经知道什么是“环境变量”并且知道如何使用它们,你可以放心跳过这一部分。 + +/// + +环境变量(也称为“**env var**”)是一个独立于 Python 代码**之外**的变量,它存在于**操作系统**中,可以被你的 Python 代码(或其他程序)读取。 + +环境变量对于处理应用程序**设置**、作为 Python **安装**的一部分等方面非常有用。 + +## 创建和使用环境变量 + +你在 **shell(终端)**中就可以**创建**和使用环境变量,并不需要用到 Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 你可以使用以下命令创建一个名为 MY_NAME 的环境变量 +$ export MY_NAME="Wade Wilson" + +// 然后,你可以在其他程序中使用它,例如 +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 创建一个名为 MY_NAME 的环境变量 +$ $Env:MY_NAME = "Wade Wilson" + +// 在其他程序中使用它,例如 +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 在 Python 中读取环境变量 + +你也可以在 Python **之外**的终端中创建环境变量(或使用任何其他方法),然后在 Python 中**读取**它们。 + +例如,你可以创建一个名为 `main.py` 的文件,其中包含以下内容: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +第二个参数是 `os.getenv()` 的默认返回值。 + +如果没有提供,默认值为 `None`,这里我们提供 `"World"` 作为默认值。 + +/// + +然后你可以调用这个 Python 程序: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 这里我们还没有设置环境变量 +$ python main.py + +// 因为我们没有设置环境变量,所以我们得到的是默认值 + +Hello World from Python + +// 但是如果我们事先创建过一个环境变量 +$ export MY_NAME="Wade Wilson" + +// 然后再次调用程序 +$ python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 这里我们还没有设置环境变量 +$ python main.py + +// 因为我们没有设置环境变量,所以我们得到的是默认值 + +Hello World from Python + +// 但是如果我们事先创建过一个环境变量 +$ $Env:MY_NAME = "Wade Wilson" + +// 然后再次调用程序 +$ python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +由于环境变量可以在代码之外设置、但可以被代码读取,并且不必与其他文件一起存储(提交到 `git`),因此通常用于配置或**设置**。 + +你还可以为**特定的程序调用**创建特定的环境变量,该环境变量仅对该程序可用,且仅在其运行期间有效。 + +要实现这一点,只需在同一行内、程序本身之前创建它: + +
+ +```console +// 在这个程序调用的同一行中创建一个名为 MY_NAME 的环境变量 +$ MY_NAME="Wade Wilson" python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python + +// 在此之后这个环境变量将不会依然存在 +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +你可以在 The Twelve-Factor App: 配置中了解更多信息。 + +/// + +## 类型和验证 + +这些环境变量只能处理**文本字符串**,因为它们是处于 Python 范畴之外的,必须与其他程序和操作系统的其余部分兼容(甚至与不同的操作系统兼容,如 Linux、Windows、macOS)。 + +这意味着从环境变量中读取的**任何值**在 Python 中都将是一个 `str`,任何类型转换或验证都必须在代码中完成。 + +你将在[高级用户指南 - 设置和环境变量](./advanced/settings.md)中了解更多关于使用环境变量处理**应用程序设置**的信息。 + +## `PATH` 环境变量 + +有一个**特殊的**环境变量称为 **`PATH`**,操作系统(Linux、macOS、Windows)用它来查找要运行的程序。 + +`PATH` 变量的值是一个长字符串,由 Linux 和 macOS 上的冒号 `:` 分隔的目录组成,而在 Windows 上则是由分号 `;` 分隔的。 + +例如,`PATH` 环境变量可能如下所示: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +这意味着系统应该在以下目录中查找程序: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +这意味着系统应该在以下目录中查找程序: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +当你在终端中输入一个**命令**时,操作系统会在 `PATH` 环境变量中列出的**每个目录**中**查找**程序。 + +例如,当你在终端中输入 `python` 时,操作系统会在该列表中的**第一个目录**中查找名为 `python` 的程序。 + +如果找到了,那么操作系统将**使用它**;否则,操作系统会继续在**其他目录**中查找。 + +### 安装 Python 和更新 `PATH` + +安装 Python 时,可能会询问你是否要更新 `PATH` 环境变量。 + +//// tab | Linux, macOS + +假设你安装 Python 并最终将其安装在了目录 `/opt/custompython/bin` 中。 + +如果你同意更新 `PATH` 环境变量,那么安装程序将会将 `/opt/custompython/bin` 添加到 `PATH` 环境变量中。 + +它看起来大概会像这样: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +如此一来,当你在终端中输入 `python` 时,系统会在 `/opt/custompython/bin` 中找到 Python 程序(最后一个目录)并使用它。 + +//// + +//// tab | Windows + +假设你安装 Python 并最终将其安装在了目录 `C:\opt\custompython\bin` 中。 + +如果你同意更新 `PATH` 环境变量 (在 Python 安装程序中,这个操作是名为 `Add Python x.xx to PATH` 的复选框 —— 译者注),那么安装程序将会将 `C:\opt\custompython\bin` 添加到 `PATH` 环境变量中。 + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +如此一来,当你在终端中输入 `python` 时,系统会在 `C:\opt\custompython\bin` 中找到 Python 程序(最后一个目录)并使用它。 + +//// + +因此,如果你输入: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +系统会在 `/opt/custompython/bin` 中**找到** `python` 程序并运行它。 + +这和输入以下命令大致等价: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +系统会在 `C:\opt\custompython\bin\python` 中**找到** `python` 程序并运行它。 + +这和输入以下命令大致等价: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +当学习[虚拟环境](virtual-environments.md)时,这些信息将会很有用。 + +## 结论 + +通过这个教程,你应该对**环境变量**是什么以及如何在 Python 中使用它们有了基本的了解。 + +你也可以在环境变量 - 维基百科 (Wikipedia for Environment Variable) 中了解更多关于它们的信息。 + +在许多情况下,环境变量的用途和适用性并不是很明显。但是在开发过程中,它们会在许多不同的场景中出现,因此了解它们是很有必要的。 + +例如,你将在下一节关于[虚拟环境](virtual-environments.md)中需要这些信息。 diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md new file mode 100644 index 000000000..f532c7fb7 --- /dev/null +++ b/docs/zh/docs/fastapi-cli.md @@ -0,0 +1,87 @@ +# FastAPI CLI + +**FastAPI CLI** 是一个命令行程序,你可以用它来部署和运行你的 FastAPI 应用程序,管理你的 FastAPI 项目,等等。 + +当你安装 FastAPI 时(例如使用 `pip install FastAPI` 命令),会包含一个名为 `fastapi-cli` 的软件包,该软件包在终端中提供 `fastapi` 命令。 + +要在开发环境中运行你的 FastAPI 应用,你可以使用 `fastapi dev` 命令: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +该命令行程序 `fastapi` 就是 **FastAPI CLI**。 + +FastAPI CLI 接收你的 Python 程序路径,自动检测包含 FastAPI 的变量(通常命名为 `app`)及其导入方式,然后启动服务。 + +在生产环境中,你应该使用 `fastapi run` 命令。🚀 + +在内部,**FastAPI CLI** 使用了 Uvicorn,这是一个高性能、适用于生产环境的 ASGI 服务器。😎 + +## `fastapi dev` + +当你运行 `fastapi dev` 时,它将以开发模式运行。 + +默认情况下,它会启用**自动重载**,因此当你更改代码时,它会自动重新加载服务器。该功能是资源密集型的,且相较不启用时更不稳定,因此你应该仅在开发环境下使用它。 + +默认情况下,它将监听 IP 地址 `127.0.0.1`,这是你的机器与自身通信的 IP 地址(`localhost`)。 + +## `fastapi run` + +当你运行 `fastapi run` 时,它默认以生产环境模式运行。 + +默认情况下,**自动重载是禁用的**。 + +它将监听 IP 地址 `0.0.0.0`,即所有可用的 IP 地址,这样任何能够与该机器通信的人都可以公开访问它。这通常是你在生产环境中运行它的方式,例如在容器中运行。 + +在大多数情况下,你会(且应该)有一个“终止代理”在上层为你处理 HTTPS,这取决于你如何部署应用程序,你的服务提供商可能会为你处理此事,或者你可能需要自己设置。 + +/// tip | 提示 + +你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。 + +/// diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md deleted file mode 100644 index 7ef3f3c1a..000000000 --- a/docs/zh/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# FastAPI 社区 - -FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋友。 - -## 创建者 & 维护者 - -嘿! 👋 - -这就是我: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -我是 **FastAPI** 的创建者和维护者. 你能在 [帮助 FastAPI - 获取帮助 - 与作者联系](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} 阅读有关此内容的更多信息。 - -...但是在这里我想向您展示社区。 - ---- - -**FastAPI** 得到了社区的大力支持。因此我想突出他们的贡献。 - -这些人: - -* [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 -* [创建 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* 审核 Pull Requests, 对于 [翻译](contributing.md#translations){.internal-link target=_blank} 尤为重要。 - -向他们致以掌声。 👏 🙇 - -## 上个月最活跃的用户 - -上个月这些用户致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 专家组 - -以下是 **FastAPI 专家**。 🤓 - -这些用户一直以来致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 - -他们通过帮助许多人而被证明是专家。✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 杰出贡献者 - -以下是 **杰出的贡献者**。 👷 - -这些用户 [创建了最多已被合并的 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 - -他们贡献了源代码,文档,翻译等。 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -还有很多其他贡献者(超过100个),你可以在 FastAPI GitHub 贡献者页面 中看到他们。👷 - -## 杰出审核者 - -以下用户是「杰出的评审者」。 🕵️ - -### 翻译审核 - -我只会说少数几种语言(而且还不是很流利 😅)。所以,具备[能力去批准文档翻译](contributing.md#translations){.internal-link target=_blank} 是这些评审者们。如果没有它们,就不会有多语言文档。 - ---- - -**杰出的评审者** 🕵️ 评审了最多来自他人的 Pull Requests,他们保证了代码、文档尤其是 **翻译** 的质量。 - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 赞助商 - -以下是 **赞助商** 。😎 - -他们主要通过GitHub Sponsors支持我在 **FastAPI** (和其他项目)的工作。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### 金牌赞助商 - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 银牌赞助商 - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 铜牌赞助商 - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### 个人赞助 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## 关于数据 - 技术细节 - -该页面的目的是突出社区为帮助他人而付出的努力。 - -尤其是那些不引人注目且涉及更困难的任务,例如帮助他人解决问题或者评审翻译 Pull Requests。 - -该数据每月计算一次,您可以阅读 源代码。 - -这里也强调了赞助商的贡献。 - -我也保留更新算法,栏目,统计阈值等的权利(以防万一🤷)。 diff --git a/docs/zh/docs/features.md b/docs/zh/docs/features.md index d8190032f..24dc3e8ce 100644 --- a/docs/zh/docs/features.md +++ b/docs/zh/docs/features.md @@ -65,10 +65,13 @@ my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` 意思是: +/// info - 直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` 意思是: + +直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")` + +/// ### 编辑器支持 diff --git a/docs/zh/docs/help-fastapi.md b/docs/zh/docs/help-fastapi.md index 1a9aa57d0..09f37a44b 100644 --- a/docs/zh/docs/help-fastapi.md +++ b/docs/zh/docs/help-fastapi.md @@ -26,13 +26,13 @@ ## 在 GitHub 上为 **FastAPI** 加星 -您可以在 GitHub 上 **Star** FastAPI(只要点击右上角的星星就可以了): https://github.com/tiangolo/fastapi。⭐️ +您可以在 GitHub 上 **Star** FastAPI(只要点击右上角的星星就可以了): https://github.com/fastapi/fastapi。⭐️ **Star** 以后,其它用户就能更容易找到 FastAPI,并了解到已经有其他用户在使用它了。 ## 关注 GitHub 资源库的版本发布 -您还可以在 GitHub 上 **Watch** FastAPI,(点击右上角的 **Watch** 按钮)https://github.com/tiangolo/fastapi。👀 +您还可以在 GitHub 上 **Watch** FastAPI,(点击右上角的 **Watch** 按钮)https://github.com/fastapi/fastapi。👀 您可以选择只关注发布(**Releases only**)。 @@ -59,7 +59,7 @@ ## Tweet about **FastAPI** -Tweet about **FastAPI** 让我和大家知道您为什么喜欢 FastAPI。🎉 +Tweet about **FastAPI** 让我和大家知道您为什么喜欢 FastAPI。🎉 知道有人使用 **FastAPI**,我会很开心,我也想知道您为什么喜欢 FastAPI,以及您在什么项目/哪些公司使用 FastAPI,等等。 @@ -70,13 +70,13 @@ ## 在 GitHub 上帮助其他人解决问题 -您可以查看现有 issues,并尝试帮助其他人解决问题,说不定您能解决这些问题呢。🤓 +您可以查看现有 issues,并尝试帮助其他人解决问题,说不定您能解决这些问题呢。🤓 -如果帮助很多人解决了问题,您就有可能成为 [FastAPI 的官方专家](fastapi-people.md#experts){.internal-link target=_blank}。🎉 +如果帮助很多人解决了问题,您就有可能成为 [FastAPI 的官方专家](fastapi-people.md#_3){.internal-link target=_blank}。🎉 ## 监听 GitHub 资源库 -您可以在 GitHub 上「监听」FastAPI(点击右上角的 "watch" 按钮): https://github.com/tiangolo/fastapi. 👀 +您可以在 GitHub 上「监听」FastAPI(点击右上角的 "watch" 按钮): https://github.com/fastapi/fastapi. 👀 如果您选择 "Watching" 而不是 "Releases only",有人创建新 Issue 时,您会接收到通知。 @@ -84,7 +84,7 @@ ## 创建 Issue -您可以在 GitHub 资源库中创建 Issue,例如: +您可以在 GitHub 资源库中创建 Issue,例如: * 提出**问题**或**意见** * 提出新**特性**建议 @@ -96,9 +96,9 @@ 您可以创建 PR 为源代码做[贡献](contributing.md){.internal-link target=_blank},例如: * 修改文档错别字 -* 编辑这个文件,分享 FastAPI 的文章、视频、博客,不论是您自己的,还是您看到的都成 +* 编辑这个文件,分享 FastAPI 的文章、视频、博客,不论是您自己的,还是您看到的都成 * 注意,添加的链接要放在对应区块的开头 -* [翻译文档](contributing.md#translations){.internal-link target=_blank} +* [翻译文档](contributing.md#_8){.internal-link target=_blank} * 审阅别人翻译的文档 * 添加新的文档内容 * 修复现有问题/Bug @@ -108,11 +108,13 @@ 快加入 👥 Discord 聊天服务器 👥 和 FastAPI 社区里的小伙伴一起哈皮吧。 -!!! tip "提示" +/// tip | 提示 - 如有问题,请在 GitHub Issues 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#experts){.internal-link target=_blank}的帮助。 +如有问题,请在 GitHub Issues 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 - 聊天室仅供闲聊。 +聊天室仅供闲聊。 + +/// ### 别在聊天室里提问 @@ -120,7 +122,7 @@ GitHub Issues 里提供了模板,指引您提出正确的问题,有利于获得优质的回答,甚至可能解决您还没有想到的问题。而且就算答疑解惑要耗费不少时间,我还是会尽量在 GitHub 里回答问题。但在聊天室里,我就没功夫这么做了。😅 -聊天室里的聊天内容也不如 GitHub 里好搜索,聊天里的问答很容易就找不到了。只有在 GitHub Issues 里的问答才能帮助您成为 [FastAPI 专家](fastapi-people.md#experts){.internal-link target=_blank},在 GitHub Issues 中为您带来更多关注。 +聊天室里的聊天内容也不如 GitHub 里好搜索,聊天里的问答很容易就找不到了。只有在 GitHub Issues 里的问答才能帮助您成为 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank},在 GitHub Issues 中为您带来更多关注。 另一方面,聊天室里有成千上万的用户,在这里,您有很大可能遇到聊得来的人。😄 diff --git a/docs/zh/docs/history-design-future.md b/docs/zh/docs/history-design-future.md index 798b8fb5f..48cfef524 100644 --- a/docs/zh/docs/history-design-future.md +++ b/docs/zh/docs/history-design-future.md @@ -1,6 +1,6 @@ # 历史、设计、未来 -不久前,曾有 **FastAPI** 用户问过: +不久前,曾有 **FastAPI** 用户问过: > 这个项目有怎样的历史?好像它只用了几周就从默默无闻变得众所周知…… diff --git a/docs/zh/docs/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..1a2daeec1 --- /dev/null +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,78 @@ +# 配置 Swagger UI + +你可以配置一些额外的 Swagger UI 参数. + +如果需要配置它们,可以在创建 `FastAPI()` 应用对象时或调用 `get_swagger_ui_html()` 函数时传递 `swagger_ui_parameters` 参数。 + +`swagger_ui_parameters` 接受一个直接传递给 Swagger UI的字典,包含配置参数键值对。 + +FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因为这是 Swagger UI 需要的。 + +## 不使用语法高亮 + +比如,你可以禁用 Swagger UI 中的语法高亮。 + +当没有改变设置时,语法高亮默认启用: + + + +但是你可以通过设置 `syntaxHighlight` 为 `False` 来禁用 Swagger UI 中的语法高亮: + +```Python hl_lines="3" +{!../../docs_src/configure_swagger_ui/tutorial001.py!} +``` + +...在此之后,Swagger UI 将不会高亮代码: + + + +## 改变主题 + +同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点): + +```Python hl_lines="3" +{!../../docs_src/configure_swagger_ui/tutorial002.py!} +``` + +这个配置会改变语法高亮主题: + + + +## 改变默认 Swagger UI 参数 + +FastAPI 包含了一些默认配置参数,适用于大多数用例。 + +其包括这些默认配置参数: + +```Python +{!../../fastapi/openapi/docs.py[ln:7-23]!} +``` + +你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。 + +比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中: + +```Python hl_lines="3" +{!../../docs_src/configure_swagger_ui/tutorial003.py!} +``` + +## 其他 Swagger UI 参数 + +查看其他 Swagger UI 参数,请阅读 docs for Swagger UI parameters。 + +## JavaScript-only 配置 + +Swagger UI 同样允许使用 **JavaScript-only** 配置对象(例如,JavaScript 函数)。 + +FastAPI 包含这些 JavaScript-only 的 `presets` 设置: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +这些是 **JavaScript** 对象,而不是字符串,所以你不能直接从 Python 代码中传递它们。 + +如果你需要像这样使用 JavaScript-only 配置,你可以使用上述方法之一。覆盖所有 Swagger UI *path operation* 并手动编写任何你需要的 JavaScript。 diff --git a/docs/zh/docs/how-to/general.md b/docs/zh/docs/how-to/general.md new file mode 100644 index 000000000..e8b6dd3b2 --- /dev/null +++ b/docs/zh/docs/how-to/general.md @@ -0,0 +1,39 @@ +# 通用 - 如何操作 - 诀窍 + +这里是一些指向文档中其他部分的链接,用于解答一般性或常见问题。 + +## 数据过滤 - 安全性 + +为确保不返回超过需要的数据,请阅读 [教程 - 响应模型 - 返回类型](../tutorial/response-model.md){.internal-link target=_blank} 文档。 + +## 文档的标签 - OpenAPI + +在文档界面中添加**路径操作**的标签和进行分组,请阅读 [教程 - 路径操作配置 - Tags 参数](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank} 文档。 + +## 文档的概要和描述 - OpenAPI + +在文档界面中添加**路径操作**的概要和描述,请阅读 [教程 - 路径操作配置 - Summary 和 Description 参数](../tutorial/path-operation-configuration.md#summary-description){.internal-link target=_blank} 文档。 + +## 文档的响应描述 - OpenAPI + +在文档界面中定义并显示响应描述,请阅读 [教程 - 路径操作配置 - 响应描述](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank} 文档。 + +## 文档弃用**路径操作** - OpenAPI + +在文档界面中显示弃用的**路径操作**,请阅读 [教程 - 路径操作配置 - 弃用](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank} 文档。 + +## 将任何数据转换为 JSON 兼容格式 + +要将任何数据转换为 JSON 兼容格式,请阅读 [教程 - JSON 兼容编码器](../tutorial/encoder.md){.internal-link target=_blank} 文档。 + +## OpenAPI 元数据 - 文档 + +要添加 OpenAPI 的元数据,包括许可证、版本、联系方式等,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md){.internal-link target=_blank} 文档。 + +## OpenAPI 自定义 URL + +要自定义 OpenAPI 的 URL(或删除它),请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#openapi-url){.internal-link target=_blank} 文档。 + +## OpenAPI 文档 URL + +要更改用于自动生成文档的 URL,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}. diff --git a/docs/zh/docs/how-to/index.md b/docs/zh/docs/how-to/index.md new file mode 100644 index 000000000..ac097618b --- /dev/null +++ b/docs/zh/docs/how-to/index.md @@ -0,0 +1,13 @@ +# 如何操作 - 诀窍 + +在这里,你将看到关于**多个主题**的不同诀窍或“如何操作”指南。 + +这些方法多数是**相互独立**的,在大多数情况下,你只需在这些内容适用于**你的项目**时才需要学习它们。 + +如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。 + +/// tip | 小技巧 + +如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。 + +/// diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index a480d6640..d3e9e3112 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,26 +11,29 @@ FastAPI 框架,高性能,易于学习,高效编码,生产可用

- - Test + + Test - - Coverage + + Coverage Package version + + Supported Python versions +

--- **文档**: https://fastapi.tiangolo.com -**源码**: https://github.com/tiangolo/fastapi +**源码**: https://github.com/fastapi/fastapi --- -FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.8+ 并基于标准的 Python 类型提示。 +FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 并基于标准的 Python 类型提示。 关键特性: @@ -61,7 +70,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 「_[...] 最近我一直在使用 **FastAPI**。[...] 实际上我正在计划将其用于我所在的**微软**团队的所有**机器学习服务**。其中一些服务正被集成进核心 **Windows** 产品和一些 **Office** 产品。_」 -
Kabir Khan - 微软 (ref)
+
Kabir Khan - 微软 (ref)
--- @@ -85,7 +94,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 「_老实说,你的作品看起来非常可靠和优美。在很多方面,这就是我想让 **Hug** 成为的样子 - 看到有人实现了它真的很鼓舞人心。_」 -
Timothy Crosley - Hug 作者 (ref)
+
Timothy Crosley - Hug 作者 (ref)
--- @@ -107,7 +116,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 ## 依赖 -Python 3.8 及更高版本 +Python 及更高版本 FastAPI 站在以下巨人的肩膀之上: @@ -126,7 +135,7 @@ $ pip install fastapi -你还会需要一个 ASGI 服务器,生产环境可以使用 Uvicorn 或者 Hypercorn。 +你还会需要一个 ASGI 服务器,生产环境可以使用 Uvicorn 或者 Hypercorn
@@ -187,7 +196,7 @@ async def read_item(item_id: int, q: Union[str, None] = None): **Note**: -如果你不知道是否会用到,可以查看文档的 _"In a hurry?"_ 章节中 关于 `async` 和 `await` 的部分。 +如果你不知道是否会用到,可以查看文档的 _"In a hurry?"_ 章节中 关于 `async` 和 `await` 的部分
@@ -323,7 +332,7 @@ def update_item(item_id: int, item: Item): 你不需要去学习新的语法、了解特定库的方法或类,等等。 -只需要使用标准的 **Python 3.8 及更高版本**。 +只需要使用标准的 **Python 及更高版本**。 举个例子,比如声明 `int` 类型: @@ -410,7 +419,7 @@ item: Item ![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) -教程 - 用户指南 中有包含更多特性的更完整示例。 +教程 - 用户指南 中有包含更多特性的更完整示例。 **剧透警告**: 教程 - 用户指南中的内容有: @@ -431,13 +440,13 @@ item: Item 独立机构 TechEmpower 所作的基准测试结果显示,基于 Uvicorn 运行的 **FastAPI** 程序是 最快的 Python web 框架之一,仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部使用了它们)。(*) -想了解更多,请查阅 基准测试 章节。 +想了解更多,请查阅 基准测试 章节。 ## 可选依赖 用于 Pydantic: -* email_validator - 用于 email 校验。 +* email-validator - 用于 email 校验。 用于 Starlette: @@ -447,14 +456,14 @@ item: Item * itsdangerous - 需要 `SessionMiddleware` 支持时安装。 * pyyaml - 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。 * graphene - 需要 `GraphQLApp` 支持时安装。 -* ujson - 使用 `UJSONResponse` 时安装。 用于 FastAPI / Starlette: * uvicorn - 用于加载和运行你的应用程序的服务器。 * orjson - 使用 `ORJSONResponse` 时安装。 +* ujson - 使用 `UJSONResponse` 时安装。 -你可以通过 `pip install fastapi[all]` 命令来安装以上所有依赖。 +你可以通过 `pip install "fastapi[all]"` 命令来安装以上所有依赖。 ## 许可协议 diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md index feafa5333..48eb990df 100644 --- a/docs/zh/docs/project-generation.md +++ b/docs/zh/docs/project-generation.md @@ -1,84 +1,28 @@ -# 项目生成 - 模板 - -项目生成器一般都会提供很多初始设置、安全措施、数据库,甚至还准备好了第一个 API 端点,能帮助您快速上手。 - -项目生成器的设置通常都很主观,您可以按需更新或修改,但对于您的项目来说,它是非常好的起点。 - -## 全栈 FastAPI + PostgreSQL - -GitHub:https://github.com/tiangolo/full-stack-fastapi-postgresql - -### 全栈 FastAPI + PostgreSQL - 功能 - -* 完整的 **Docker** 集成(基于 Docker) -* Docker Swarm 开发模式 -* **Docker Compose** 本地开发集成与优化 -* **生产可用**的 Python 网络服务器,使用 Uvicorn 或 Gunicorn -* Python **FastAPI** 后端: -* * **速度快**:可与 **NodeJS** 和 **Go** 比肩的极高性能(归功于 Starlette 和 Pydantic) - * **直观**:强大的编辑器支持,处处皆可自动补全,减少调试时间 - * **简单**:易学、易用,阅读文档所需时间更短 - * **简短**:代码重复最小化,每次参数声明都可以实现多个功能 - * **健壮**: 生产级别的代码,还有自动交互文档 - * **基于标准**:完全兼容并基于 API 开放标准:OpenAPIJSON Schema - * **更多功能**包括自动验证、序列化、交互文档、OAuth2 JWT 令牌身份验证等 -* **安全密码**,默认使用密码哈希 -* **JWT 令牌**身份验证 -* **SQLAlchemy** 模型(独立于 Flask 扩展,可直接用于 Celery Worker) -* 基础的用户模型(可按需修改或删除) -* **Alembic** 迁移 -* **CORS**(跨域资源共享) -* **Celery** Worker 可从后端其它部分有选择地导入并使用模型和代码 -* REST 后端测试基于 Pytest,并与 Docker 集成,可独立于数据库实现完整的 API 交互测试。因为是在 Docker 中运行,每次都可从头构建新的数据存储(使用 ElasticSearch、MongoDB、CouchDB 等数据库,仅测试 API 运行) -* Python 与 **Jupyter Kernels** 集成,用于远程或 Docker 容器内部开发,使用 Atom Hydrogen 或 Visual Studio Code 的 Jupyter 插件 -* **Vue** 前端: - * 由 Vue CLI 生成 - * **JWT 身份验证**处理 - * 登录视图 - * 登录后显示主仪表盘视图 - * 主仪表盘支持用户创建与编辑 - * 用户信息编辑 - * **Vuex** - * **Vue-router** - * **Vuetify** 美化组件 - * **TypeScript** - * 基于 **Nginx** 的 Docker 服务器(优化了 Vue-router 配置) - * Docker 多阶段构建,无需保存或提交编译的代码 - * 在构建时运行前端测试(可禁用) - * 尽量模块化,开箱即用,但仍可使用 Vue CLI 重新生成或创建所需项目,或复用所需内容 -* 使用 **PGAdmin** 管理 PostgreSQL 数据库,可轻松替换为 PHPMyAdmin 或 MySQL -* 使用 **Flower** 监控 Celery 任务 -* 使用 **Traefik** 处理前后端负载平衡,可把前后端放在同一个域下,按路径分隔,但在不同容器中提供服务 -* Traefik 集成,包括自动生成 Let's Encrypt **HTTPS** 凭证 -* GitLab **CI**(持续集成),包括前后端测试 - -## 全栈 FastAPI + Couchbase - -GitHub:https://github.com/tiangolo/full-stack-fastapi-couchbase - -⚠️ **警告** ⚠️ - -如果您想从头开始创建新项目,建议使用以下备选方案。 - -例如,项目生成器全栈 FastAPI + PostgreSQL 会更适用,这个项目的维护积极,用的人也多,还包括了所有新功能和改进内容。 - -当然,您也可以放心使用这个基于 Couchbase 的生成器,它也能正常使用。就算用它生成项目也没有任何问题(为了更好地满足需求,您可以自行更新这个项目)。 - -详见资源仓库中的文档。 - -## 全栈 FastAPI + MongoDB - -……敬请期待,得看我有没有时间做这个项目。😅 🎉 - -## FastAPI + spaCy 机器学习模型 - -GitHub:https://github.com/microsoft/cookiecutter-spacy-fastapi - -### FastAPI + spaCy 机器学习模型 - 功能 - -* 集成 **spaCy** NER 模型 -* 内置 **Azure 认知搜索**请求格式 -* **生产可用**的 Python 网络服务器,使用 Uvicorn 与 Gunicorn -* 内置 **Azure DevOps** Kubernetes (AKS) CI/CD 开发 -* **多语**支持,可在项目设置时选择 spaCy 内置的语言 -* 不仅局限于 spaCy,可**轻松扩展**至其它模型框架(Pytorch、TensorFlow) +# FastAPI全栈模板 + +模板通常带有特定的设置,而且被设计为灵活和可定制的。这允许您根据项目的需求修改和调整它们,使它们成为一个很好的起点。🏁 + +您可以使用此模板开始,因为它包含了许多已经为您完成的初始设置、安全性、数据库和一些API端点。 + +代码仓: Full Stack FastAPI Template + +## FastAPI全栈模板 - 技术栈和特性 + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) 用于Python后端API. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) 用于Python和SQL数据库的集成(ORM)。 + - 🔍 [Pydantic](https://docs.pydantic.dev) FastAPI的依赖项之一,用于数据验证和配置管理。 + - 💾 [PostgreSQL](https://www.postgresql.org) 作为SQL数据库。 +- 🚀 [React](https://react.dev) 用于前端。 + - 💃 使用了TypeScript、hooks、[Vite](https://vitejs.dev)和其他一些现代化的前端技术栈。 + - 🎨 [Chakra UI](https://chakra-ui.com) 用于前端组件。 + - 🤖 一个自动化生成的前端客户端。 + - 🧪 [Playwright](https://playwright.dev)用于端到端测试。 + - 🦇 支持暗黑主题(Dark mode)。 +- 🐋 [Docker Compose](https://www.docker.com) 用于开发环境和生产环境。 +- 🔒 默认使用密码哈希来保证安全。 +- 🔑 JWT令牌用于权限验证。 +- 📫 使用邮箱来进行密码恢复。 +- ✅ 单元测试用了[Pytest](https://pytest.org). +- 📞 [Traefik](https://traefik.io) 用于反向代理和负载均衡。 +- 🚢 部署指南(Docker Compose)包含了如何起一个Traefik前端代理来自动化HTTPS认证。 +- 🏭 CI(持续集成)和 CD(持续部署)基于GitHub Actions。 diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index 214b47611..dab6bd4c0 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -12,15 +12,18 @@ 但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。 -!!! note - 如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。 +/// note + +如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。 + +/// ## 动机 让我们从一个简单的例子开始: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` 运行这段程序将输出: @@ -36,7 +39,7 @@ John Doe * 中间用一个空格来拼接它们。 ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### 修改示例 @@ -80,7 +83,7 @@ John Doe 这些就是"类型提示": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` 这和声明默认值是不同的,例如: @@ -110,7 +113,7 @@ John Doe 下面是一个已经有类型提示的函数: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` 因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误: @@ -120,7 +123,7 @@ John Doe 现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 声明类型 @@ -141,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 嵌套类型 @@ -159,7 +162,7 @@ John Doe 从 `typing` 模块导入 `List`(注意是大写的 `L`): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 同样以冒号(`:`)来声明这个变量。 @@ -169,7 +172,7 @@ John Doe 由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。 @@ -189,7 +192,7 @@ John Doe 声明 `tuple` 和 `set` 的方法也是一样的: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` 这表示: @@ -206,7 +209,7 @@ John Doe 第二个子类型声明 `dict` 的所有值: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` 这表示: @@ -222,13 +225,13 @@ John Doe 假设你有一个名为 `Person` 的类,拥有 name 属性: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 接下来,你可以将一个变量声明为 `Person` 类型: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 然后,你将再次获得所有的编辑器支持: @@ -250,11 +253,14 @@ John Doe 下面的例子来自 Pydantic 官方文档: ```Python -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` -!!! info - 想进一步了解 Pydantic,请阅读其文档. +/// info + +想进一步了解 Pydantic,请阅读其文档. + +/// 整个 **FastAPI** 建立在 Pydantic 的基础之上。 @@ -282,5 +288,8 @@ John Doe 最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。 -!!! info - 如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。 +/// info + +如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。 + +/// diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md index 94b75d4fd..80622e129 100644 --- a/docs/zh/docs/tutorial/background-tasks.md +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ 首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数: -```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1, 13] *} **FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。 @@ -33,17 +31,13 @@ 由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数: -```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 添加后台任务 在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中: -```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 接收以下参数: @@ -57,41 +51,47 @@ **FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} - ``` +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13, 15, 22, 25] *} -=== "Python 3.9+" +//// - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +{* ../../docs_src/background_tasks/tutorial002_an_py39.py hl[13, 15, 22, 25] *} - ```Python hl_lines="14 16 23 26" - {!> ../../../docs_src/background_tasks/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ 没Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +{* ../../docs_src/background_tasks/tutorial002_an.py hl[14, 16, 23, 26] *} - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ 没Annotated" +//// tab | Python 3.10+ 没Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 + +/// + +{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11, 13, 20, 23] *} + +//// + +//// tab | Python 3.8+ 没Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +{* ../../docs_src/background_tasks/tutorial002.py hl[13, 15, 22, 25] *} + +//// 该示例中,信息会在响应发出 *之后* 被写到 `log.txt` 文件。 diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 138959566..318e10fd7 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ **FastAPI** 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序。 -!!! info - 如果你来自 Flask,那这将相当于 Flask 的 Blueprints。 +/// info + +如果你来自 Flask,那这将相当于 Flask 的 Blueprints。 + +/// ## 一个文件结构示例 @@ -26,16 +29,19 @@ │   └── admin.py ``` -!!! tip - 上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。 +/// tip + +上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。 - 这就是能将代码从一个文件导入到另一个文件的原因。 +这就是能将代码从一个文件导入到另一个文件的原因。 - 例如,在 `app/main.py` 中,你可以有如下一行: +例如,在 `app/main.py` 中,你可以有如下一行: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * `app` 目录包含了所有内容。并且它有一个空文件 `app/__init__.py`,因此它是一个「Python 包」(「Python 模块」的集合):`app`。 * 它包含一个 `app/main.py` 文件。由于它位于一个 Python 包(一个包含 `__init__.py` 文件的目录)中,因此它是该包的一个「模块」:`app.main`。 @@ -80,7 +86,7 @@ 你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### 使用 `APIRouter` 的*路径操作* @@ -90,7 +96,7 @@ 使用方式与 `FastAPI` 类相同: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` 你可以将 `APIRouter` 视为一个「迷你 `FastAPI`」类。 @@ -99,8 +105,11 @@ 所有相同的 `parameters`、`responses`、`dependencies`、`tags` 等等。 -!!! tip - 在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。 +/// tip + +在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。 + +/// 我们将在主 `FastAPI` 应用中包含该 `APIRouter`,但首先,让我们来看看依赖项和另一个 `APIRouter`。 @@ -113,13 +122,16 @@ 现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部: ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!../../../docs_src/bigger_applications/app/dependencies.py!} +{!../../docs_src/bigger_applications/app/dependencies.py!} ``` -!!! tip - 我们正在使用虚构的请求首部来简化此示例。 +/// tip + +我们正在使用虚构的请求首部来简化此示例。 + +但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。 - 但在实际情况下,使用集成的[安全性实用工具](./security/index.md){.internal-link target=_blank}会得到更好的效果。 +/// ## 其他使用 `APIRouter` 的模块 @@ -144,7 +156,7 @@ 因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。 ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` 由于每个*路径操作*的路径都必须以 `/` 开头,例如: @@ -163,8 +175,11 @@ async def read_item(item_id: str): 我们可以添加一个 `dependencies` 列表,这些依赖项将被添加到路由器中的所有*路径操作*中,并将针对向它们发起的每个请求执行/解决。 -!!! tip - 请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。 +/// tip + +请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。 + +/// 最终结果是项目相关的路径现在为: @@ -181,11 +196,17 @@ async def read_item(item_id: str): * 路由器的依赖项最先执行,然后是[装饰器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank},再然后是普通的参数依赖项。 * 你还可以添加[具有 `scopes` 的 `Security` 依赖项](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}。 -!!! tip - 在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。 +/// tip + +在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。 + +/// + +/// check -!!! check - `prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。 +`prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。 + +/// ### 导入依赖项 @@ -196,13 +217,16 @@ async def read_item(item_id: str): 因此,我们通过 `..` 对依赖项使用了相对导入: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### 相对导入如何工作 -!!! tip - 如果你完全了解导入的工作原理,请从下面的下一部分继续。 +/// tip + +如果你完全了解导入的工作原理,请从下面的下一部分继续。 + +/// 一个单点 `.`,例如: @@ -266,13 +290,16 @@ from ...dependencies import get_token_header 但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip - 最后的这个路径操作将包含标签的组合:`["items","custom"]`。 +/// tip + +最后的这个路径操作将包含标签的组合:`["items","custom"]`。 - 并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。 +并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。 + +/// ## `FastAPI` 主体 @@ -291,7 +318,7 @@ from ...dependencies import get_token_header 我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 导入 `APIRouter` @@ -299,7 +326,7 @@ from ...dependencies import get_token_header 现在,我们导入具有 `APIRouter` 的其他子模块: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 由于文件 `app/routers/users.py` 和 `app/routers/items.py` 是同一 Python 包 `app` 一个部分的子模块,因此我们可以使用单个点 ` .` 通过「相对导入」来导入它们。 @@ -328,20 +355,23 @@ from .routers import items, users from app.routers import items, users ``` -!!! info - 第一个版本是「相对导入」: +/// info + +第一个版本是「相对导入」: - ```Python - from .routers import items, users - ``` +```Python +from .routers import items, users +``` - 第二个版本是「绝对导入」: +第二个版本是「绝对导入」: + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。 - 要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。 +/// ### 避免名称冲突 @@ -361,7 +391,7 @@ from .routers.users import router 因此,为了能够在同一个文件中使用它们,我们直接导入子模块: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 包含 `users` 和 `items` 的 `APIRouter` @@ -369,29 +399,38 @@ from .routers.users import router 现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。 ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。 +/// info - `items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。 +`users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。 + +`items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。 + +/// 使用 `app.include_router()`,我们可以将每个 `APIRouter` 添加到主 `FastAPI` 应用程序中。 它将包含来自该路由器的所有路由作为其一部分。 -!!! note "技术细节" - 实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。 +/// note | 技术细节 + +实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。 + +所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。 + +/// - 所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。 +/// check -!!! check - 包含路由器时,你不必担心性能问题。 +包含路由器时,你不必担心性能问题。 - 这将花费几微秒时间,并且只会在启动时发生。 +这将花费几微秒时间,并且只会在启动时发生。 - 因此,它不会影响性能。⚡ +因此,它不会影响性能。⚡ + +/// ### 包含一个有自定义 `prefix`、`tags`、`responses` 和 `dependencies` 的 `APIRouter` @@ -402,7 +441,7 @@ from .routers.users import router 对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` 但是我们仍然希望在包含 `APIRouter` 时设置一个自定义的 `prefix`,以便其所有*路径操作*以 `/admin` 开头,我们希望使用本项目已经有的 `dependencies` 保护它,并且我们希望它包含自定义的 `tags` 和 `responses`。 @@ -410,7 +449,7 @@ from .routers.users import router 我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 这样,原始的 `APIRouter` 将保持不变,因此我们仍然可以与组织中的其他项目共享相同的 `app/internal/admin.py` 文件。 @@ -433,21 +472,24 @@ from .routers.users import router 这里我们这样做了...只是为了表明我们可以做到🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。 -!!! info "特别的技术细节" - **注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。 +/// info | 特别的技术细节 + +**注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。 + +--- - --- +`APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。 - `APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。 +这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。 - 这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。 +由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。 - 由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。 +/// ## 查看自动化的 API 文档 diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index fb6c6d9b6..9aeb481ef 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -1,112 +1,153 @@ # 请求体 - 字段 -与使用 `Query`、`Path` 和 `Body` 在*路径操作函数*中声明额外的校验和元数据的方式相同,你可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。 +与在*路径操作函数*中使用 `Query`、`Path` 、`Body` 声明校验与元数据的方式一样,可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。 ## 导入 `Field` -首先,你必须导入它: +首先,从 Pydantic 中导入 `Field`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001_an.py!} +``` - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -!!! warning - 注意,`Field` 是直接从 `pydantic` 导入的,而不是像其他的(`Query`,`Path`,`Body` 等)都从 `fastapi` 导入。 +/// + +```Python hl_lines="2" +{!> ../../docs_src/body_fields/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="4" +{!> ../../docs_src/body_fields/tutorial001.py!} +``` + +//// + +/// warning | 警告 + +注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。 + +/// ## 声明模型属性 -然后,你可以对模型属性使用 `Field`: +然后,使用 `Field` 定义模型的属性: + +//// tab | Python 3.10+ + +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12-15" +{!> ../../docs_src/body_fields/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// -=== "Python 3.10+" +```Python hl_lines="9-12" +{!> ../../docs_src/body_fields/tutorial001_py310.py!} +``` - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` +/// tip -=== "Python 3.8+" +Prefer to use the `Annotated` version if possible. - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +```Python hl_lines="11-14" +{!> ../../docs_src/body_fields/tutorial001.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +`Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。 -=== "Python 3.8+ non-Annotated" +/// note | 技术细节 - !!! tip - Prefer to use the `Annotated` version if possible. +实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。 - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。 -`Field` 的工作方式和 `Query`、`Path` 和 `Body` 相同,包括它们的参数等等也完全相同。 +`Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。 -!!! note "技术细节" - 实际上,`Query`、`Path` 和其他你将在之后看到的类,创建的是由一个共同的 `Params` 类派生的子类的对象,该共同类本身又是 Pydantic 的 `FieldInfo` 类的子类。 +注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。 - Pydantic 的 `Field` 也会返回一个 `FieldInfo` 的实例。 +/// - `Body` 也直接返回 `FieldInfo` 的一个子类的对象。还有其他一些你之后会看到的类是 `Body` 类的子类。 +/// tip | 提示 - 请记住当你从 `fastapi` 导入 `Query`、`Path` 等对象时,他们实际上是返回特殊类的函数。 +注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。 -!!! tip - 注意每个模型属性如何使用类型、默认值和 `Field` 在代码结构上和*路径操作函数*的参数是相同的,区别是用 `Field` 替换`Path`、`Query` 和 `Body`。 +/// -## 添加额外信息 +## 添加更多信息 -你可以在 `Field`、`Query`、`Body` 中声明额外的信息。这些信息将包含在生成的 JSON Schema 中。 +`Field`、`Query`、`Body` 等对象里可以声明更多信息,并且 JSON Schema 中也会集成这些信息。 -你将在文档的后面部分学习声明示例时,了解到更多有关添加额外信息的知识。 +*声明示例*一章中将详细介绍添加更多信息的知识。 -## 总结 +## 小结 -你可以使用 Pydantic 的 `Field` 为模型属性声明额外的校验和元数据。 +Pydantic 的 `Field` 可以为模型属性声明更多校验和元数据。 -你还可以使用额外的关键字参数来传递额外的 JSON Schema 元数据。 +传递 JSON Schema 元数据还可以使用更多关键字参数。 diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md index c93ef2f5c..c3bc0db9e 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -8,44 +8,63 @@ 你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="18-20" +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-20" +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-21" +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-19" +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// + +```Python hl_lines="19-21" +{!> ../../docs_src/body_multiple_params/tutorial001.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// note - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。 -!!! note - 请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。 +/// ## 多个请求体参数 @@ -62,17 +81,21 @@ 但是你也可以声明多个请求体参数,例如 `item` 和 `user`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +```Python hl_lines="20" +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../docs_src/body_multiple_params/tutorial002.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +//// 在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。 @@ -93,9 +116,11 @@ } ``` -!!! note - 请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。 +/// note +请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。 + +/// **FastAPI** 将自动对请求中的数据进行转换,因此 `item` 参数将接收指定的内容,`user` 参数也是如此。 @@ -112,41 +137,57 @@ 但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="23" +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="23" +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="24" +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="22" +{!> ../../docs_src/body_multiple_params/tutorial003.py!} +``` - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +//// 在这种情况下,**FastAPI** 将期望像这样的请求体: @@ -181,45 +222,63 @@ q: str = None 比如: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="27" +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="27" +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="28" +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.9+" +/// - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` +```Python hl_lines="25" +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.10+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +/// -=== "Python 3.8+ non-Annotated" +```Python hl_lines="27" +{!> ../../docs_src/body_multiple_params/tutorial004.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +/// info -!!! info - `Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。 +`Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。 +/// ## 嵌入单个请求体参数 @@ -235,41 +294,57 @@ item: Item = Body(embed=True) 比如: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="17" +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="15" +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="17" +{!> ../../docs_src/body_multiple_params/tutorial005.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +//// 在这种情况下,**FastAPI** 将期望像这样的请求体: diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index 3f519ae33..316ba9878 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -6,17 +6,21 @@ 你可以将一个属性定义为拥有子元素的类型。例如 Python `list`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial001.py!} +``` - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +//// 这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。 @@ -29,7 +33,7 @@ 首先,从 Python 的标准库 `typing` 模块中导入 `List`: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### 声明具有子类型的 List @@ -51,23 +55,29 @@ my_list: List[str] 因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +```Python hl_lines="12" +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial002.py!} +``` + +//// ## Set 类型 @@ -77,23 +87,29 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se 然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="12" +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +//// + +//// tab | Python 3.9+ + +```Python hl_lines="14" +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="1 14" +{!> ../../docs_src/body_nested_models/tutorial003.py!} +``` - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +//// 这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。 @@ -115,45 +131,57 @@ Pydantic 模型的每个属性都具有类型。 例如,我们可以定义一个 `Image` 模型: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7-9" +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} +``` + +//// - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9-11" +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9-11" +{!> ../../docs_src/body_nested_models/tutorial004.py!} +``` - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// ### 将子模型用作类型 然后我们可以将其用作一个属性的类型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} +``` + +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial004.py!} +``` + +//// 这意味着 **FastAPI** 将期望类似于以下内容的请求体: @@ -186,23 +214,29 @@ Pydantic 模型的每个属性都具有类型。 例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8" +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +```Python hl_lines="4 10" +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10" +{!> ../../docs_src/body_nested_models/tutorial005.py!} +``` - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +//// 该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。 @@ -210,23 +244,29 @@ Pydantic 模型的每个属性都具有类型。 你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +```Python hl_lines="18" +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="20" +{!> ../../docs_src/body_nested_models/tutorial006.py!} +``` + +//// 这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体: @@ -254,33 +294,45 @@ Pydantic 模型的每个属性都具有类型。 } ``` -!!! info - 请注意 `images` 键现在具有一组 image 对象是如何发生的。 +/// info + +请注意 `images` 键现在具有一组 image 对象是如何发生的。 + +/// ## 深度嵌套模型 你可以定义任意深度的嵌套模型: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 12 18 21 25" +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} +``` + +//// - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="9 14 20 23 27" +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 14 20 23 27" +{!> ../../docs_src/body_nested_models/tutorial007.py!} +``` - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。 -!!! info - 请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。 +/// ## 纯列表请求体 @@ -292,17 +344,21 @@ images: List[Image] 例如: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="13" +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} +``` - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +```Python hl_lines="15" +{!> ../../docs_src/body_nested_models/tutorial008.py!} +``` + +//// ## 无处不在的编辑器支持 @@ -332,26 +388,33 @@ images: List[Image] 在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/body_nested_models/tutorial009.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +//// -=== "Python 3.8+" +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +请记住 JSON 仅支持将 `str` 作为键。 -!!! tip - 请记住 JSON 仅支持将 `str` 作为键。 +但是 Pydantic 具有自动转换数据的功能。 - 但是 Pydantic 具有自动转换数据的功能。 +这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。 - 这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。 +然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。 - 然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。 +/// ## 总结 diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index 43f20f8fc..9372e1dfd 100644 --- a/docs/zh/docs/tutorial/body-updates.md +++ b/docs/zh/docs/tutorial/body-updates.md @@ -7,7 +7,7 @@ 把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`。 ```Python hl_lines="30-35" -{!../../../docs_src/body_updates/tutorial001.py!} +{!../../docs_src/body_updates/tutorial001.py!} ``` `PUT` 用于接收替换现有数据的数据。 @@ -34,15 +34,17 @@ 即,只发送要更新的数据,其余数据保持不变。 -!!! Note "笔记" +/// note | 笔记 - `PATCH` 没有 `PUT` 知名,也怎么不常用。 +`PATCH` 没有 `PUT` 知名,也怎么不常用。 - 很多人甚至只用 `PUT` 实现部分更新。 +很多人甚至只用 `PUT` 实现部分更新。 - **FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。 +**FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。 - 但本指南也会分别介绍这两种操作各自的用途。 +但本指南也会分别介绍这两种操作各自的用途。 + +/// ### 使用 Pydantic 的 `exclude_unset` 参数 @@ -55,7 +57,7 @@ 然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`: ```Python hl_lines="34" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### 使用 Pydantic 的 `update` 参数 @@ -65,7 +67,7 @@ 例如,`stored_item_model.copy(update=update_data)`: ```Python hl_lines="35" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### 更新部分数据小结 @@ -84,18 +86,22 @@ * 返回更新后的模型。 ```Python hl_lines="30-37" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` -!!! tip "提示" +/// tip | 提示 + +实际上,HTTP `PUT` 也可以完成相同的操作。 +但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。 + +/// - 实际上,HTTP `PUT` 也可以完成相同的操作。 - 但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。 +/// note | 笔记 -!!! note "笔记" +注意,输入模型仍需验证。 - 注意,输入模型仍需验证。 +因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。 - 因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。 +为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。 - 为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。 +/// diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index 3d615be39..bf3117beb 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -1,55 +1,68 @@ # 请求体 -当你需要将数据从客户端(例如浏览器)发送给 API 时,你将其作为「请求体」发送。 +FastAPI 使用**请求体**从客户端(例如浏览器)向 API 发送数据。 -**请求**体是客户端发送给 API 的数据。**响应**体是 API 发送给客户端的数据。 +**请求体**是客户端发送给 API 的数据。**响应体**是 API 发送给客户端的数据。 -你的 API 几乎总是要发送**响应**体。但是客户端并不总是需要发送**请求**体。 +API 基本上肯定要发送**响应体**,但是客户端不一定发送**请求体**。 -我们使用 Pydantic 模型来声明**请求**体,并能够获得它们所具有的所有能力和优点。 +使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。 -!!! info - 你不能使用 `GET` 操作(HTTP 方法)发送请求体。 +/// info | 说明 - 要发送数据,你必须使用下列方法之一:`POST`(较常见)、`PUT`、`DELETE` 或 `PATCH`。 +发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。 + +规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。 + +我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。 + +/// ## 导入 Pydantic 的 `BaseModel` -首先,你需要从 `pydantic` 中导入 `BaseModel`: +从 `pydantic` 中导入 `BaseModel`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="2" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="4" +{!> ../../docs_src/body/tutorial001.py!} +``` + +//// ## 创建数据模型 -然后,将你的数据模型声明为继承自 `BaseModel` 的类。 +把数据模型声明为继承 `BaseModel` 的类。 + +使用 Python 标准类型声明所有属性: + +//// tab | Python 3.10+ -使用标准的 Python 类型来声明所有属性: +```Python hl_lines="5-9" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.10+" +//// - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="7-11" +{!> ../../docs_src/body/tutorial001.py!} +``` - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// -和声明查询参数时一样,当一个模型属性具有默认值时,它不是必需的。否则它是一个必需属性。将默认值设为 `None` 可使其成为可选属性。 +与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。 -例如,上面的模型声明了一个这样的 JSON「`object`」(或 Python `dict`): +例如,上述模型声明如下 JSON **对象**(即 Python **字典**): ```JSON { @@ -60,7 +73,7 @@ } ``` -...由于 `description` 和 `tax` 是可选的(它们的默认值为 `None`),下面的 JSON「`object`」也将是有效的: +……由于 `description` 和 `tax` 是可选的(默认值为 `None`),下面的 JSON **对象**也有效: ```JSON { @@ -69,127 +82,165 @@ } ``` -## 声明为参数 +## 声明请求体参数 -使用与声明路径和查询参数的相同方式声明请求体,即可将其添加到「路径操作」中: +使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +```Python hl_lines="16" +{!> ../../docs_src/body/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../docs_src/body/tutorial001.py!} +``` -...并且将它的类型声明为你创建的 `Item` 模型。 +//// -## 结果 +……此处,请求体参数的类型为 `Item` 模型。 -仅仅使用了 Python 类型声明,**FastAPI** 将会: +## 结论 -* 将请求体作为 JSON 读取。 -* 转换为相应的类型(在需要时)。 -* 校验数据。 - * 如果数据无效,将返回一条清晰易读的错误信息,指出不正确数据的确切位置和内容。 -* 将接收的数据赋值到参数 `item` 中。 - * 由于你已经在函数中将它声明为 `Item` 类型,你还将获得对于所有属性及其类型的一切编辑器支持(代码补全等)。 -* 为你的模型生成 JSON 模式 定义,你还可以在其他任何对你的项目有意义的地方使用它们。 -* 这些模式将成为生成的 OpenAPI 模式的一部分,并且被自动化文档 UI 所使用。 +仅使用 Python 类型声明,**FastAPI** 就可以: -## 自动化文档 +* 以 JSON 形式读取请求体 +* (在必要时)把请求体转换为对应的类型 +* 校验数据: + * 数据无效时返回错误信息,并指出错误数据的确切位置和内容 +* 把接收的数据赋值给参数 `item` + * 把函数中请求体参数的类型声明为 `Item`,还能获得代码补全等编辑器支持 +* 为模型生成 JSON Schema,在项目中所需的位置使用 +* 这些概图是 OpenAPI 概图的部件,用于 API 文档 UI -你所定义模型的 JSON 模式将成为生成的 OpenAPI 模式的一部分,并且在交互式 API 文档中展示: +## API 文档 - +Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文档中显示: -而且还将在每一个需要它们的*路径操作*的 API 文档中使用: + - +而且,还会用于 API 文档中使用了概图的*路径操作*: + + ## 编辑器支持 -在你的编辑器中,你会在函数内部的任意地方得到类型提示和代码补全(如果你接收的是一个 `dict` 而不是 Pydantic 模型,则不会发生这种情况): +在编辑器中,函数内部均可使用类型提示、代码补全(如果接收的不是 Pydantic 模型,而是**字典**,就没有这样的支持): + + + +还支持检查错误的类型操作: + + - +这并非偶然,整个 **FastAPI** 框架都是围绕这种思路精心设计的。 -你还会获得对不正确的类型操作的错误检查: +并且,在 FastAPI 的设计阶段,我们就已经进行了全面测试,以确保 FastAPI 可以获得所有编辑器的支持。 - +我们还改进了 Pydantic,让它也支持这些功能。 -这并非偶然,整个框架都是围绕该设计而构建。 +虽然上面的截图取自 Visual Studio Code。 -并且在进行任何实现之前,已经在设计阶段经过了全面测试,以确保它可以在所有的编辑器中生效。 +但 PyCharm 和大多数 Python 编辑器也支持同样的功能: -Pydantic 本身甚至也进行了一些更改以支持此功能。 + -上面的截图取自 Visual Studio Code。 +/// tip | 提示 -但是在 PyCharm 和绝大多数其他 Python 编辑器中你也会获得同样的编辑器支持: +使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。 - +该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下: + +* 自动补全 +* 类型检查 +* 代码重构 +* 查找 +* 代码审查 + +/// ## 使用模型 -在函数内部,你可以直接访问模型对象的所有属性: +在*路径操作*函数内部直接访问模型对象的属性: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +```Python hl_lines="19" +{!> ../../docs_src/body/tutorial002_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../docs_src/body/tutorial002.py!} +``` + +//// ## 请求体 + 路径参数 -你可以同时声明路径参数和请求体。 +**FastAPI** 支持同时声明路径参数和请求体。 + +**FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。 -**FastAPI** 将识别出与路径参数匹配的函数参数应**从路径中获取**,而声明为 Pydantic 模型的函数参数应**从请求体中获取**。 +//// tab | Python 3.10+ + +```Python hl_lines="15-16" +{!> ../../docs_src/body/tutorial003_py310.py!} +``` -=== "Python 3.10+" +//// - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../docs_src/body/tutorial003.py!} +``` - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +//// ## 请求体 + 路径参数 + 查询参数 -你还可以同时声明**请求体**、**路径参数**和**查询参数**。 +**FastAPI** 支持同时声明**请求体**、**路径参数**和**查询参数**。 + +**FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。 + +//// tab | Python 3.10+ + +```Python hl_lines="16" +{!> ../../docs_src/body/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../docs_src/body/tutorial004.py!} +``` -**FastAPI** 会识别它们中的每一个,并从正确的位置获取数据。 +//// -=== "Python 3.10+" +函数参数按如下规则进行识别: - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +- **路径**中声明了相同参数的参数,是路径参数 +- 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数 +- 类型是 **Pydantic 模型**的参数,是**请求体** -=== "Python 3.8+" +/// note | 笔记 - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。 -函数参数将依次按如下规则进行识别: +FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。 -* 如果在**路径**中也声明了该参数,它将被用作路径参数。 -* 如果参数属于**单一类型**(比如 `int`、`float`、`str`、`bool` 等)它将被解释为**查询**参数。 -* 如果参数的类型被声明为一个 **Pydantic 模型**,它将被解释为**请求体**。 +/// ## 不使用 Pydantic -如果你不想使用 Pydantic 模型,你还可以使用 **Body** 参数。请参阅文档 [请求体 - 多个参数:请求体中的单一值](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}。 +即便不使用 Pydantic 模型也能使用 **Body** 参数。详见[请求体 - 多参数:请求体中的单值](body-multiple-params.md#_2){.internal-link target=\_blank}。 diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index 8571422dd..762dca766 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -6,41 +6,57 @@ 首先,导入 `Cookie`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001_an.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="3" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` + +//// ## 声明 `Cookie` 参数 @@ -49,51 +65,71 @@ 第一个值是默认值,还可以传递所有验证参数或注释参数: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` +/// -=== "Python 3.9+" +```Python hl_lines="7" +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ non-Annotated - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +/// tip -=== "Python 3.10+ non-Annotated" +尽可能选择使用 `Annotated` 的版本。 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/cookie_params/tutorial001.py!} +``` -=== "Python 3.8+ non-Annotated" +//// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// note | 技术细节 - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +`Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 -!!! note "技术细节" +注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。 - `Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 +/// - 注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。 +/// info | 说明 -!!! info "说明" +必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 - 必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index ddd4e7682..84c435c97 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 特定的 HTTP headers 或者使用通配符 `"*"` 允许所有 headers。 ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` 默认情况下,这个 `CORSMiddleware` 实现所使用的默认参数较为保守,所以你需要显式地启用特定的源、方法或者 headers,以便浏览器能够在跨域上下文中使用它们。 @@ -78,7 +78,10 @@ 更多关于 CORS 的信息,请查看 Mozilla CORS 文档。 -!!! note "技术细节" - 你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。 +/// note | 技术细节 - 出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。 +你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。 + +出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。 + +/// diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md index 51801d498..a5afa1aaa 100644 --- a/docs/zh/docs/tutorial/debugging.md +++ b/docs/zh/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ 在你的 FastAPI 应用中直接导入 `uvicorn` 并运行: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### 关于 `__name__ == "__main__"` @@ -70,8 +70,11 @@ from myapp import app uvicorn.run(app, host="0.0.0.0", port=8000) ``` -!!! info - 更多信息请检查 Python 官方文档. +/// info + +更多信息请检查 Python 官方文档. + +/// ## 使用你的调试器运行代码 diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index 1866da298..917459d1d 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,21 @@ 在前面的例子中, 我们从依赖项 ("可依赖对象") 中返回了一个 `dict`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// 但是后面我们在路径操作函数的参数 `commons` 中得到了一个 `dict`。 @@ -79,45 +83,57 @@ fluffy = Cat(name="Mr Fluffy") 所以,我们可以将上面的依赖项 "可依赖对象" `common_parameters` 更改为类 `CommonQueryParams`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +```Python hl_lines="9-13" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="11-15" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// 注意用于创建类实例的 `__init__` 方法: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// -=== "Python 3.6+" +//// tab | Python 3.6+ + +```Python hl_lines="12" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// ...它与我们以前的 `common_parameters` 具有相同的参数: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="6" +{!> ../../docs_src/dependencies/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="9" +{!> ../../docs_src/dependencies/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +//// 这些参数就是 **FastAPI** 用来 "处理" 依赖项的。 @@ -133,17 +149,21 @@ fluffy = Cat(name="Mr Fluffy") 现在,您可以使用这个类来声明你的依赖项了。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial002.py!} +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// **FastAPI** 调用 `CommonQueryParams` 类。这将创建该类的一个 "实例",该实例将作为参数 `commons` 被传递给你的函数。 @@ -183,17 +203,21 @@ commons = Depends(CommonQueryParams) ..就像: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial003_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial003.py!} +``` + +//// 但是声明类型是被鼓励的,因为那样你的编辑器就会知道将传递什么作为参数 `commons` ,然后它可以帮助你完成代码,类型检查,等等: @@ -227,21 +251,28 @@ commons: CommonQueryParams = Depends() 同样的例子看起来像这样: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial004_py310.py!} +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +```Python hl_lines="19" +{!> ../../docs_src/dependencies/tutorial004.py!} +``` + +//// ... **FastAPI** 会知道怎么处理。 -!!! tip - 如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。 +/// tip + +如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。 + +这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。 - 这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。 +/// diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 61ea371e5..c202c977b 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -15,24 +15,28 @@ 该参数的值是由 `Depends()` 组成的 `list`: ```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` 路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。 -!!! tip "提示" +/// tip | 提示 - 有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。 +有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。 - 在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。 +在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。 - 使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。 +使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。 -!!! info "说明" +/// - 本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。 +/// info | 说明 - 但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。 +本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。 + +但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。 + +/// ## 依赖项错误和返回值 @@ -43,7 +47,7 @@ 路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项: ```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 触发异常 @@ -51,7 +55,7 @@ 路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常: ```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 返回值 @@ -61,7 +65,7 @@ 因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项: ```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ## 为一组路径操作定义依赖项 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index e24b9409f..792b6784d 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -1,161 +1,284 @@ # 使用yield的依赖项 -FastAPI支持在完成后执行一些额外步骤的依赖项. +FastAPI支持在完成后执行一些额外步骤的依赖项. -为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。 +为此,你需要使用 `yield` 而不是 `return`,然后再编写这些额外的步骤(代码)。 -!!! 提示 - 确保只使用一次 `yield` 。 +/// tip | 提示 -!!! 注意 "技术细节" +确保在每个依赖中只使用一次 `yield`。 - 任何一个可以与以下内容一起使用的函数: +/// - * `@contextlib.contextmanager` 或者 - * `@contextlib.asynccontextmanager` +/// note | 技术细节 - 都可以作为 **FastAPI** 的依赖项。 +任何一个可以与以下内容一起使用的函数: - 实际上,FastAPI内部就使用了这两个装饰器。 +* `@contextlib.contextmanager` 或者 +* `@contextlib.asynccontextmanager` +都可以作为 **FastAPI** 的依赖项。 + +实际上,FastAPI内部就使用了这两个装饰器。 + +/// ## 使用 `yield` 的数据库依赖项 -例如,您可以使用这种方式创建一个数据库会话,并在完成后关闭它。 +例如,你可以使用这种方式创建一个数据库会话,并在完成后关闭它。 在发送响应之前,只会执行 `yield` 语句及之前的代码: ```Python hl_lines="2-4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` -生成的值会注入到*路径操作*和其他依赖项中: +生成的值会注入到 *路由函数* 和其他依赖项中: ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` -"yield"语句后面的代码会在发送响应后执行:: +`yield` 语句后面的代码会在创建响应后,发送响应前执行: ```Python hl_lines="5-6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` -!!! 提示 +/// tip | 提示 + +你可以使用 `async` 或普通函数。 - 您可以使用 `async` 或普通函数。 +**FastAPI** 会像处理普通依赖一样,对每个依赖做正确的处理。 - **FastAPI** 会像处理普通依赖关系一样,对每个依赖关系做正确的处理。 +/// -## 同时包含了 `yield` 和 `try` 的依赖项 +## 包含 `yield` 和 `try` 的依赖项 -如果在带有 `yield` 的依赖关系中使用 `try` 代码块,就会收到使用依赖关系时抛出的任何异常。 +如果在包含 `yield` 的依赖中使用 `try` 代码块,你会捕获到使用依赖时抛出的任何异常。 -例如,如果中间某个代码在另一个依赖中或在*路径操作*中使数据库事务 "回滚 "或产生任何其他错误,您就会在依赖中收到异常。 +例如,如果某段代码在另一个依赖中或在 *路由函数* 中使数据库事务"回滚"或产生任何其他错误,你将会在依赖中捕获到异常。 -因此,你可以使用 `except SomeException` 在依赖关系中查找特定的异常。 +因此,你可以使用 `except SomeException` 在依赖中捕获特定的异常。 -同样,您也可以使用 `finally` 来确保退出步骤得到执行,无论是否存在异常。 +同样,你也可以使用 `finally` 来确保退出步骤得到执行,无论是否存在异常。 ```Python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` -## 使用`yield`的子依赖项 +## 使用 `yield` 的子依赖项 -你可以拥有任意大小和形状的子依赖和子依赖的“树”,而且它们中的任何一个或所有的都可以使用`yield`。 +你可以声明任意数量和层级的树状依赖,而且它们中的任何一个或所有的都可以使用 `yield`。 -**FastAPI** 会确保每个带有`yield`的依赖中的“退出代码”按正确顺序运行。 +**FastAPI** 会确保每个带有 `yield` 的依赖中的"退出代码"按正确顺序运行。 例如,`dependency_c` 可以依赖于 `dependency_b`,而 `dependency_b` 则依赖于 `dependency_a`。 -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6 14 22" +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="5 13 21" +{!> ../../docs_src/dependencies/tutorial008_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 提示 - ```Python hl_lines="6 14 22" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +如果可以,请尽量使用 `Annotated` 版本。 -=== "Python 3.8+" +/// - ```Python hl_lines="5 13 21" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +```Python hl_lines="4 12 20" +{!> ../../docs_src/dependencies/tutorial008.py!} +``` + +//// + +所有这些依赖都可以使用 `yield`。 -=== "Python 3.8+ non-Annotated" +在这种情况下,`dependency_c` 在执行其退出代码时需要 `dependency_b`(此处称为 `dep_b`)的值仍然可用。 - !!! tip - 如果可能,请尽量使用“ Annotated”版本。 +而 `dependency_b` 反过来则需要 `dependency_a`(此处称为 `dep_a` )的值在其退出代码中可用。 - ```Python hl_lines="4 12 20" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +//// tab | Python 3.9+ -所有这些依赖都可以使用`yield`。 +```Python hl_lines="18-19 26-27" +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// -在这种情况下,`dependency_c` 在执行其退出代码时需要`dependency_b`(此处称为 `dep_b`)的值仍然可用。 +//// tab | Python 3.8+ -而`dependency_b` 反过来则需要`dependency_a`(此处称为 `dep_a`)的值在其退出代码中可用。 +```Python hl_lines="17-18 25-26" +{!> ../../docs_src/dependencies/tutorial008_an.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="18-19 26-27" - {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip | 提示 - ```Python hl_lines="17-18 25-26" - {!> ../../../docs_src/dependencies/tutorial008_an.py!} - ``` +如果可以,请尽量使用 `Annotated` 版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 如果可能,请尽量使用“ Annotated”版本。 +```Python hl_lines="16-17 24-25" +{!> ../../docs_src/dependencies/tutorial008.py!} +``` - ```Python hl_lines="16-17 24-25" - {!> ../../../docs_src/dependencies/tutorial008.py!} - ``` +//// -同样,你可以有混合了`yield`和`return`的依赖。 +同样,你可以混合使用带有 `yield` 或 `return` 的依赖。 -你也可以有一个单一的依赖需要多个其他带有`yield`的依赖,等等。 +你也可以声明一个依赖于多个带有 `yield` 的依赖,等等。 你可以拥有任何你想要的依赖组合。 **FastAPI** 将确保按正确的顺序运行所有内容。 -!!! note "技术细节" +/// note | 技术细节 + +这是由 Python 的上下文管理器完成的。 + +**FastAPI** 在内部使用它们来实现这一点。 + +/// + +## 包含 `yield` 和 `HTTPException` 的依赖项 + +你可以使用带有 `yield` 的依赖项,并且可以包含 `try` 代码块用于捕获异常。 + +同样,你可以在 `yield` 之后的退出代码中抛出一个 `HTTPException` 或类似的异常。 + +/// tip | 提示 + +这是一种相对高级的技巧,在大多数情况下你并不需要使用它,因为你可以在其他代码中抛出异常(包括 `HTTPException` ),例如在 *路由函数* 中。 + +但是如果你需要,你也可以在依赖项中做到这一点。🤓 + +/// + +//// tab | Python 3.9+ + +```Python hl_lines="18-22 31" +{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="17-21 30" +{!> ../../docs_src/dependencies/tutorial008b_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 提示 + +如果可以,请尽量使用 `Annotated` 版本。 + +/// + +```Python hl_lines="16-20 29" +{!> ../../docs_src/dependencies/tutorial008b.py!} +``` + +//// + +你还可以创建一个 [自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} 用于捕获异常(同时也可以抛出另一个 `HTTPException`)。 + +## 包含 `yield` 和 `except` 的依赖项 + +如果你在包含 `yield` 的依赖项中使用 `except` 捕获了一个异常,然后你没有重新抛出该异常(或抛出一个新异常),与在普通的Python代码中相同,FastAPI不会注意到发生了异常。 + +//// tab | Python 3.9+ - 这是由 Python 的上下文管理器完成的。 +```Python hl_lines="15-16" +{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="14-15" +{!> ../../docs_src/dependencies/tutorial008c_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 提示 + +如果可以,请尽量使用 `Annotated` 版本。 + +/// + +```Python hl_lines="13-14" +{!> ../../docs_src/dependencies/tutorial008c.py!} +``` - **FastAPI** 在内部使用它们来实现这一点。 +//// +在示例代码的情况下,客户端将会收到 *HTTP 500 Internal Server Error* 的响应,因为我们没有抛出 `HTTPException` 或者类似的异常,并且服务器也 **不会有任何日志** 或者其他提示来告诉我们错误是什么。😱 -## 使用 `yield` 和 `HTTPException` 的依赖项 +### 在包含 `yield` 和 `except` 的依赖项中一定要 `raise` -您看到可以使用带有 `yield` 的依赖项,并且具有捕获异常的 `try` 块。 +如果你在使用 `yield` 的依赖项中捕获到了一个异常,你应该再次抛出捕获到的异常,除非你抛出 `HTTPException` 或类似的其他异常, -在 `yield` 后抛出 `HTTPException` 或类似的异常是很诱人的,但是**这不起作用**。 +你可以使用 `raise` 再次抛出捕获到的异常。 -带有`yield`的依赖中的退出代码在响应发送之后执行,因此[异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}已经运行过。没有任何东西可以捕获退出代码(在`yield`之后)中的依赖抛出的异常。 +//// tab | Python 3.9+ -所以,如果在`yield`之后抛出`HTTPException`,默认(或任何自定义)异常处理程序捕获`HTTPException`并返回HTTP 400响应的机制将不再能够捕获该异常。 +```Python hl_lines="17" +{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial008d_an.py!} +``` + +//// -这就是允许在依赖中设置的任何东西(例如数据库会话(DB session))可以被后台任务使用的原因。 +//// tab | Python 3.8+ non-Annotated -后台任务在响应发送之后运行。因此,无法触发`HTTPException`,因为甚至没有办法更改*已发送*的响应。 +/// tip | 提示 -但如果后台任务产生了数据库错误,至少你可以在带有`yield`的依赖中回滚或清理关闭会话,并且可能记录错误或将其报告给远程跟踪系统。 +如果可以,请尽量使用 `Annotated` 版本。 -如果你知道某些代码可能会引发异常,那就做最“Pythonic”的事情,就是在代码的那部分添加一个`try`块。 +/// -如果你有自定义异常,希望在返回响应之前处理,并且可能修改响应甚至触发`HTTPException`,可以创建[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}。 +```Python hl_lines="15" +{!> ../../docs_src/dependencies/tutorial008d.py!} +``` + +//// -!!! tip +现在客户端同样会得到 *HTTP 500 Internal Server Error* 响应,但是服务器日志会记录下我们自定义的 `InternalError`。 - 在`yield`之前仍然可以引发包括`HTTPException`在内的异常,但在`yield`之后则不行。 +## 使用 `yield` 的依赖项的执行 -执行的顺序大致如下图所示。时间从上到下流动。每列都是相互交互或执行代码的其中一部分。 +执行顺序大致如下时序图所示。时间轴从上到下,每一列都代表交互或者代码执行的一部分。 ```mermaid sequenceDiagram @@ -166,54 +289,89 @@ participant dep as Dep with yield participant operation as Path Operation participant tasks as Background tasks - Note over client,tasks: Can raise exception for dependency, handled after response is sent - Note over client,operation: Can raise HTTPException and can change the response + Note over client,operation: Can raise exceptions, including HTTPException client ->> dep: Start request Note over dep: Run code up to yield - opt raise - dep -->> handler: Raise HTTPException + opt raise Exception + dep -->> handler: Raise Exception handler -->> client: HTTP error response - dep -->> dep: Raise other exception end dep ->> operation: Run dependency, e.g. DB session opt raise - operation -->> dep: Raise HTTPException - dep -->> handler: Auto forward exception + operation -->> dep: Raise Exception (e.g. HTTPException) + opt handle + dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception + end handler -->> client: HTTP error response - operation -->> dep: Raise other exception - dep -->> handler: Auto forward exception end + operation ->> client: Return response to client Note over client,operation: Response is already sent, can't change it anymore opt Tasks operation -->> tasks: Send background tasks end opt Raise other exception - tasks -->> dep: Raise other exception - end - Note over dep: After yield - opt Handle other exception - dep -->> dep: Handle exception, can't change response. E.g. close DB session. + tasks -->> tasks: Handle exceptions in the background task code end ``` -!!! info - 只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。 +/// info | 说明 + +只会向客户端发送 **一次响应** ,可能是一个错误响应,也可能是来自 *路由函数* 的响应。 - 在发送了其中一个响应之后,就无法再发送其他响应了。 +在发送了其中一个响应之后,就无法再发送其他响应了。 -!!! tip - 这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。 +/// - 如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。 +/// tip | 提示 + +这个时序图展示了 `HTTPException`,除此之外你也可以抛出任何你在使用 `yield` 的依赖项中或者[自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}中捕获的异常。 + +如果你引发任何异常,它将传递给使用 `yield` 的依赖项,包括 `HTTPException`。在大多数情况下你应当从使用 `yield` 的依赖项中重新抛出捕获的异常或者一个新的异常来确保它会被正确的处理。 + +/// + +## 包含 `yield`, `HTTPException`, `except` 的依赖项和后台任务 + +/// warning | 注意 + +你大概率不需要了解这些技术细节,可以跳过这一章节继续阅读后续的内容。 + +如果你使用的FastAPI的版本早于0.106.0,并且在使用后台任务中使用了包含 `yield` 的依赖项中的资源,那么这些细节会对你有一些用处。 + +/// + +### 包含 `yield` 和 `except` 的依赖项的技术细节 + +在FastAPI 0.110.0版本之前,如果使用了一个包含 `yield` 的依赖项,你在依赖项中使用 `except` 捕获了一个异常,但是你没有再次抛出该异常,这个异常会被自动抛出/转发到异常处理器或者内部服务错误处理器。 + +### 后台任务和使用 `yield` 的依赖项的技术细节 + +在FastAPI 0.106.0版本之前,在 `yield` 后面抛出异常是不可行的,因为 `yield` 之后的退出代码是在响应被发送之后再执行,这个时候异常处理器已经执行过了。 + +这样设计的目的主要是为了允许在后台任务中使用被依赖项`yield`的对象,因为退出代码会在后台任务结束后再执行。 + +然而这也意味着在等待响应通过网络传输的同时,非必要的持有一个 `yield` 依赖项中的资源(例如数据库连接),这一行为在FastAPI 0.106.0被改变了。 + +/// tip | 提示 + +除此之外,后台任务通常是一组独立的逻辑,应该被单独处理,并且使用它自己的资源(例如它自己的数据库连接)。 + +这样也会让你的代码更加简洁。 + +/// + +如果你之前依赖于这一行为,那么现在你应该在后台任务中创建并使用它自己的资源,不要在内部使用属于 `yield` 依赖项的资源。 + +例如,你应该在后台任务中创建一个新的数据库会话用于查询数据,而不是使用相同的会话。你应该将对象的ID作为参数传递给后台任务函数,然后在该函数中重新获取该对象,而不是直接将数据库对象作为参数。 ## 上下文管理器 -### 什么是“上下文管理器” +### 什么是"上下文管理器" -“上下文管理器”是您可以在`with`语句中使用的任何Python对象。 +"上下文管理器"是你可以在 `with` 语句中使用的任何Python对象。 -例如,您可以使用`with`读取文件: +例如,你可以使用`with`读取文件: ```Python with open("./somefile.txt") as f: @@ -221,33 +379,39 @@ with open("./somefile.txt") as f: print(contents) ``` -在底层,`open("./somefile.txt")`创建了一个被称为“上下文管理器”的对象。 +在底层,`open("./somefile.txt")`创建了一个被称为"上下文管理器"的对象。 + +当 `with` 代码块结束时,它会确保关闭文件,即使发生了异常也是如此。 -当`with`块结束时,它会确保关闭文件,即使发生了异常也是如此。 +当你使用 `yield` 创建一个依赖项时,**FastAPI** 会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 -当你使用`yield`创建一个依赖项时,**FastAPI**会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 +### 在使用 `yield` 的依赖项中使用上下文管理器 -### 在依赖项中使用带有`yield`的上下文管理器 +/// warning | 注意 -!!! warning - 这是一个更为“高级”的想法。 +这是一个更为"高级"的想法。 - 如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。 +如果你刚开始使用 **FastAPI** ,你可以暂时可以跳过它。 + +/// 在Python中,你可以通过创建一个带有`__enter__()`和`__exit__()`方法的类来创建上下文管理器。 -你也可以在**FastAPI**的依赖项中使用带有`yield`的`with`或`async with`语句,通过在依赖函数内部使用它们。 +你也可以在 **FastAPI** 的 `yield` 依赖项中通过 `with` 或者 `async with` 语句来使用它们: ```Python hl_lines="1-9 13" -{!../../../docs_src/dependencies/tutorial010.py!} +{!../../docs_src/dependencies/tutorial010.py!} ``` -!!! tip - 另一种创建上下文管理器的方法是: +/// tip | 提示 + +另一种创建上下文管理器的方法是: + +* `@contextlib.contextmanager`或者 +* `@contextlib.asynccontextmanager` - * `@contextlib.contextmanager`或者 - * `@contextlib.asynccontextmanager` +使用它们装饰一个只有单个 `yield` 的函数。这就是 **FastAPI** 内部对于 `yield` 依赖项的处理方式。 - 使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。 +但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 - 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 +/// diff --git a/docs/zh/docs/tutorial/dependencies/global-dependencies.md b/docs/zh/docs/tutorial/dependencies/global-dependencies.md index 3f7afa32c..66f153f6b 100644 --- a/docs/zh/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/global-dependencies.md @@ -7,7 +7,7 @@ 这样一来,就可以为所有*路径操作*应用该依赖项: ```Python hl_lines="15" -{!../../../docs_src/dependencies/tutorial012.py!} +{!../../docs_src/dependencies/tutorial012.py!} ``` [*路径装饰器依赖项*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 一章的思路均适用于全局依赖项, 在本例中,这些依赖项可以用于应用中的所有*路径操作*。 diff --git a/docs/zh/docs/tutorial/dependencies/index.md b/docs/zh/docs/tutorial/dependencies/index.md index 7a133061d..e0d2c5f70 100644 --- a/docs/zh/docs/tutorial/dependencies/index.md +++ b/docs/zh/docs/tutorial/dependencies/index.md @@ -32,7 +32,7 @@ FastAPI 提供了简单易用,但功能强大的** read_users 这样,只编写一次代码,**FastAPI** 就可以为多个*路径操作*共享这段代码 。 -!!! check "检查" +/// check | 检查 + +注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。 - 注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。 +只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。 - 只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。 +/// ## 要不要使用 `async`? @@ -114,9 +118,11 @@ common_parameters --> read_users 上述这些操作都是可行的,**FastAPI** 知道该怎么处理。 -!!! note "笔记" +/// note | 笔记 + +如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。 - 如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。 +/// ## 与 OpenAPI 集成 diff --git a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md index 58377bbfe..e0b75aa0c 100644 --- a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md @@ -11,7 +11,7 @@ FastAPI 支持创建含**子依赖项**的依赖项。 下列代码创建了第一层依赖项: ```Python hl_lines="8-9" -{!../../../docs_src/dependencies/tutorial005.py!} +{!../../docs_src/dependencies/tutorial005.py!} ``` 这段代码声明了类型为 `str` 的可选查询参数 `q`,然后返回这个查询参数。 @@ -23,7 +23,7 @@ FastAPI 支持创建含**子依赖项**的依赖项。 接下来,创建另一个依赖项函数,并同时用该依赖项自身再声明一个依赖项(所以这也是一个「依赖项」): ```Python hl_lines="13" -{!../../../docs_src/dependencies/tutorial005.py!} +{!../../docs_src/dependencies/tutorial005.py!} ``` 这里重点说明一下声明的参数: @@ -38,14 +38,16 @@ FastAPI 支持创建含**子依赖项**的依赖项。 接下来,就可以使用依赖项: ```Python hl_lines="22" -{!../../../docs_src/dependencies/tutorial005.py!} +{!../../docs_src/dependencies/tutorial005.py!} ``` -!!! info "信息" +/// info | 信息 - 注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。 +注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。 - 但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。 +但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。 + +/// ```mermaid graph TB @@ -79,10 +81,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False 但它依然非常强大,能够声明任意嵌套深度的「图」或树状的依赖结构。 -!!! tip "提示" +/// tip | 提示 + +这些简单的例子现在看上去虽然没有什么实用价值, - 这些简单的例子现在看上去虽然没有什么实用价值, +但在**安全**一章中,您会了解到这些例子的用途, - 但在**安全**一章中,您会了解到这些例子的用途, +以及这些例子所能节省的代码量。 - 以及这些例子所能节省的代码量。 +/// diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md index 859ebc2e8..41f37cd8d 100644 --- a/docs/zh/docs/tutorial/encoder.md +++ b/docs/zh/docs/tutorial/encoder.md @@ -20,17 +20,21 @@ 它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +```Python hl_lines="4 21" +{!> ../../docs_src/encoder/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="5 22" +{!> ../../docs_src/encoder/tutorial001.py!} +``` + +//// 在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。 @@ -38,5 +42,8 @@ 这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。 -!!! note - `jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。 +/// note + +`jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。 + +/// diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index cf39de0dd..ea5798b67 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -55,76 +55,108 @@ 下面是一个*路径操作*的示例,其中的参数使用了上面的一些类型。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3 12-16" +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="1 3 12-16" +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="1 3 13-17" +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} +``` - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1 2 11-15" +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1 2 12-16" +{!> ../../docs_src/extra_data_types/tutorial001.py!} +``` + +//// 注意,函数内的参数有原生的数据类型,你可以,例如,执行正常的日期操作,如: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="19-20" +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="17-18" +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} +``` - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="18-19" +{!> ../../docs_src/extra_data_types/tutorial001.py!} +``` - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +//// diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md index 94d82c524..982cf15fb 100644 --- a/docs/zh/docs/tutorial/extra-models.md +++ b/docs/zh/docs/tutorial/extra-models.md @@ -8,27 +8,33 @@ * **输出模型**不应含密码 * **数据库模型**需要加密的密码 -!!! danger "危险" +/// danger | 危险 - 千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。 +千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。 - 如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。 +如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。 + +/// ## 多个模型 下面的代码展示了不同模型处理密码字段的方式,及使用位置的大致思路: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" +{!> ../../docs_src/extra_models/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!> ../../docs_src/extra_models/tutorial001.py!} +``` - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +//// ### `**user_in.dict()` 简介 @@ -140,9 +146,11 @@ UserInDB( ) ``` -!!! warning "警告" +/// warning | 警告 + +辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。 - 辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。 +/// ## 减少重复 @@ -162,17 +170,21 @@ FastAPI 可以做得更好。 通过这种方式,可以只声明模型之间的区别(分别包含明文密码、哈希密码,以及无密码的模型)。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +```Python hl_lines="7 13-14 17-18 21-22" +{!> ../../docs_src/extra_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 15-16 19-20 23-24" +{!> ../../docs_src/extra_models/tutorial002.py!} +``` - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +//// ## `Union` 或者 `anyOf` @@ -182,21 +194,27 @@ FastAPI 可以做得更好。 为此,请使用 Python 标准类型提示 `typing.Union`: -!!! note "笔记" +/// note | 笔记 + +定义 `Union` 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 - 定义 `Union` 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 +/// -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +```Python hl_lines="1 14-15 18-20 33" +{!> ../../docs_src/extra_models/tutorial003_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="1 14-15 18-20 33" +{!> ../../docs_src/extra_models/tutorial003.py!} +``` + +//// ## 模型列表 @@ -204,17 +222,21 @@ FastAPI 可以做得更好。 为此,请使用标准的 Python `typing.List`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +```Python hl_lines="18" +{!> ../../docs_src/extra_models/tutorial004_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +```Python hl_lines="1 20" +{!> ../../docs_src/extra_models/tutorial004.py!} +``` + +//// ## 任意 `dict` 构成的响应 @@ -224,17 +246,21 @@ FastAPI 可以做得更好。 此时,可以使用 `typing.Dict`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="6" +{!> ../../docs_src/extra_models/tutorial005_py39.py!} +``` - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="1 8" +{!> ../../docs_src/extra_models/tutorial005.py!} +``` - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +//// ## 小结 diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md index 30fae99cf..2f573501c 100644 --- a/docs/zh/docs/tutorial/first-steps.md +++ b/docs/zh/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ 最简单的 FastAPI 文件可能像下面这样: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 将其复制到 `main.py` 文件中。 @@ -24,13 +24,15 @@ $ uvicorn main:app --reload -!!! note - `uvicorn main:app` 命令含义如下: +/// note - * `main`:`main.py` 文件(一个 Python「模块」)。 - * `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 - * `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。 +`uvicorn main:app` 命令含义如下: +* `main`:`main.py` 文件(一个 Python「模块」)。 +* `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 +* `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。 + +/// 在输出中,会有一行信息像下面这样: @@ -133,20 +135,23 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 ### 步骤 1:导入 `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` 是一个为你的 API 提供了所有功能的 Python 类。 -!!! note "技术细节" - `FastAPI` 是直接从 `Starlette` 继承的类。 +/// note | 技术细节 + +`FastAPI` 是直接从 `Starlette` 继承的类。 + +你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 - 你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 +/// ### 步骤 2:创建一个 `FastAPI`「实例」 ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 这里的变量 `app` 会是 `FastAPI` 类的一个「实例」。 @@ -168,7 +173,7 @@ $ uvicorn main:app --reload 如果你像下面这样创建应用: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` 将代码放入 `main.py` 文件中,然后你可以像下面这样运行 `uvicorn`: @@ -201,8 +206,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - 「路径」也通常被称为「端点」或「路由」。 +/// info + +「路径」也通常被称为「端点」或「路由」。 + +/// 开发 API 时,「路径」是用来分离「关注点」和「资源」的主要手段。 @@ -244,7 +252,7 @@ https://example.com/items/foo #### 定义一个*路径操作装饰器* ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")` 告诉 **FastAPI** 在它下方的函数负责处理如下访问请求: @@ -252,16 +260,19 @@ https://example.com/items/foo * 请求路径为 `/` * 使用 get 操作 -!!! info "`@decorator` Info" - `@something` 语法在 Python 中被称为「装饰器」。 +/// info | `@decorator` Info + +`@something` 语法在 Python 中被称为「装饰器」。 - 像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。 +像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。 - 装饰器接收位于其下方的函数并且用它完成一些工作。 +装饰器接收位于其下方的函数并且用它完成一些工作。 - 在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。 +在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。 - 它是一个「**路径操作装饰器**」。 +它是一个「**路径操作装饰器**」。 + +/// 你也可以使用其他的操作: @@ -276,14 +287,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip - 您可以随意使用任何一个操作(HTTP方法)。 +/// tip + +您可以随意使用任何一个操作(HTTP方法)。 + +**FastAPI** 没有强制要求操作有任何特定的含义。 - **FastAPI** 没有强制要求操作有任何特定的含义。 +此处提供的信息仅作为指导,而不是要求。 - 此处提供的信息仅作为指导,而不是要求。 +比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。 - 比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。 +/// ### 步骤 4:定义**路径操作函数** @@ -294,7 +308,7 @@ https://example.com/items/foo * **函数**:是位于「装饰器」下方的函数(位于 `@app.get("/")` 下方)。 ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 这是一个 Python 函数。 @@ -308,16 +322,19 @@ https://example.com/items/foo 你也可以将其定义为常规函数而不使用 `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` -!!! note - 如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。 +/// note + +如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。 + +/// ### 步骤 5:返回内容 ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 你可以返回一个 `dict`、`list`,像 `str`、`int` 一样的单个值,等等。 diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md index 701cd241e..799e81eb2 100644 --- a/docs/zh/docs/tutorial/handling-errors.md +++ b/docs/zh/docs/tutorial/handling-errors.md @@ -26,7 +26,7 @@ ### 导入 `HTTPException` ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` @@ -43,7 +43,7 @@ 本例中,客户端用 `ID` 请求的 `item` 不存在时,触发状态码为 `404` 的异常: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` @@ -67,14 +67,15 @@ ``` -!!! tip "提示" +/// tip | 提示 - 触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。 +触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。 - 还支持传递 `dict`、`list` 等数据结构。 +还支持传递 `dict`、`list` 等数据结构。 - **FastAPI** 能自动处理这些数据,并将之转换为 JSON。 +**FastAPI** 能自动处理这些数据,并将之转换为 JSON。 +/// ## 添加自定义响应头 @@ -85,7 +86,7 @@ 但对于某些高级应用场景,还是需要添加自定义响应头: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` @@ -100,7 +101,7 @@ 此时,可以用 `@app.exception_handler()` 添加自定义异常控制器: ```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` @@ -115,12 +116,13 @@ ``` -!!! note "技术细节" +/// note | 技术细节 - `from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。 +`from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。 - **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。 +**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。 +/// ## 覆盖默认异常处理器 @@ -141,7 +143,7 @@ 这样,异常处理器就可以接收 `Request` 与异常。 ```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` @@ -174,10 +176,11 @@ path -> item_id ### `RequestValidationError` vs `ValidationError` -!!! warning "警告" +/// warning | 警告 - 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 +如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 +/// `RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。 @@ -196,16 +199,17 @@ path -> item_id 例如,只为错误返回纯文本响应,而不是返回 JSON 格式的内容: ```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` -!!! note "技术细节" +/// note | 技术细节 - 还可以使用 `from starlette.responses import PlainTextResponse`。 +还可以使用 `from starlette.responses import PlainTextResponse`。 - **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。 +**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。 +/// ### 使用 `RequestValidationError` 的请求体 @@ -214,7 +218,7 @@ path -> item_id 开发时,可以用这个请求体生成日志、调试错误,并返回给用户。 ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} +{!../../docs_src/handling_errors/tutorial005.py!} ``` @@ -280,7 +284,7 @@ FastAPI 支持先对异常进行某些处理,然后再使用 **FastAPI** 中 从 `fastapi.exception_handlers` 中导入要复用的默认异常处理器: ```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` diff --git a/docs/zh/docs/tutorial/header-params.md b/docs/zh/docs/tutorial/header-params.md index 25dfeba87..c45a6b095 100644 --- a/docs/zh/docs/tutorial/header-params.md +++ b/docs/zh/docs/tutorial/header-params.md @@ -6,41 +6,57 @@ 首先,导入 `Header`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="3" +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../docs_src/header_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="1" +{!> ../../docs_src/header_params/tutorial001_py310.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="3" +{!> ../../docs_src/header_params/tutorial001.py!} +``` - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +//// ## 声明 `Header` 参数 @@ -48,51 +64,71 @@ 第一个值是默认值,还可以传递所有验证参数或注释参数: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="10" +{!> ../../docs_src/header_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="7" +{!> ../../docs_src/header_params/tutorial001_py310.py!} +``` + +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +//// tab | Python 3.8+ non-Annotated -!!! note "技术细节" +/// tip - `Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。 +尽可能选择使用 `Annotated` 的版本。 - 注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。 +/// + +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial001.py!} +``` -!!! info "说明" +//// - 必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。 +/// note | 技术细节 + +`Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。 + +注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。 + +/// + +/// info | 说明 + +必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。 + +/// ## 自动转换 @@ -110,46 +146,63 @@ 如需禁用下划线自动转换为连字符,可以把 `Header` 的 `convert_underscores` 参数设置为 `False`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/header_params/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="11" +{!> ../../docs_src/header_params/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../docs_src/header_params/tutorial002_an.py!} +``` + +//// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.9+" +/// tip - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+" +/// + +```Python hl_lines="8" +{!> ../../docs_src/header_params/tutorial002_py310.py!} +``` - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="10" +{!> ../../docs_src/header_params/tutorial002.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +//// -!!! warning "警告" +/// warning | 警告 - 注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。 +注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。 +/// ## 重复的请求头 @@ -161,50 +214,71 @@ 例如,声明 `X-Token` 多次出现的请求头,可以写成这样: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003_an_py310.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003_an_py39.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python hl_lines="10" +{!> ../../docs_src/header_params/tutorial003_an.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +//// -=== "Python 3.9+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +Prefer to use the `Annotated` version if possible. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="7" +{!> ../../docs_src/header_params/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="9" +{!> ../../docs_src/header_params/tutorial003.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +//// 与*路径操作*通信时,以下面的方式发送两个 HTTP 请求头: diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md index 6180d3de3..ab19f02c5 100644 --- a/docs/zh/docs/tutorial/index.md +++ b/docs/zh/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ......以上安装还包括了 `uvicorn`,你可以将其用作运行代码的服务器。 -!!! note - 你也可以分开来安装。 +/// note - 假如你想将应用程序部署到生产环境,你可能要执行以下操作: +你也可以分开来安装。 - ``` - pip install fastapi - ``` +假如你想将应用程序部署到生产环境,你可能要执行以下操作: - 并且安装`uvicorn`来作为服务器: +``` +pip install fastapi +``` + +并且安装`uvicorn`来作为服务器: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +然后对你想使用的每个可选依赖项也执行相同的操作。 - 然后对你想使用的每个可选依赖项也执行相同的操作。 +/// ## 进阶用户指南 diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md index 8170e6ecc..2398f3e01 100644 --- a/docs/zh/docs/tutorial/metadata.md +++ b/docs/zh/docs/tutorial/metadata.md @@ -1,101 +1,110 @@ -# 元数据和文档 URL - -你可以在 FastAPI 应用程序中自定义多个元数据配置。 - -## API 元数据 - -你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段: - -| 参数 | 类型 | 描述 | -|------------|------|-------------| -| `title` | `str` | API 的标题。 | -| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. | -| `description` | `str` | API 的简短描述。可以使用Markdown。 | -| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 | -| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 | -| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。
contact 字段
参数Type描述
namestr联系人/组织的识别名称。
urlstr指向联系信息的 URL。必须采用 URL 格式。
emailstr联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。
| -| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。
license_info 字段
参数类型描述
namestr必须的 (如果设置了license_info). 用于 API 的许可证名称。
identifierstr一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。
urlstr用于 API 的许可证的 URL。必须采用 URL 格式。
| - -你可以按如下方式设置它们: - -```Python hl_lines="4-6" -{!../../../docs_src/metadata/tutorial001.py!} -``` - -!!! tip - 您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。 - -通过这样设置,自动 API 文档看起来会像: - - - -## 标签元数据 - -### 创建标签元数据 - -让我们在带有标签的示例中为 `users` 和 `items` 试一下。 - -创建标签元数据并把它传递给 `openapi_tags` 参数: - -```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} -``` - -注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。 - -!!! 提示 - 不必为你使用的所有标签都添加元数据。 - -### 使用你的标签 - -将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签: - -```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} -``` - -!!! 信息 - 阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。 - -### 查看文档 - -如果你现在查看文档,它们会显示所有附加的元数据: - - - -### 标签顺序 - -每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。 - -例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。 - -## OpenAPI URL - -默认情况下,OpenAPI 模式服务于 `/openapi.json`。 - -但是你可以通过参数 `openapi_url` 对其进行配置。 - -例如,将其设置为服务于 `/api/v1/openapi.json`: - -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} -``` - -如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。 - -## 文档 URLs - -你可以配置两个文档用户界面,包括: - -* **Swagger UI**:服务于 `/docs`。 - * 可以使用参数 `docs_url` 设置它的 URL。 - * 可以通过设置 `docs_url=None` 禁用它。 -* ReDoc:服务于 `/redoc`。 - * 可以使用参数 `redoc_url` 设置它的 URL。 - * 可以通过设置 `redoc_url=None` 禁用它。 - -例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc: - -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} -``` +# 元数据和文档 URL + +你可以在 FastAPI 应用程序中自定义多个元数据配置。 + +## API 元数据 + +你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段: + +| 参数 | 类型 | 描述 | +|------------|------|-------------| +| `title` | `str` | API 的标题。 | +| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. | +| `description` | `str` | API 的简短描述。可以使用Markdown。 | +| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 | +| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 | +| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。
contact 字段
参数Type描述
namestr联系人/组织的识别名称。
urlstr指向联系信息的 URL。必须采用 URL 格式。
emailstr联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。
| +| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。
license_info 字段
参数类型描述
namestr必须的 (如果设置了license_info). 用于 API 的许可证名称。
identifierstr一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。
urlstr用于 API 的许可证的 URL。必须采用 URL 格式。
| + +你可以按如下方式设置它们: + +```Python hl_lines="4-6" +{!../../docs_src/metadata/tutorial001.py!} +``` + +/// tip + +您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。 + +/// + +通过这样设置,自动 API 文档看起来会像: + + + +## 标签元数据 + +### 创建标签元数据 + +让我们在带有标签的示例中为 `users` 和 `items` 试一下。 + +创建标签元数据并把它传递给 `openapi_tags` 参数: + +```Python hl_lines="3-16 18" +{!../../docs_src/metadata/tutorial004.py!} +``` + +注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。 + +/// tip | 提示 + +不必为你使用的所有标签都添加元数据。 + +/// + +### 使用你的标签 + +将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签: + +```Python hl_lines="21 26" +{!../../docs_src/metadata/tutorial004.py!} +``` + +/// info | 信息 + +阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。 + +/// + +### 查看文档 + +如果你现在查看文档,它们会显示所有附加的元数据: + + + +### 标签顺序 + +每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。 + +例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。 + +## OpenAPI URL + +默认情况下,OpenAPI 模式服务于 `/openapi.json`。 + +但是你可以通过参数 `openapi_url` 对其进行配置。 + +例如,将其设置为服务于 `/api/v1/openapi.json`: + +```Python hl_lines="3" +{!../../docs_src/metadata/tutorial002.py!} +``` + +如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。 + +## 文档 URLs + +你可以配置两个文档用户界面,包括: + +* **Swagger UI**:服务于 `/docs`。 + * 可以使用参数 `docs_url` 设置它的 URL。 + * 可以通过设置 `docs_url=None` 禁用它。 +* ReDoc:服务于 `/redoc`。 + * 可以使用参数 `redoc_url` 设置它的 URL。 + * 可以通过设置 `redoc_url=None` 禁用它。 + +例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc: + +```Python hl_lines="3" +{!../../docs_src/metadata/tutorial003.py!} +``` diff --git a/docs/zh/docs/tutorial/middleware.md b/docs/zh/docs/tutorial/middleware.md index c9a7e7725..8076f8d52 100644 --- a/docs/zh/docs/tutorial/middleware.md +++ b/docs/zh/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * 它可以对该**响应**做些什么或者执行任何需要的代码. * 然后它返回这个 **响应**. -!!! note "技术细节" - 如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行. +/// note | 技术细节 - 如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行. +如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行. + +如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行. + +/// ## 创建中间件 @@ -29,18 +32,24 @@ * 然后你可以在返回 `response` 前进一步修改它. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` -!!! tip - 请记住可以 用'X-' 前缀添加专有自定义请求头. +/// tip + +请记住可以 用'X-' 前缀添加专有自定义请求头. + +但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中. + +/// + +/// note | 技术细节 - 但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中. +你也可以使用 `from starlette.requests import Request`. -!!! note "技术细节" - 你也可以使用 `from starlette.requests import Request`. +**FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette. - **FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette. +/// ### 在 `response` 的前和后 @@ -51,7 +60,7 @@ 例如你可以添加自定义请求头 `X-Process-Time` 包含以秒为单位的接收请求和生成响应的时间: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## 其他中间件 diff --git a/docs/zh/docs/tutorial/path-operation-configuration.md b/docs/zh/docs/tutorial/path-operation-configuration.md index f79b0e692..add370d1c 100644 --- a/docs/zh/docs/tutorial/path-operation-configuration.md +++ b/docs/zh/docs/tutorial/path-operation-configuration.md @@ -2,9 +2,11 @@ *路径操作装饰器*支持多种配置参数。 -!!! warning "警告" +/// warning | 警告 - 注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。 +注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。 + +/// ## `status_code` 状态码 @@ -15,23 +17,25 @@ 如果记不住数字码的涵义,也可以用 `status` 的快捷常量: ```Python hl_lines="3 17" -{!../../../docs_src/path_operation_configuration/tutorial001.py!} +{!../../docs_src/path_operation_configuration/tutorial001.py!} ``` 状态码在响应中使用,并会被添加到 OpenAPI 概图。 -!!! note "技术细节" +/// note | 技术细节 + +也可以使用 `from starlette import status` 导入状态码。 - 也可以使用 `from starlette import status` 导入状态码。 +**FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。 - **FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。 +/// ## `tags` 参数 `tags` 参数的值是由 `str` 组成的 `list` (一般只有一个 `str` ),`tags` 用于为*路径操作*添加标签: ```Python hl_lines="17 22 27" -{!../../../docs_src/path_operation_configuration/tutorial002.py!} +{!../../docs_src/path_operation_configuration/tutorial002.py!} ``` OpenAPI 概图会自动添加标签,供 API 文档接口使用: @@ -43,7 +47,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: 路径装饰器还支持 `summary` 和 `description` 这两个参数: ```Python hl_lines="20-21" -{!../../../docs_src/path_operation_configuration/tutorial003.py!} +{!../../docs_src/path_operation_configuration/tutorial003.py!} ``` ## 文档字符串(`docstring`) @@ -53,7 +57,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: 文档字符串支持 Markdown,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。 ```Python hl_lines="19-27" -{!../../../docs_src/path_operation_configuration/tutorial004.py!} +{!../../docs_src/path_operation_configuration/tutorial004.py!} ``` 下图为 Markdown 文本在 API 文档中的显示效果: @@ -65,18 +69,22 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: `response_description` 参数用于定义响应的描述说明: ```Python hl_lines="21" -{!../../../docs_src/path_operation_configuration/tutorial005.py!} +{!../../docs_src/path_operation_configuration/tutorial005.py!} ``` -!!! info "说明" +/// info | 说明 + +注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。 + +/// - 注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。 +/// check | 检查 -!!! check "检查" +OpenAPI 规定每个*路径操作*都要有响应描述。 - OpenAPI 规定每个*路径操作*都要有响应描述。 +如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。 - 如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。 +/// @@ -85,7 +93,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: `deprecated` 参数可以把*路径操作*标记为弃用,无需直接删除: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` API 文档会把该路径操作标记为弃用: diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md index 9b41ad7cf..3a1ebdbca 100644 --- a/docs/zh/docs/tutorial/path-params-numeric-validations.md +++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md @@ -6,41 +6,57 @@ 首先,从 `fastapi` 导入 `Path`: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +```Python hl_lines="1 3" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ -=== "Python 3.9+" +```Python hl_lines="1 3" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` + +//// - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="3-4" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.10+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="1" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +/// + +```Python hl_lines="3" +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// ## 声明元数据 @@ -48,48 +64,67 @@ 例如,要声明路径参数 `item_id`的 `title` 元数据值,你可以输入: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.10+ non-Annotated" +```Python hl_lines="11" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +``` - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +//// - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +/// -!!! note - 路径参数总是必需的,因为它必须是路径的一部分。 +```Python hl_lines="8" +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +``` - 所以,你应该在声明时使用 `...` 将其标记为必需参数。 +//// - 然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。 +//// tab | Python 3.8+ non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +```Python hl_lines="10" +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +//// + +/// note + +路径参数总是必需的,因为它必须是路径的一部分。 + +所以,你应该在声明时使用 `...` 将其标记为必需参数。 + +然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。 + +/// ## 按需对参数排序 @@ -107,14 +142,19 @@ 因此,你可以将函数声明为: -=== "Python 3.8 non-Annotated" +//// tab | Python 3.8 non-Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// + +```Python hl_lines="7" +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +//// ## 按需对参数排序的技巧 @@ -125,7 +165,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参数都应作为关键字参数(键值对),也被称为 kwargs,来调用。即使它们没有默认值。 ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## 数值校验:大于等于 @@ -135,7 +175,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 像下面这样,添加 `ge=1` 后,`item_id` 将必须是一个大于(`g`reater than)或等于(`e`qual)`1` 的整数。 ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## 数值校验:大于和小于等于 @@ -146,7 +186,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 * `le`:小于等于(`l`ess than or `e`qual) ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## 数值校验:浮点数、大于和小于 @@ -160,7 +200,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 对于 lt 也是一样的。 ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## 总结 @@ -174,18 +214,24 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 * `lt`:小于(`l`ess `t`han) * `le`:小于等于(`l`ess than or `e`qual) -!!! info - `Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。 +/// info + +`Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。 + +而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。 + +/// + +/// note | 技术细节 - 而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。 +当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。 -!!! note "技术细节" - 当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。 +当被调用时,它们返回同名类的实例。 - 当被调用时,它们返回同名类的实例。 +如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。 - 如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。 +因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。 - 因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。 +这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。 - 这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。 +/// diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md index 5bb4eba80..0666783e2 100644 --- a/docs/zh/docs/tutorial/path-params.md +++ b/docs/zh/docs/tutorial/path-params.md @@ -1,48 +1,54 @@ # 路径参数 -你可以使用与 Python 格式化字符串相同的语法来声明路径"参数"或"变量": +FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**变量**): ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` -路径参数 `item_id` 的值将作为参数 `item_id` 传递给你的函数。 +这段代码把路径参数 `item_id` 的值传递给路径函数的参数 `item_id`。 -所以,如果你运行示例并访问 http://127.0.0.1:8000/items/foo,将会看到如下响应: +运行示例并访问 http://127.0.0.1:8000/items/foo,可获得如下响应: ```JSON {"item_id":"foo"} ``` -## 有类型的路径参数 +## 声明路径参数的类型 -你可以使用标准的 Python 类型标注为函数中的路径参数声明类型。 +使用 Python 标准类型注解,声明路径操作函数中路径参数的类型。 ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` -在这个例子中,`item_id` 被声明为 `int` 类型。 +本例把 `item_id` 的类型声明为 `int`。 -!!! check - 这将为你的函数提供编辑器支持,包括错误检查、代码补全等等。 +/// check | 检查 -## 数据转换 +类型声明将为函数提供错误检查、代码补全等编辑器支持。 -如果你运行示例并打开浏览器访问 http://127.0.0.1:8000/items/3,将得到如下响应: +/// + +## 数据转换 + +运行示例并访问 http://127.0.0.1:8000/items/3,返回的响应如下: ```JSON {"item_id":3} ``` -!!! check - 注意函数接收(并返回)的值为 3,是一个 Python `int` 值,而不是字符串 `"3"`。 +/// check | 检查 + +注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。 - 所以,**FastAPI** 通过上面的类型声明提供了对请求的自动"解析"。 +**FastAPI** 通过类型声明自动**解析**请求中的数据。 + +/// ## 数据校验 -但如果你通过浏览器访问 http://127.0.0.1:8000/items/foo,你会看到一个清晰可读的 HTTP 错误: +通过浏览器访问 http://127.0.0.1:8000/items/foo,接收如下 HTTP 错误信息: ```JSON { @@ -59,176 +65,204 @@ } ``` -因为路径参数 `item_id` 传入的值为 `"foo"`,它不是一个 `int`。 +这是因为路径参数 `item_id` 的值 (`"foo"`)的类型不是 `int`。 + +值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: http://127.0.0.1:8000/items/4.2。 + +/// check | 检查 -如果你提供的是 `float` 而非整数也会出现同样的错误,比如: http://127.0.0.1:8000/items/4.2 +**FastAPI** 使用 Python 类型声明实现了数据校验。 -!!! check - 所以,通过同样的 Python 类型声明,**FastAPI** 提供了数据校验功能。 +注意,上面的错误清晰地指出了未通过校验的具体原因。 - 注意上面的错误同样清楚地指出了校验未通过的具体原因。 +这在开发调试与 API 交互的代码时非常有用。 - 在开发和调试与你的 API 进行交互的代码时,这非常有用。 +/// -## 文档 +## 查看文档 -当你打开浏览器访问 http://127.0.0.1:8000/docs,你将看到自动生成的交互式 API 文档: +访问 http://127.0.0.1:8000/docs,查看自动生成的 API 文档: - + -!!! check - 再一次,还是通过相同的 Python 类型声明,**FastAPI** 为你提供了自动生成的交互式文档(集成 Swagger UI)。 +/// check | 检查 - 注意这里的路径参数被声明为一个整数。 +还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。 -## 基于标准的好处:可选文档 +注意,路径参数的类型是整数。 -由于生成的 API 模式来自于 OpenAPI 标准,所以有很多工具与其兼容。 +/// -正因如此,**FastAPI** 内置了一个可选的 API 文档(使用 Redoc): +## 基于标准的好处,备选文档 - +**FastAPI** 使用 OpenAPI 生成概图,所以能兼容很多工具。 -同样的,还有很多其他兼容的工具,包括适用于多种语言的代码生成工具。 +因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 http://127.0.0.1:8000/redoc: + + + +同样,还有很多兼容工具,包括多种语言的代码生成工具。 ## Pydantic -所有的数据校验都由 Pydantic 在幕后完成,所以你可以从它所有的优点中受益。并且你知道它在这方面非常胜任。 +FastAPI 充分地利用了 Pydantic 的优势,用它在后台校验数据。众所周知,Pydantic 擅长的就是数据校验。 -你可以使用同样的类型声明来声明 `str`、`float`、`bool` 以及许多其他的复合数据类型。 +同样,`str`、`float`、`bool` 以及很多复合数据类型都可以使用类型声明。 -本教程的下一章节将探讨其中的一些内容。 +下一章介绍详细内容。 ## 顺序很重要 -在创建*路径操作*时,你会发现有些情况下路径是固定的。 +有时,*路径操作*中的路径是写死的。 + +比如要使用 `/users/me` 获取当前用户的数据。 -比如 `/users/me`,我们假设它用来获取关于当前用户的数据. +然后还要使用 `/users/{user_id}`,通过用户 ID 获取指定用户的数据。 -然后,你还可以使用路径 `/users/{user_id}` 来通过用户 ID 获取关于特定用户的数据。 +由于*路径操作*是按顺序依次运行的,因此,一定要在 `/users/{user_id}` 之前声明 `/users/me` : -由于*路径操作*是按顺序依次运行的,你需要确保路径 `/users/me` 声明在路径 `/users/{user_id}`之前: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` -否则,`/users/{user_id}` 的路径还将与 `/users/me` 相匹配,"认为"自己正在接收一个值为 `"me"` 的 `user_id` 参数。 +否则,`/users/{user_id}` 将匹配 `/users/me`,FastAPI 会**认为**正在接收值为 `"me"` 的 `user_id` 参数。 ## 预设值 -如果你有一个接收路径参数的路径操作,但你希望预先设定可能的有效参数值,则可以使用标准的 Python `Enum` 类型。 +路径操作使用 Python 的 `Enum` 类型接收预设的*路径参数*。 -### 创建一个 `Enum` 类 +### 创建 `Enum` 类 -导入 `Enum` 并创建一个继承自 `str` 和 `Enum` 的子类。 +导入 `Enum` 并创建继承自 `str` 和 `Enum` 的子类。 -通过从 `str` 继承,API 文档将能够知道这些值必须为 `string` 类型并且能够正确地展示出来。 +通过从 `str` 继承,API 文档就能把值的类型定义为**字符串**,并且能正确渲染。 -然后创建具有固定值的类属性,这些固定值将是可用的有效值: +然后,创建包含固定值的类属性,这些固定值是可用的有效值: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! info - 枚举(或 enums)从 3.4 版本起在 Python 中可用。 +/// info | 说明 + +Python 3.4 及之后版本支持枚举(即 enums)。 + +/// + +/// tip | 提示 -!!! tip - 如果你想知道,"AlexNet"、"ResNet" 和 "LeNet" 只是机器学习中的模型名称。 +**AlexNet**、**ResNet**、**LeNet** 是机器学习模型。 + +/// ### 声明*路径参数* -然后使用你定义的枚举类(`ModelName`)创建一个带有类型标注的*路径参数*: +使用 Enum 类(`ModelName`)创建使用类型注解的*路径参数*: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### 查看文档 -因为已经指定了*路径参数*的可用值,所以交互式文档可以恰当地展示它们: + API 文档会显示预定义*路径参数*的可用值: - + -### 使用 Python *枚举类型* +### 使用 Python _枚举类型_ -*路径参数*的值将是一个*枚举成员*。 +*路径参数*的值是枚举的元素。 -#### 比较*枚举成员* +#### 比较*枚举元素* -你可以将它与你创建的枚举类 `ModelName` 中的*枚举成员*进行比较: +枚举类 `ModelName` 中的*枚举元素*支持比较操作: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### 获取*枚举值* -你可以使用 `model_name.value` 或通常来说 `your_enum_member.value` 来获取实际的值(在这个例子中为 `str`): +使用 `model_name.value` 或 `your_enum_member.value` 获取实际的值(本例中为**字符串**): -```Python hl_lines="19" -{!../../../docs_src/path_params/tutorial005.py!} +```Python hl_lines="20" +{!../../docs_src/path_params/tutorial005.py!} ``` -!!! tip - 你也可以通过 `ModelName.lenet.value` 来获取值 `"lenet"`。 +/// tip | 提示 + +使用 `ModelName.lenet.value` 也能获取值 `"lenet"`。 + +/// -#### 返回*枚举成员* +#### 返回*枚举元素* -你可以从*路径操作*中返回*枚举成员*,即使嵌套在 JSON 结构中(例如一个 `dict` 中)。 +即使嵌套在 JSON 请求体里(例如, `dict`),也可以从*路径操作*返回*枚举元素*。 -在返回给客户端之前,它们将被转换为对应的值: +返回给客户端之前,要把枚举元素转换为对应的值(本例中为字符串): -```Python hl_lines="18-21" -{!../../../docs_src/path_params/tutorial005.py!} +```Python hl_lines="18 21 23" +{!../../docs_src/path_params/tutorial005.py!} +``` + +客户端中的 JSON 响应如下: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} ``` ## 包含路径的路径参数 -假设你有一个*路径操作*,它的路径为 `/files/{file_path}`。 +假设*路径操作*的路径为 `/files/{file_path}`。 -但是你需要 `file_path` 自身也包含*路径*,比如 `home/johndoe/myfile.txt`。 +但需要 `file_path` 中也包含*路径*,比如,`home/johndoe/myfile.txt`。 -因此,该文件的URL将类似于这样:`/files/home/johndoe/myfile.txt`。 +此时,该文件的 URL 是这样的:`/files/home/johndoe/myfile.txt`。 ### OpenAPI 支持 -OpenAPI 不支持任何方式去声明*路径参数*以在其内部包含*路径*,因为这可能会导致难以测试和定义的情况出现。 +OpenAPI 不支持声明包含路径的*路径参数*,因为这会导致测试和定义更加困难。 -不过,你仍然可以通过 Starlette 的一个内部工具在 **FastAPI** 中实现它。 +不过,仍可使用 Starlette 内置工具在 **FastAPI** 中实现这一功能。 -而且文档依旧可以使用,但是不会添加任何该参数应包含路径的说明。 +而且不影响文档正常运行,但是不会添加该参数包含路径的说明。 ### 路径转换器 -你可以使用直接来自 Starlette 的选项来声明一个包含*路径*的*路径参数*: +直接使用 Starlette 的选项声明包含*路径*的*路径参数*: ``` /files/{file_path:path} ``` -在这种情况下,参数的名称为 `file_path`,结尾部分的 `:path` 说明该参数应匹配任意的*路径*。 +本例中,参数名为 `file_path`,结尾部分的 `:path` 说明该参数应匹配*路径*。 -因此,你可以这样使用它: +用法如下: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` -!!! tip - 你可能会需要参数包含 `/home/johndoe/myfile.txt`,以斜杠(`/`)开头。 +/// tip | 提示 + +注意,包含 `/home/johndoe/myfile.txt` 的路径参数要以斜杠(`/`)开头。 + +本例中的 URL 是 `/files//home/johndoe/myfile.txt`。注意,`files` 和 `home` 之间要使用**双斜杠**(`//`)。 - 在这种情况下,URL 将会是 `/files//home/johndoe/myfile.txt`,在`files` 和 `home` 之间有一个双斜杠(`//`)。 +/// -## 总结 +## 小结 -使用 **FastAPI**,通过简短、直观和标准的 Python 类型声明,你将获得: +通过简短、直观的 Python 标准类型声明,**FastAPI** 可以获得: -* 编辑器支持:错误检查,代码补全等 -* 数据 "解析" -* 数据校验 -* API 标注和自动生成的文档 +- 编辑器支持:错误检查,代码自动补全等 +- 数据**解析** +- 数据校验 +- API 注解和 API 文档 -而且你只需要声明一次即可。 +只需要声明一次即可。 -这可能是 **FastAPI** 与其他框架相比主要的明显优势(除了原始性能以外)。 +这可能是除了性能以外,**FastAPI** 与其它框架相比的主要优势。 diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md index af0428837..70e6f8a96 100644 --- a/docs/zh/docs/tutorial/query-params-str-validations.md +++ b/docs/zh/docs/tutorial/query-params-str-validations.md @@ -4,17 +4,21 @@ 让我们以下面的应用程序为例: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +//// 查询参数 `q` 的类型为 `str`,默认值为 `None`,因此它是可选的。 @@ -27,7 +31,7 @@ 为此,首先从 `fastapi` 导入 `Query`: ```Python hl_lines="1" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` ## 使用 `Query` 作为默认值 @@ -35,7 +39,7 @@ 现在,将 `Query` 用作查询参数的默认值,并将它的 `max_length` 参数设置为 50: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` 由于我们必须用 `Query(default=None)` 替换默认值 `None`,`Query` 的第一个参数同样也是用于定义默认值。 @@ -67,7 +71,7 @@ q: Union[str, None] = Query(default=None, max_length=50) 你还可以添加 `min_length` 参数: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} +{!../../docs_src/query_params_str_validations/tutorial003.py!} ``` ## 添加正则表达式 @@ -75,7 +79,7 @@ q: Union[str, None] = Query(default=None, max_length=50) 你可以定义一个参数值必须匹配的正则表达式: ```Python hl_lines="11" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` 这个指定的正则表达式通过以下规则检查接收到的参数值: @@ -95,11 +99,14 @@ q: Union[str, None] = Query(default=None, max_length=50) 假设你想要声明查询参数 `q`,使其 `min_length` 为 `3`,并且默认值为 `fixedquery`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` -!!! note - 具有默认值还会使该参数成为可选参数。 +/// note + +具有默认值还会使该参数成为可选参数。 + +/// ## 声明为必需参数 @@ -124,7 +131,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 因此,当你在使用 `Query` 且需要声明一个值是必需的时,只需不声明默认参数: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` ### 使用省略号(`...`)声明必需参数 @@ -132,12 +139,15 @@ q: Union[str, None] = Query(default=None, min_length=3) 有另一种方法可以显式的声明一个值是必需的,即将默认参数的默认值设为 `...` : ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006b.py!} +{!../../docs_src/query_params_str_validations/tutorial006b.py!} ``` -!!! info - 如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为「省略号」。 - Pydantic 和 FastAPI 使用它来显式的声明需要一个值。 +/// info + +如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为「省略号」。 +Pydantic 和 FastAPI 使用它来显式的声明需要一个值。 + +/// 这将使 **FastAPI** 知道此查询参数是必需的。 @@ -148,23 +158,28 @@ q: Union[str, None] = Query(default=None, min_length=3) 为此,你可以声明`None`是一个有效的类型,并仍然使用`default=...`: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial006c.py!} +{!../../docs_src/query_params_str_validations/tutorial006c.py!} ``` -!!! tip - Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。 +/// tip + +Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。 + +/// ### 使用Pydantic中的`Required`代替省略号(`...`) 如果你觉得使用 `...` 不舒服,你也可以从 Pydantic 导入并使用 `Required`: ```Python hl_lines="2 8" -{!../../../docs_src/query_params_str_validations/tutorial006d.py!} +{!../../docs_src/query_params_str_validations/tutorial006d.py!} ``` -!!! tip - 请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required` +/// tip + +请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required` +/// ## 查询参数列表 / 多个值 @@ -173,7 +188,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 例如,要声明一个可在 URL 中出现多次的查询参数 `q`,你可以这样写: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` 然后,输入如下网址: @@ -195,8 +210,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip - 要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。 +/// tip + +要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。 + +/// 交互式 API 文档将会相应地进行更新,以允许使用多个值: @@ -207,7 +225,7 @@ http://localhost:8000/items/?q=foo&q=bar 你还可以定义在没有任何给定值时的默认 `list` 值: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` 如果你访问: @@ -232,13 +250,16 @@ http://localhost:8000/items/ 你也可以直接使用 `list` 代替 `List [str]`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` -!!! note - 请记住,在这种情况下 FastAPI 将不会检查列表的内容。 +/// note - 例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。 +请记住,在这种情况下 FastAPI 将不会检查列表的内容。 + +例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。 + +/// ## 声明更多元数据 @@ -246,21 +267,24 @@ http://localhost:8000/items/ 这些信息将包含在生成的 OpenAPI 模式中,并由文档用户界面和外部工具所使用。 -!!! note - 请记住,不同的工具对 OpenAPI 的支持程度可能不同。 +/// note + +请记住,不同的工具对 OpenAPI 的支持程度可能不同。 + +其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。 - 其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。 +/// 你可以添加 `title`: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` 以及 `description`: ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## 别名参数 @@ -282,7 +306,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 这时你可以用 `alias` 参数声明一个别名,该别名将用于在 URL 中查找查询参数值: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## 弃用参数 @@ -294,7 +318,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 那么将参数 `deprecated=True` 传入 `Query`: ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` 文档将会像下面这样展示它: diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md index a0cc7fea3..4a9917be2 100644 --- a/docs/zh/docs/tutorial/query-params.md +++ b/docs/zh/docs/tutorial/query-params.md @@ -1,95 +1,122 @@ # 查询参数 -声明不属于路径参数的其他函数参数时,它们将被自动解释为"查询字符串"参数 +声明的参数不是路径参数时,路径操作函数会把该参数自动解释为**查询**参数。 ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` -查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,并以 `&` 符号分隔。 +查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,以 `&` 分隔。 -例如,在以下 url 中: +例如,以下 URL 中: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 ``` -...查询参数为: +……查询参数为: -* `skip`:对应的值为 `0` -* `limit`:对应的值为 `10` +* `skip`:值为 `0` +* `limit`:值为 `10` -由于它们是 URL 的一部分,因此它们的"原始值"是字符串。 +这些值都是 URL 的组成部分,因此,它们的类型**本应**是字符串。 -但是,当你为它们声明了 Python 类型(在上面的示例中为 `int`)时,它们将转换为该类型并针对该类型进行校验。 +但声明 Python 类型(上例中为 `int`)之后,这些值就会转换为声明的类型,并进行类型校验。 -应用于路径参数的所有相同过程也适用于查询参数: +所有应用于路径参数的流程也适用于查询参数: -* (很明显的)编辑器支持 -* 数据"解析" +* (显而易见的)编辑器支持 +* 数据**解析** * 数据校验 -* 自动生成文档 +* API 文档 ## 默认值 -由于查询参数不是路径的固定部分,因此它们可以是可选的,并且可以有默认值。 +查询参数不是路径的固定内容,它是可选的,还支持默认值。 -在上面的示例中,它们具有 `skip=0` 和 `limit=10` 的默认值。 +上例用 `skip=0` 和 `limit=10` 设定默认值。 -因此,访问 URL: +访问 URL: ``` http://127.0.0.1:8000/items/ ``` -将与访问以下地址相同: +与访问以下地址相同: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 ``` -但是,如果你访问的是: +但如果访问: ``` http://127.0.0.1:8000/items/?skip=20 ``` -函数中的参数值将会是: +查询参数的值就是: * `skip=20`:在 URL 中设定的值 * `limit=10`:使用默认值 ## 可选参数 -通过同样的方式,你可以将它们的默认值设置为 `None` 来声明可选查询参数: +同理,把默认值设为 `None` 即可声明**可选的**查询参数: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +```Python hl_lines="7" +{!> ../../docs_src/query_params/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params/tutorial002.py!} +``` + +//// + +本例中,查询参数 `q` 是可选的,默认值为 `None`。 -=== "Python 3.8+" +/// check | 检查 - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。 +/// -在这个例子中,函数参数 `q` 将是可选的,并且默认值为 `None`。 +/// note | 笔记 -!!! check - 还要注意的是,**FastAPI** 足够聪明,能够分辨出参数 `item_id` 是路径参数而 `q` 不是,因此 `q` 是一个查询参数。 +因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。 + +FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。 + +/// ## 查询参数类型转换 -你还可以声明 `bool` 类型,它们将被自动转换: +参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型: + + +//// tab | Python 3.10+ ```Python hl_lines="7" -{!../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/query_params/tutorial003.py!} ``` -这个例子中,如果你访问: +//// + +本例中,访问: ``` http://127.0.0.1:8000/items/foo?short=1 @@ -119,42 +146,54 @@ http://127.0.0.1:8000/items/foo?short=on http://127.0.0.1:8000/items/foo?short=yes ``` -或任何其他的变体形式(大写,首字母大写等等),你的函数接收的 `short` 参数都会是布尔值 `True`。对于值为 `False` 的情况也是一样的。 +或其它任意大小写形式(大写、首字母大写等),函数接收的 `short` 参数都是布尔值 `True`。值为 `False` 时也一样。 ## 多个路径和查询参数 -你可以同时声明多个路径参数和查询参数,**FastAPI** 能够识别它们。 +**FastAPI** 可以识别同时声明的多个路径参数和查询参数。 + +而且声明查询参数的顺序并不重要。 -而且你不需要以任何特定的顺序来声明。 +FastAPI 通过参数名进行检测: -它们将通过名称被检测到: +//// tab | Python 3.10+ -```Python hl_lines="6 8" -{!../../../docs_src/query_params/tutorial004.py!} +```Python hl_lines="6 8" +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` -## 必需查询参数 +//// -当你为非路径参数声明了默认值时(目前而言,我们所知道的仅有查询参数),则该参数不是必需的。 +//// tab | Python 3.8+ + +```Python hl_lines="8 10" +{!> ../../docs_src/query_params/tutorial004.py!} +``` -如果你不想添加一个特定的值,而只是想使该参数成为可选的,则将默认值设置为 `None`。 +//// -但当你想让一个查询参数成为必需的,不声明任何默认值就可以: +## 必选查询参数 + +为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就**不是必选**的了。 + +如果只想把参数设为**可选**,但又不想指定参数的值,则要把默认值设为 `None`。 + +如果要把查询参数设置为**必选**,就不要声明默认值: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` -这里的查询参数 `needy` 是类型为 `str` 的必需查询参数。 +这里的查询参数 `needy` 是类型为 `str` 的必选查询参数。 -如果你在浏览器中打开一个像下面的 URL: +在浏览器中打开如下 URL: ``` http://127.0.0.1:8000/items/foo-item ``` -...因为没有添加必需的参数 `needy`,你将看到类似以下的错误: +……因为路径中没有必选参数 `needy`,返回的响应中会显示如下错误信息: ```JSON { @@ -171,13 +210,13 @@ http://127.0.0.1:8000/items/foo-item } ``` -由于 `needy` 是必需参数,因此你需要在 URL 中设置它的值: +`needy` 是必选参数,因此要在 URL 中设置值: ``` http://127.0.0.1:8000/items/foo-item?needy=sooooneedy ``` -...这样就正常了: +……这样就正常了: ```JSON { @@ -186,17 +225,32 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy } ``` -当然,你也可以定义一些参数为必需的,一些具有默认值,而某些则完全是可选的: +当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的: -```Python hl_lines="7" -{!../../../docs_src/query_params/tutorial006.py!} +//// tab | Python 3.10+ + +```Python hl_lines="8" +{!> ../../docs_src/query_params/tutorial006_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../docs_src/query_params/tutorial006.py!} ``` -在这个例子中,有3个查询参数: +//// + +本例中有 3 个查询参数: + +* `needy`,必选的 `str` 类型参数 +* `skip`,默认值为 `0` 的 `int` 类型参数 +* `limit`,可选的 `int` 类型参数 + +/// tip | 提示 -* `needy`,一个必需的 `str` 类型参数。 -* `skip`,一个默认值为 `0` 的 `int` 类型参数。 -* `limit`,一个可选的 `int` 类型参数。 +还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。 -!!! tip - 你还可以像在 [路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`。 +/// diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md index 1cd3518cf..5a68d1d3f 100644 --- a/docs/zh/docs/tutorial/request-files.md +++ b/docs/zh/docs/tutorial/request-files.md @@ -2,20 +2,22 @@ `File` 用于定义客户端的上传文件。 -!!! info "说明" +/// info | 说明 - 因为上传文件以「表单数据」形式发送。 +因为上传文件以「表单数据」形式发送。 - 所以接收上传文件,要预先安装 `python-multipart`。 +所以接收上传文件,要预先安装 `python-multipart`。 - 例如: `pip install python-multipart`。 +例如: `pip install python-multipart`。 + +/// ## 导入 `File` 从 `fastapi` 导入 `File` 和 `UploadFile`: ```Python hl_lines="1" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` ## 定义 `File` 参数 @@ -23,18 +25,22 @@ 创建文件(`File`)参数的方式与 `Body` 和 `Form` 一样: ```Python hl_lines="7" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` -!!! info "说明" +/// info | 说明 + +`File` 是直接继承自 `Form` 的类。 + +注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。 - `File` 是直接继承自 `Form` 的类。 +/// - 注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。 +/// tip | 提示 -!!! tip "提示" +声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 - 声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 +/// 文件作为「表单数据」上传。 @@ -49,7 +55,7 @@ 定义文件参数时使用 `UploadFile`: ```Python hl_lines="12" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` `UploadFile` 与 `bytes` 相比有更多优势: @@ -92,13 +98,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 技术细节" +/// note | `async` 技术细节 + +使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。 + +/// - 使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。 +/// note | Starlette 技术细节 -!!! note "Starlette 技术细节" +**FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。 - **FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。 +/// ## 什么是 「表单数据」 @@ -106,42 +116,50 @@ contents = myfile.file.read() **FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。 -!!! note "技术细节" +/// note | 技术细节 - 不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。 +不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。 - 但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。 +但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。 - 编码和表单字段详见 MDN Web 文档的 POST 小节。 +编码和表单字段详见 MDN Web 文档的 POST 小节。 -!!! warning "警告" +/// - 可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。 +/// warning | 警告 - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。 + +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 + +/// ## 可选文件上传 您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7 14" +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} +``` + +//// - ```Python hl_lines="7 14" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9 17" +{!> ../../docs_src/request_files/tutorial001_02.py!} +``` - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +//// ## 带有额外元数据的 `UploadFile` 您也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据: ```Python hl_lines="13" -{!../../../docs_src/request_files/tutorial001_03.py!} +{!../../docs_src/request_files/tutorial001_03.py!} ``` ## 多文件上传 @@ -152,42 +170,52 @@ FastAPI 支持同时上传多个文件。 上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`): -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="8 13" +{!> ../../docs_src/request_files/tutorial002_py39.py!} +``` - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="10 15" +{!> ../../docs_src/request_files/tutorial002.py!} +``` - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +//// 接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。 -!!! note "技术细节" +/// note | 技术细节 - 也可以使用 `from starlette.responses import HTMLResponse`。 +也可以使用 `from starlette.responses import HTMLResponse`。 - `fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。 +`fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。 + +/// ### 带有额外元数据的多文件上传 和之前的方式一样, 您可以为 `File()` 设置额外参数, 即使是 `UploadFile`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="16" +{!> ../../docs_src/request_files/tutorial003_py39.py!} +``` - ```Python hl_lines="16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="18" +{!> ../../docs_src/request_files/tutorial003.py!} +``` - ```Python hl_lines="18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +//// ## 小结 diff --git a/docs/zh/docs/tutorial/request-forms-and-files.md b/docs/zh/docs/tutorial/request-forms-and-files.md index f58593669..bd87f5b68 100644 --- a/docs/zh/docs/tutorial/request-forms-and-files.md +++ b/docs/zh/docs/tutorial/request-forms-and-files.md @@ -2,16 +2,18 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。 -!!! info "说明" +/// info | 说明 - 接收上传文件或表单数据,要预先安装 `python-multipart`。 +接收上传文件或表单数据,要预先安装 `python-multipart`。 - 例如,`pip install python-multipart`。 +例如,`pip install python-multipart`。 + +/// ## 导入 `File` 与 `Form` ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## 定义 `File` 与 `Form` 参数 @@ -19,18 +21,20 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。 创建文件和表单参数的方式与 `Body` 和 `Query` 一样: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` 文件和表单字段作为表单数据上传与接收。 声明文件可以使用 `bytes` 或 `UploadFile` 。 -!!! warning "警告" +/// warning | 警告 + +可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。 - 可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。 +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/request-forms.md b/docs/zh/docs/tutorial/request-forms.md index e4fcd88ff..5938bb83d 100644 --- a/docs/zh/docs/tutorial/request-forms.md +++ b/docs/zh/docs/tutorial/request-forms.md @@ -2,18 +2,20 @@ 接收的不是 JSON,而是表单字段时,要使用 `Form`。 -!!! info "说明" +/// info | 说明 - 要使用表单,需预先安装 `python-multipart`。 +要使用表单,需预先安装 `python-multipart`。 - 例如,`pip install python-multipart`。 +例如,`pip install python-multipart`。 + +/// ## 导入 `Form` 从 `fastapi` 导入 `Form`: ```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` ## 定义 `Form` 参数 @@ -21,7 +23,7 @@ 创建表单(`Form`)参数的方式与 `Body` 和 `Query` 一样: ```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` 例如,OAuth2 规范的 "密码流" 模式规定要通过表单字段发送 `username` 和 `password`。 @@ -30,13 +32,17 @@ 使用 `Form` 可以声明与 `Body` (及 `Query`、`Path`、`Cookie`)相同的元数据和验证。 -!!! info "说明" +/// info | 说明 + +`Form` 是直接继承自 `Body` 的类。 + +/// - `Form` 是直接继承自 `Body` 的类。 +/// tip | 提示 -!!! tip "提示" +声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 - 声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 +/// ## 关于 "表单字段" @@ -44,19 +50,23 @@ **FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。 -!!! note "技术细节" +/// note | 技术细节 + +表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。 + +但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。 - 表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。 +编码和表单字段详见 MDN Web 文档的 POST小节。 - 但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。 +/// - 编码和表单字段详见 MDN Web 文档的 POST小节。 +/// warning | 警告 -!!! warning "警告" +可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。 - 可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。 +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md index 0f1b3b4b9..fd0facca8 100644 --- a/docs/zh/docs/tutorial/response-model.md +++ b/docs/zh/docs/tutorial/response-model.md @@ -8,26 +8,35 @@ * `@app.delete()` * 等等。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../docs_src/response_model/tutorial001_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +```Python hl_lines="17 22 24-27" +{!> ../../docs_src/response_model/tutorial001_py39.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="17 22 24-27" +{!> ../../docs_src/response_model/tutorial001.py!} +``` -!!! note - 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 +//// + +/// note + +注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 + +/// 它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。 @@ -42,21 +51,24 @@ FastAPI 将使用此 `response_model` 来: * 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。 -!!! note "技术细节" - 响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。 +/// note | 技术细节 + +响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。 + +/// ## 返回与输入相同的数据 现在我们声明一个 `UserIn` 模型,它将包含一个明文密码属性。 ```Python hl_lines="9 11" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` 我们正在使用此模型声明输入数据,并使用同一模型声明输出数据: ```Python hl_lines="17-18" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` 现在,每当浏览器使用一个密码创建用户时,API 都会在响应中返回相同的密码。 @@ -65,52 +77,67 @@ FastAPI 将使用此 `response_model` 来: 但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。 -!!! danger - 永远不要存储用户的明文密码,也不要在响应中发送密码。 +/// danger + +永远不要存储用户的明文密码,也不要在响应中发送密码。 + +/// ## 添加输出模型 相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="9 11 16" +{!> ../../docs_src/response_model/tutorial003_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="9 11 16" +{!> ../../docs_src/response_model/tutorial003.py!} +``` + +//// 这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="24" +{!> ../../docs_src/response_model/tutorial003_py310.py!} +``` + +//// - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="24" +{!> ../../docs_src/response_model/tutorial003.py!} +``` - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// ...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +```Python hl_lines="22" +{!> ../../docs_src/response_model/tutorial003_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="22" +{!> ../../docs_src/response_model/tutorial003.py!} +``` + +//// 因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。 @@ -129,7 +156,7 @@ FastAPI 将使用此 `response_model` 来: 你的响应模型可以具有默认值,例如: ```Python hl_lines="11 13-14" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` * `description: Union[str, None] = None` 具有默认值 `None`。 @@ -145,7 +172,7 @@ FastAPI 将使用此 `response_model` 来: 你可以设置*路径操作装饰器*的 `response_model_exclude_unset=True` 参数: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` 然后响应中将不会包含那些默认值,而是仅有实际设置的值。 @@ -159,16 +186,22 @@ FastAPI 将使用此 `response_model` 来: } ``` -!!! info - FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。 +/// info + +FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。 -!!! info - 你还可以使用: +/// - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +/// info - 参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。 +你还可以使用: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。 + +/// #### 默认值字段有实际值的数据 @@ -203,10 +236,13 @@ FastAPI 将使用此 `response_model` 来: 因此,它们将包含在 JSON 响应中。 -!!! tip - 请注意默认值可以是任何值,而不仅是`None`。 +/// tip + +请注意默认值可以是任何值,而不仅是`None`。 + +它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。 - 它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。 +/// ### `response_model_include` 和 `response_model_exclude` @@ -216,28 +252,34 @@ FastAPI 将使用此 `response_model` 来: 如果你只有一个 Pydantic 模型,并且想要从输出中移除一些数据,则可以使用这种快捷方法。 -!!! tip - 但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。 +/// tip - 这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。 +但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。 - 这也适用于作用类似的 `response_model_by_alias`。 +这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。 + +这也适用于作用类似的 `response_model_by_alias`。 + +/// ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial005.py!} +{!../../docs_src/response_model/tutorial005.py!} ``` -!!! tip - `{"name", "description"}` 语法创建一个具有这两个值的 `set`。 +/// tip + +`{"name", "description"}` 语法创建一个具有这两个值的 `set`。 + +等同于 `set(["name", "description"])`。 - 等同于 `set(["name", "description"])`。 +/// #### 使用 `list` 而不是 `set` 如果你忘记使用 `set` 而是使用 `list` 或 `tuple`,FastAPI 仍会将其转换为 `set` 并且正常工作: ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial006.py!} +{!../../docs_src/response_model/tutorial006.py!} ``` ## 总结 diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md index cc23231b4..1e5e7964f 100644 --- a/docs/zh/docs/tutorial/response-status-code.md +++ b/docs/zh/docs/tutorial/response-status-code.md @@ -9,18 +9,22 @@ * 等…… ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` -!!! note "笔记" +/// note | 笔记 - 注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。 +注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。 + +/// `status_code` 参数接收表示 HTTP 状态码的数字。 -!!! info "说明" +/// info | 说明 + +`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。 - `status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。 +/// 它可以: @@ -29,17 +33,21 @@ -!!! note "笔记" +/// note | 笔记 + +某些响应状态码表示响应没有响应体(参阅下一章)。 - 某些响应状态码表示响应没有响应体(参阅下一章)。 +FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 - FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 +/// ## 关于 HTTP 状态码 -!!! note "笔记" +/// note | 笔记 - 如果已经了解 HTTP 状态码,请跳到下一章。 +如果已经了解 HTTP 状态码,请跳到下一章。 + +/// 在 HTTP 协议中,发送 3 位数的数字状态码是响应的一部分。 @@ -58,16 +66,18 @@ * 对于来自客户端的一般错误,可以只使用 `400` * `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码 -!!! tip "提示" +/// tip | 提示 + +状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。 - 状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。 +/// ## 状态码名称快捷方式 再看下之前的例子: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` 表示**已创建**的状态码。 @@ -77,18 +87,20 @@ 可以使用 `fastapi.status` 中的快捷变量。 ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` 这只是一种快捷方式,具有相同的数字代码,但它可以使用编辑器的自动补全功能: -!!! note "技术细节" +/// note | 技术细节 + +也可以使用 `from starlette import status`。 - 也可以使用 `from starlette import status`。 +为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 - 为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 +/// ## 更改默认状态码 diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md index ae204dc61..b3883e4d3 100644 --- a/docs/zh/docs/tutorial/schema-extra-example.md +++ b/docs/zh/docs/tutorial/schema-extra-example.md @@ -10,17 +10,21 @@ 您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +```Python hl_lines="13-21" +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="15-23" +{!> ../../docs_src/schema_extra_example/tutorial001.py!} +``` + +//// 这些额外的信息将按原样添加到输出的JSON模式中。 @@ -28,20 +32,27 @@ 在 `Field`, `Path`, `Query`, `Body` 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 `example`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="2 8-11" +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} +``` + +//// - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="4 10-13" +{!> ../../docs_src/schema_extra_example/tutorial002.py!} +``` - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +//// -!!! warning - 请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。 +/// warning + +请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。 + +/// ## `Body` 额外参数 @@ -49,41 +60,57 @@ 比如,你可以将请求体的一个 `example` 传递给 `Body`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="22-27" +{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="22-27" +{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="23-28" +{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +尽可能选择使用 `Annotated` 的版本。 - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` +/// -=== "Python 3.8+" +```Python hl_lines="18-23" +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} +``` - ```Python hl_lines="23-28" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ non-Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python hl_lines="20-25" +{!> ../../docs_src/schema_extra_example/tutorial003.py!} +``` - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +//// ## 文档 UI 中的例子 diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md index f28cc24f8..561721f6e 100644 --- a/docs/zh/docs/tutorial/security/first-steps.md +++ b/docs/zh/docs/tutorial/security/first-steps.md @@ -20,36 +20,47 @@ 把下面的示例代码复制到 `main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` +```Python +{!> ../../docs_src/security/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/security/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated -=== "Python 3.8+" +/// tip - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 -=== "Python 3.8+ non-Annotated" +/// - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +```Python +{!> ../../docs_src/security/tutorial001.py!} +``` - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +//// ## 运行 -!!! info "说明" +/// info | 说明 + +先安装 `python-multipart`。 - 先安装 `python-multipart`。 +安装命令: `pip install python-multipart`。 - 安装命令: `pip install python-multipart`。 +这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。 - 这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。 +/// 用下面的命令运行该示例: @@ -71,19 +82,23 @@ $ uvicorn main:app --reload -!!! check "Authorize 按钮!" +/// check | Authorize 按钮! - 页面右上角出现了一个「**Authorize**」按钮。 +页面右上角出现了一个「**Authorize**」按钮。 - *路径操作*的右上角也出现了一个可以点击的小锁图标。 +*路径操作*的右上角也出现了一个可以点击的小锁图标。 + +/// 点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段: -!!! note "笔记" +/// note | 笔记 + +目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。 - 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。 +/// 虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。 @@ -125,39 +140,45 @@ OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户 本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。 -!!! info "说明" +/// info | 说明 - `Bearer` 令牌不是唯一的选择。 +`Bearer` 令牌不是唯一的选择。 - 但它是最适合这个用例的方案。 +但它是最适合这个用例的方案。 - 甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。 +甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。 - 本例中,**FastAPI** 还提供了构建工具。 +本例中,**FastAPI** 还提供了构建工具。 + +/// 创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。 ```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` -!!! tip "提示" +/// tip | 提示 + +在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。 - 在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。 +因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。 - 因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。 +使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。 - 使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。 +/// 该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。 接下来,学习如何创建实际的路径操作。 -!!! info "说明" +/// info | 说明 - 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。 +严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。 - 这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。 +这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。 + +/// `oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。 @@ -174,18 +195,20 @@ oauth2_scheme(some, parameters) 接下来,使用 `Depends` 把 `oauth2_scheme` 传入依赖项。 ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` 该依赖项使用字符串(`str`)接收*路径操作函数*的参数 `token` 。 **FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。 -!!! info "技术细节" +/// info | 技术细节 + +**FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。 - **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。 +所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。 - 所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。 +/// ## 实现的操作 diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md index 1f17f5bd9..e0f763b30 100644 --- a/docs/zh/docs/tutorial/security/get-current-user.md +++ b/docs/zh/docs/tutorial/security/get-current-user.md @@ -3,7 +3,7 @@ 上一章中,(基于依赖注入系统的)安全系统向*路径操作函数*传递了 `str` 类型的 `token`: ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` 但这并不实用。 @@ -18,7 +18,7 @@ 与使用 Pydantic 声明请求体相同,并且可在任何位置使用: ```Python hl_lines="5 12-16" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## 创建 `get_current_user` 依赖项 @@ -32,7 +32,7 @@ 与之前直接在路径操作中的做法相同,新的 `get_current_user` 依赖项从子依赖项 `oauth2_scheme` 中接收 `str` 类型的 `token`: ```Python hl_lines="25" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## 获取用户 @@ -40,7 +40,7 @@ `get_current_user` 使用创建的(伪)工具函数,该函数接收 `str` 类型的令牌,并返回 Pydantic 的 `User` 模型: ```Python hl_lines="19-22 26-27" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## 注入当前用户 @@ -48,25 +48,28 @@ 在*路径操作* 的 `Depends` 中使用 `get_current_user`: ```Python hl_lines="31" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` 注意,此处把 `current_user` 的类型声明为 Pydantic 的 `User` 模型。 这有助于在函数内部使用代码补全和类型检查。 -!!! tip "提示" +/// tip | 提示 - 还记得请求体也是使用 Pydantic 模型声明的吧。 +还记得请求体也是使用 Pydantic 模型声明的吧。 - 放心,因为使用了 `Depends`,**FastAPI** 不会搞混。 +放心,因为使用了 `Depends`,**FastAPI** 不会搞混。 -!!! check "检查" +/// - 依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。 +/// check | 检查 - 而不是局限于只能有一个返回该类型数据的依赖项。 +依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。 +而不是局限于只能有一个返回该类型数据的依赖项。 + +/// ## 其它模型 @@ -102,7 +105,7 @@ 所有*路径操作*只需 3 行代码就可以了: ```Python hl_lines="30-32" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## 小结 diff --git a/docs/zh/docs/tutorial/security/index.md b/docs/zh/docs/tutorial/security/index.md index 0595f5f63..e888a4fe9 100644 --- a/docs/zh/docs/tutorial/security/index.md +++ b/docs/zh/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth2是一个规范,它定义了几种处理身份认证和授权的方法 OAuth2 没有指定如何加密通信,它期望你为应用程序使用 HTTPS 进行通信。 -!!! tip - 在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。 +/// tip +在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。 + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI 定义了以下安全方案: * 此自动发现机制是 OpenID Connect 规范中定义的内容。 -!!! tip - 集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。 +/// tip + +集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。 + +最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。 - 最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。 +/// ## **FastAPI** 实用工具 diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 33a4d7fc7..4bb6e6318 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -26,29 +26,27 @@ JWT 字符串没有加密,任何人都能用它恢复原始信息。 如需深入了解 JWT 令牌,了解它的工作方式,请参阅 https://jwt.io。 -## 安装 `python-jose` +## 安装 `PyJWT` -安装 `python-jose`,在 Python 中生成和校验 JWT 令牌: +安装 `PyJWT`,在 Python 中生成和校验 JWT 令牌:
```console -$ pip install python-jose[cryptography] +$ pip install pyjwt ---> 100% ```
-Python-jose 需要安装配套的加密后端。 +/// info | 说明 -本教程推荐的后端是:pyca/cryptography。 +如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。 -!!! tip "提示" +您可以在 PyJWT Installation docs 获得更多信息。 - 本教程以前使用 PyJWT。 - - 但后来换成了 Python-jose,因为 Python-jose 支持 PyJWT 的所有功能,还支持与其它工具集成时可能会用到的一些其它功能。 +/// ## 密码哈希 @@ -62,7 +60,7 @@ $ pip install python-jose[cryptography] 原因很简单,假如数据库被盗,窃贼无法获取用户的明文密码,得到的只是哈希值。 -这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大)。 +这样一来,窃贼就无法在其它应用中使用窃取的密码(要知道,很多用户在所有系统中都使用相同的密码,风险超大)。 ## 安装 `passlib` @@ -84,13 +82,15 @@ $ pip install passlib[bcrypt] -!!! tip "提示" +/// tip | 提示 + +`passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。 - `passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。 +例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。 - 例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。 +并且,用户可以同时从 Django 应用或 FastAPI 应用登录。 - 并且,用户可以同时从 Django 应用或 FastAPI 应用登录。 +/// ## 密码哈希与校验 @@ -98,13 +98,15 @@ $ pip install passlib[bcrypt] 创建用于密码哈希和身份校验的 PassLib **上下文**。 -!!! tip "提示" +/// tip | 提示 + +PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。 - PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。 +例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。 - 例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。 +同时,这些功能都是兼容的。 - 同时,这些功能都是兼容的。 +/// 接下来,创建三个工具函数,其中一个函数用于哈希用户的密码。 @@ -112,13 +114,63 @@ $ pip install passlib[bcrypt] 第三个函数用于身份验证,并返回用户。 +//// tab | Python 3.10+ + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 50 57-58 61-62 71-77" +{!> ../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + ```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` -!!! note "笔记" +//// + +//// tab | Python 3.8+ non-Annotated - 查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。 +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="8 49 56-57 60-61 70-76" +{!> ../../docs_src/security/tutorial004.py!} +``` + +//// + +/// note | 笔记 + +查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。 + +/// ## 处理 JWT 令牌 @@ -149,7 +201,7 @@ $ openssl rand -hex 32 创建生成新的访问令牌的工具函数。 ```Python hl_lines="6 12-14 28-30 78-86" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` ## 更新依赖项 @@ -160,20 +212,116 @@ $ openssl rand -hex 32 如果令牌无效,则直接返回 HTTP 错误。 -```Python hl_lines="89-106" -{!../../../docs_src/security/tutorial004.py!} +//// tab | Python 3.10+ + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 7 14-16 30-32 80-88" +{!> ../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="3 6 12-14 28-30 78-86" +{!> ../../docs_src/security/tutorial004_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="4 7 13-15 29-31 79-87" +{!> ../../docs_src/security/tutorial004.py!} ``` +//// + ## 更新 `/token` *路径操作* 用令牌过期时间创建 `timedelta` 对象。 创建并返回真正的 JWT 访问令牌。 +//// tab | Python 3.10+ + +```Python hl_lines="118-133" +{!> ../../docs_src/security/tutorial004_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="118-133" +{!> ../../docs_src/security/tutorial004_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="119-134" +{!> ../../docs_src/security/tutorial004_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + ```Python hl_lines="115-130" -{!../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip + +Prefer to use the `Annotated` version if possible. + +/// + +```Python hl_lines="116-131" +{!> ../../docs_src/security/tutorial004.py!} +``` + +//// + ### JWT `sub` 的技术细节 JWT 规范还包括 `sub` 键,值是令牌的主题。 @@ -210,9 +358,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。 用户名: `johndoe` 密码: `secret` -!!! check "检查" +/// check | 检查 - 注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。 +注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。 + +/// @@ -233,9 +383,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。 -!!! note "笔记" +/// note | 笔记 + +注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。 - 注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。 +/// ## `scopes` 高级用法 @@ -261,7 +413,7 @@ OAuth2 支持**`scopes`**(作用域)。 开发者可以灵活选择最适合项目的安全机制。 -还可以直接使用 `passlib` 和 `python-jose` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。 +还可以直接使用 `passlib` 和 `PyJWT` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。 而且,**FastAPI** 还提供了一些工具,在不影响灵活、稳定和安全的前提下,尽可能地简化安全机制。 diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md index c7f46177f..8ce9263db 100644 --- a/docs/zh/docs/tutorial/security/simple-oauth2.md +++ b/docs/zh/docs/tutorial/security/simple-oauth2.md @@ -32,15 +32,17 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 * 脸书和 Instagram 使用 `instagram_basic` * 谷歌使用 `https://www.googleapis.com/auth/drive` -!!! info "说明" +/// info | 说明 - OAuth2 中,**作用域**只是声明指定权限的字符串。 +OAuth2 中,**作用域**只是声明指定权限的字符串。 - 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 +是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 - 这些细节只是特定的实现方式。 +这些细节只是特定的实现方式。 - 对 OAuth2 来说,都只是字符串而已。 +对 OAuth2 来说,都只是字符串而已。 + +/// ## 获取 `username` 和 `password` 的代码 @@ -51,7 +53,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 首先,导入 `OAuth2PasswordRequestForm`,然后,在 `/token` *路径操作* 中,用 `Depends` 把该类作为依赖项。 ```Python hl_lines="4 76" -{!../../../docs_src/security/tutorial003.py!} +{!../../docs_src/security/tutorial003.py!} ``` `OAuth2PasswordRequestForm` 是用以下几项内容声明表单请求体的类依赖项: @@ -61,32 +63,38 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 * 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串 * 可选的 `grant_type` -!!! tip "提示" +/// tip | 提示 + +实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 - 实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 +如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。 - 如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。 +/// * 可选的 `client_id`(本例未使用) * 可选的 `client_secret`(本例未使用) -!!! info "说明" +/// info | 说明 - `OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 +`OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 - **FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。 +**FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。 - 但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。 +但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。 - 但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。 +但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。 + +/// ### 使用表单数据 -!!! tip "提示" +/// tip | 提示 + +`OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 - `OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 +本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。 - 本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。 +/// 现在,即可使用表单字段 `username`,从(伪)数据库中获取用户数据。 @@ -95,7 +103,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 本例使用 `HTTPException` 异常显示此错误: ```Python hl_lines="3 77-79" -{!../../../docs_src/security/tutorial003.py!} +{!../../docs_src/security/tutorial003.py!} ``` ### 校验密码 @@ -123,7 +131,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大。 ```Python hl_lines="80-83" -{!../../../docs_src/security/tutorial003.py!} +{!../../docs_src/security/tutorial003.py!} ``` #### 关于 `**user_dict` @@ -142,9 +150,11 @@ UserInDB( ) ``` -!!! info "说明" +/// info | 说明 - `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#about-user_indict){.internal-link target=_blank}。 +`user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。 + +/// ## 返回 Token @@ -156,25 +166,29 @@ UserInDB( 本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。 -!!! tip "提示" +/// tip | 提示 + +下一章介绍使用哈希密码和 JWT Token 的真正安全机制。 - 下一章介绍使用哈希密码和 JWT Token 的真正安全机制。 +但现在,仅关注所需的特定细节。 - 但现在,仅关注所需的特定细节。 +/// ```Python hl_lines="85" -{!../../../docs_src/security/tutorial003.py!} +{!../../docs_src/security/tutorial003.py!} ``` -!!! tip "提示" +/// tip | 提示 - 按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 +按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 - 这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。 +这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。 - 这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。 +这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。 - **FastAPI** 则负责处理其它的工作。 +**FastAPI** 则负责处理其它的工作。 + +/// ## 更新依赖项 @@ -189,24 +203,26 @@ UserInDB( 因此,在端点中,只有当用户存在、通过身份验证、且状态为激活时,才能获得该用户: ```Python hl_lines="58-67 69-72 90" -{!../../../docs_src/security/tutorial003.py!} +{!../../docs_src/security/tutorial003.py!} ``` -!!! info "说明" +/// info | 说明 + +此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 - 此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 +任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。 - 任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。 +本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。 - 本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。 +实际上,忽略这个附加响应头,也不会有什么问题。 - 实际上,忽略这个附加响应头,也不会有什么问题。 +之所以在此提供这个附加响应头,是为了符合规范的要求。 - 之所以在此提供这个附加响应头,是为了符合规范的要求。 +说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。 - 说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。 +这就是遵循标准的好处…… - 这就是遵循标准的好处…… +/// ## 实际效果 diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index be0c76593..06b373e6d 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -1,12 +1,22 @@ # SQL (关系型) 数据库 +/// info + +这些文档即将被更新。🎉 + +当前版本假设Pydantic v1和SQLAlchemy版本小于2。 + +新的文档将包括Pydantic v2以及 SQLModel(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。 + +/// + **FastAPI**不需要你使用SQL(关系型)数据库。 但是您可以使用任何您想要的关系型数据库。 在这里,让我们看一个使用着[SQLAlchemy](https://www.sqlalchemy.org/)的示例。 -您可以很容易地将SQLAlchemy支持任何数据库,像: +您可以很容易地将其调整为任何SQLAlchemy支持的数据库,如: * PostgreSQL * MySQL @@ -18,11 +28,17 @@ 稍后,对于您的产品级别的应用程序,您可能会要使用像**PostgreSQL**这样的数据库服务器。 -!!! tip - 这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql +/// tip + +这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql + +/// -!!! note - 请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。 +/// note + +请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。 + +/// ## ORMs(对象关系映射) @@ -56,8 +72,11 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间 以类似的方式,您也可以使用任何其他 ORM。 -!!! tip - 在文档中也有一篇使用 Peewee 的等效的文章。 +/// tip + +在文档中也有一篇使用 Peewee 的等效的文章。 + +/// ## 文件结构 @@ -74,13 +93,13 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间 └── schemas.py ``` -该文件`__init__.py`只是一个空文件,但它告诉 Python 其中`sql_app`的所有模块(Python 文件)都是一个包。 +该文件`__init__.py`只是一个空文件,但它告诉 Python `sql_app` 是一个包。 现在让我们看看每个文件/模块的作用。 ## 安装 SQLAlchemy -先下载`SQLAlchemy`所需要的依赖: +首先你需要安装`SQLAlchemy`:
@@ -99,13 +118,13 @@ $ pip install sqlalchemy ### 导入 SQLAlchemy 部件 ```Python hl_lines="1-3" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### 为 SQLAlchemy 定义数据库 URL地址 ```Python hl_lines="5-6" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` 在这个例子中,我们正在“连接”到一个 SQLite 数据库(用 SQLite 数据库打开一个文件)。 @@ -122,9 +141,11 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" ...并根据您的数据库数据和相关凭据(也适用于 MySQL、MariaDB 或任何其他)对其进行调整。 -!!! tip +/// tip + +如果您想使用不同的数据库,这是就是您必须修改的地方。 - 如果您想使用不同的数据库,这是就是您必须修改的地方。 +/// ### 创建 SQLAlchemy 引擎 @@ -133,7 +154,7 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" 我们稍后会将这个`engine`在其他地方使用。 ```Python hl_lines="8-10" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` #### 注意 @@ -146,40 +167,42 @@ connect_args={"check_same_thread": False} ...仅用于`SQLite`,在其他数据库不需要它。 -!!! info "技术细节" +/// info | 技术细节 + +默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。 - 默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。 +这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 - 这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 +但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 - 但是在 FastAPI 中,普遍使用def函数,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 +此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 - 此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 +/// ### 创建一个`SessionLocal`类 -每个实例`SessionLocal`都会是一个数据库会话。当然该类本身还不是数据库会话。 +每个`SessionLocal`类的实例都会是一个数据库会话。当然该类本身还不是数据库会话。 但是一旦我们创建了一个`SessionLocal`类的实例,这个实例将是实际的数据库会话。 -我们命名它是`SessionLocal`为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。 +我们将它命名为`SessionLocal`是为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。 稍后我们将使用`Session`(从 SQLAlchemy 导入的那个)。 要创建`SessionLocal`类,请使用函数`sessionmaker`: ```Python hl_lines="11" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### 创建一个`Base`类 现在我们将使用`declarative_base()`返回一个类。 -稍后我们将用这个类继承,来创建每个数据库模型或类(ORM 模型): +稍后我们将继承这个类,来创建每个数据库模型或类(ORM 模型): ```Python hl_lines="13" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ## 创建数据库模型 @@ -190,10 +213,13 @@ connect_args={"check_same_thread": False} 我们将使用我们之前创建的`Base`类来创建 SQLAlchemy 模型。 -!!! tip - SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。 +/// tip - 而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。 +SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。 + +而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。 + +/// 从`database`(来自上面的`database.py`文件)导入`Base`。 @@ -202,14 +228,14 @@ connect_args={"check_same_thread": False} 这些类就是 SQLAlchemy 模型。 ```Python hl_lines="4 7-8 18-19" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` 这个`__tablename__`属性是用来告诉 SQLAlchemy 要在数据库中为每个模型使用的数据库表的名称。 ### 创建模型属性/列 -现在创建所有模型(类)属性。 +现在创建所有模型(类)的属性。 这些属性中的每一个都代表其相应数据库表中的一列。 @@ -218,7 +244,7 @@ connect_args={"check_same_thread": False} 我们传递一个 SQLAlchemy “类型”,如`Integer`、`String`和`Boolean`,它定义了数据库中的类型,作为参数。 ```Python hl_lines="1 10-13 21-24" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` ### 创建关系 @@ -230,7 +256,7 @@ connect_args={"check_same_thread": False} 这将或多或少会成为一种“神奇”属性,其中表示该表与其他相关的表中的值。 ```Python hl_lines="2 15 26" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` 当访问 user 中的属性`items`时,如 中`my_user.items`,它将有一个`Item`SQLAlchemy 模型列表(来自`items`表),这些模型具有指向`users`表中此记录的外键。 @@ -243,40 +269,49 @@ connect_args={"check_same_thread": False} 现在让我们查看一下文件`sql_app/schemas.py`。 -!!! tip - 为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。 +/// tip + +为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。 + +这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。 - 这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。 +因此,这将帮助我们在使用两者时避免混淆。 - 因此,这将帮助我们在使用两者时避免混淆。 +/// ### 创建初始 Pydantic*模型*/模式 -创建一个`ItemBase`和`UserBase`Pydantic*模型*(或者我们说“schema”)以及在创建或读取数据时具有共同的属性。 +创建一个`ItemBase`和`UserBase`Pydantic*模型*(或者我们说“schema”),他们拥有创建或读取数据时具有的共同属性。 -`ItemCreate`为 创建一个`UserCreate`继承自它们的所有属性(因此它们将具有相同的属性),以及创建所需的任何其他数据(属性)。 +然后创建一个继承自他们的`ItemCreate`和`UserCreate`,并添加创建时所需的其他数据(或属性)。 因此在创建时也应当有一个`password`属性。 -但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如用户请求时不应该从 API 返回响应中包含它。 +但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如通过API读取一个用户数据时,它不应当包含在内。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1 4-6 9-10 21-22 25-26" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +```Python hl_lines="1 4-6 9-10 21-22 25-26" +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="3 6-8 11-12 23-24 27-28" +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// #### SQLAlchemy 风格和 Pydantic 风格 @@ -304,26 +339,35 @@ name: str 不仅是这些项目的 ID,还有我们在 Pydantic*模型*中定义的用于读取项目的所有数据:`Item`. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13-15 29-32" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +```Python hl_lines="13-15 29-32" +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` -=== "Python 3.9+" +//// - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python hl_lines="15-17 31-34" +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// -!!! tip - 请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。 +//// tab | Python 3.8+ + +```Python hl_lines="15-17 31-34" +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// + +/// tip + +请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。 + +/// ### 使用 Pydantic 的`orm_mode` @@ -333,32 +377,41 @@ name: str 在`Config`类中,设置属性`orm_mode = True`。 -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="13 17-18 29 34-35" +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python hl_lines="13 17-18 29 34-35" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="15 19-20 31 36-37" +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="15 19-20 31 36-37" +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} +``` - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +//// -=== "Python 3.8+" +/// tip - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +请注意,它使用`=`分配一个值,例如: -!!! tip - 请注意,它使用`=`分配一个值,例如: +`orm_mode = True` - `orm_mode = True` +它不使用之前的`:`来类型声明。 - 它不使用之前的`:`来类型声明。 +这是设置配置值,而不是声明类型。 - 这是设置配置值,而不是声明类型。 +/// Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`dict`,而是一个 ORM 模型(或任何其他具有属性的任意对象)。 @@ -368,7 +421,7 @@ Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`di id = data["id"] ``` -尝试从属性中获取它,如: +它还会尝试从属性中获取它,如: ```Python id = data.id @@ -404,7 +457,7 @@ current_user.items 在这个文件中,我们将编写可重用的函数用来与数据库中的数据进行交互。 -**CRUD**分别为:**增加**、**查询**、**更改**和**删除**,即增删改查。 +**CRUD**分别为:增加(**C**reate)、查询(**R**ead)、更改(**U**pdate)、删除(**D**elete),即增删改查。 ...虽然在这个例子中我们只是新增和查询。 @@ -414,62 +467,74 @@ current_user.items 导入之前的`models`(SQLAlchemy 模型)和`schemas`(Pydantic*模型*/模式)。 -创建一些实用函数来完成: +创建一些工具函数来完成: * 通过 ID 和电子邮件查询单个用户。 * 查询多个用户。 * 查询多个项目。 ```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - 通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。 +/// tip + +通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。 + +/// ### 创建数据 -现在创建实用程序函数来创建数据。 +现在创建工具函数来创建数据。 它的步骤是: * 使用您的数据创建一个 SQLAlchemy 模型*实例。* -* 使用`add`来将该实例对象添加到您的数据库。 -* 使用`commit`来对数据库的事务提交(以便保存它们)。 -* 使用`refresh`来刷新您的数据库实例(以便它包含来自数据库的任何新数据,例如生成的 ID)。 +* 使用`add`来将该实例对象添加到数据库会话。 +* 使用`commit`来将更改提交到数据库(以便保存它们)。 +* 使用`refresh`来刷新您的实例对象(以便它包含来自数据库的任何新数据,例如生成的 ID)。 ```Python hl_lines="18-24 31-36" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` -!!! tip - SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。 +/// tip + +SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。 + +但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。 + +然后将hashed_password参数与要保存的值一起传递。 + +/// - 但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。 +/// warning - 然后将hashed_password参数与要保存的值一起传递。 +此示例不安全,密码未经过哈希处理。 -!!! warning - 此示例不安全,密码未经过哈希处理。 +在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。 - 在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。 +有关更多详细信息,请返回教程中的安全部分。 - 有关更多详细信息,请返回教程中的安全部分。 +在这里,我们只关注数据库的工具和机制。 - 在这里,我们只关注数据库的工具和机制。 +/// -!!! tip - 这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据: +/// tip - `item.dict()` +这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据: - 然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`: +`item.dict()` - `Item(**item.dict())` +然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`: - 然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`: +`Item(**item.dict())` - `Item(**item.dict(), owner_id=user_id)` +然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`: + +`Item(**item.dict(), owner_id=user_id)` + +/// ## 主**FastAPI**应用程序 @@ -479,17 +544,21 @@ current_user.items 以非常简单的方式创建数据库表: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python hl_lines="7" +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// - ```Python hl_lines="7" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python hl_lines="9" +{!> ../../docs_src/sql_databases/sql_app/main.py!} +``` - ```Python hl_lines="9" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// #### Alembic 注意 @@ -499,77 +568,95 @@ current_user.items “迁移”是每当您更改 SQLAlchemy 模型的结构、添加新属性等以在数据库中复制这些更改、添加新列、新表等时所需的一组步骤。 -您可以在[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/)。 +您可以在[Full Stack FastAPI Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-template/tree/master/backend/app/alembic)。 ### 创建依赖项 现在使用我们在`sql_app/database.py`文件中创建的`SessionLocal`来创建依赖项。 -我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在所有请求中使用相同的会话,然后在请求完成后关闭它。 +我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在整个请求中使用相同的会话,然后在请求完成后关闭它。 然后将为下一个请求创建一个新会话。 -为此,我们将创建一个新的依赖项`yield`,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。 +为此,我们将创建一个包含`yield`的依赖项,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。 我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。 -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="13-18" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="13-18" +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="15-20" +{!> ../../docs_src/sql_databases/sql_app/main.py!} +``` - ```Python hl_lines="15-20" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// -!!! info - 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 +/// info - 然后我们在finally块中关闭它。 +我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 - 通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。 +然后我们在finally块中关闭它。 - 但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception) +通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。 + +但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception) + +/// *然后,当在路径操作函数*中使用依赖项时,我们使用`Session`,直接从 SQLAlchemy 导入的类型声明它。 *这将为我们在路径操作函数*中提供更好的编辑器支持,因为编辑器将知道`db`参数的类型`Session`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="22 30 36 45 51" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="22 30 36 45 51" +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="24 32 38 47 53" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | Python 3.8+ -!!! info "技术细节" - 参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。 +```Python hl_lines="24 32 38 47 53" +{!> ../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// + +/// info | 技术细节 - 但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。 +参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。 + +但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。 + +/// ### 创建您的**FastAPI** *路径操作* 现在,到了最后,编写标准的**FastAPI** *路径操作*代码。 -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +```Python hl_lines="21-26 29-32 35-40 43-47 50-53" +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +//// tab | Python 3.8+ + +```Python hl_lines="23-28 31-34 37-42 45-49 52-55" +{!> ../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// 我们在依赖项中的每个请求之前利用`yield`创建数据库会话,然后关闭它。 @@ -577,15 +664,21 @@ current_user.items 这样,我们就可以直接从*路径操作函数*内部调用`crud.get_user`并使用该会话,来进行对数据库操作。 -!!! tip - 请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。 +/// tip + +请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。 + +但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。 + +/// - 但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。 +/// tip -!!! tip - 另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`. +另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`. - 但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。 +但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。 + +/// ### 关于 `def` 对比 `async def` @@ -614,11 +707,17 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ... ``` -!!! info - 如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/) +/// info + +如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/) + +/// -!!! note "Very Technical Details" - 如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。 +/// note | Very Technical Details + +如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。 + +/// ## 迁移 @@ -641,62 +740,74 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/database.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` * `sql_app/models.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` * `sql_app/schemas.py`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +//// -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +```Python +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} +``` -=== "Python 3.8+" +//// - ```Python - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} +``` + +//// * `sql_app/crud.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` * `sql_app/main.py`: -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +```Python +{!> ../../docs_src/sql_databases/sql_app/main.py!} +``` + +//// ## 执行项目 您可以复制这些代码并按原样使用它。 -!!! info +/// info + +事实上,这里的代码只是大多数测试代码的一部分。 - 事实上,这里的代码只是大多数测试代码的一部分。 +/// 你可以用 Uvicorn 运行它: @@ -729,38 +840,45 @@ $ uvicorn sql_app.main:app --reload ## 中间件替代数据库会话 -如果你不能使用依赖项`yield`——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以在类似的“中间件”中设置会话方法。 +如果你不能使用带有`yield`的依赖项——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以使用类似的方法在“中间件”中设置会话。 -“中间件”基本功能是一个为每个请求执行的函数在请求之前进行执行相应的代码,以及在请求执行之后执行相应的代码。 +“中间件”基本上是一个对每个请求都执行的函数,其中一些代码在端点函数之前执行,另一些代码在端点函数之后执行。 ### 创建中间件 -我们将添加中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 +我们要添加的中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 + +//// tab | Python 3.9+ + +```Python hl_lines="12-20" +{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.8+ - ```Python hl_lines="12-20" - {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} - ``` +```Python hl_lines="14-22" +{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} +``` + +//// -=== "Python 3.8+" +/// info - ```Python hl_lines="14-22" - {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} - ``` +我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 -!!! info - 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 +然后我们在finally块中关闭它。 - 然后我们在finally块中关闭它。 +通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。 - 通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。 +/// ### 关于`request.state` `request.state`是每个`Request`对象的属性。它用于存储附加到请求本身的任意对象,例如本例中的数据库会话。您可以在[Starlette 的关于`Request`state](https://www.starlette.io/requests/#other-state)的文档中了解更多信息。 -对于这种情况下,它帮助我们确保在所有请求中使用单个数据库会话,然后关闭(在中间件中)。 +对于这种情况下,它帮助我们确保在整个请求中使用单个数据库会话,然后关闭(在中间件中)。 ### 使用`yield`依赖项与使用中间件的区别 @@ -775,10 +893,16 @@ $ uvicorn sql_app.main:app --reload * 将为每个请求创建一个连接。 * 即使处理该请求的*路径操作*不需要数据库。 -!!! tip - `tyield`当依赖项 足以满足用例时,使用`tyield`依赖项方法会更好。 +/// tip + +最好使用带有yield的依赖项,如果这足够满足用例需求 + +/// + +/// info + +带有`yield`的依赖项是最近刚加入**FastAPI**中的。 -!!! info - `yield`的依赖项是最近刚加入**FastAPI**中的。 +所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 - 所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 +/// diff --git a/docs/zh/docs/tutorial/static-files.md b/docs/zh/docs/tutorial/static-files.md index e7c5c3f0a..7580f731b 100644 --- a/docs/zh/docs/tutorial/static-files.md +++ b/docs/zh/docs/tutorial/static-files.md @@ -8,13 +8,16 @@ * "挂载"(Mount) 一个 `StaticFiles()` 实例到一个指定路径。 ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` -!!! note "技术细节" - 你也可以用 `from starlette.staticfiles import StaticFiles`。 +/// note | 技术细节 - **FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。 +你也可以用 `from starlette.staticfiles import StaticFiles`。 + +**FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。 + +/// ### 什么是"挂载"(Mounting) diff --git a/docs/zh/docs/tutorial/testing.md b/docs/zh/docs/tutorial/testing.md index 77fff7596..bb3ef8a6a 100644 --- a/docs/zh/docs/tutorial/testing.md +++ b/docs/zh/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## 使用 `TestClient` -!!! 信息 - 要使用 `TestClient`,先要安装 `httpx`. +/// info | 信息 - 例:`pip install httpx`. +要使用 `TestClient`,先要安装 `httpx`. + +例:`pip install httpx`. + +/// 导入 `TestClient`. @@ -24,23 +27,32 @@ 为你需要检查的地方用标准的Python表达式写个简单的 `assert` 语句(重申,标准的`pytest`)。 ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` -!!! 提示 - 注意测试函数是普通的 `def`,不是 `async def`。 +/// tip | 提示 + +注意测试函数是普通的 `def`,不是 `async def`。 + +还有client的调用也是普通的调用,不是用 `await`。 + +这让你可以直接使用 `pytest` 而不会遇到麻烦。 + +/// + +/// note | 技术细节 + +你也可以用 `from starlette.testclient import TestClient`。 - 还有client的调用也是普通的调用,不是用 `await`。 +**FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。 - 这让你可以直接使用 `pytest` 而不会遇到麻烦。 +/// -!!! note "技术细节" - 你也可以用 `from starlette.testclient import TestClient`。 +/// tip | 提示 - **FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。 +除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。 -!!! 提示 - 除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。 +/// ## 分离测试 @@ -50,7 +62,7 @@ ### **FastAPI** app 文件 -假设你有一个像 [更大的应用](./bigger-applications.md){.internal-link target=_blank} 中所描述的文件结构: +假设你有一个像 [更大的应用](bigger-applications.md){.internal-link target=_blank} 中所描述的文件结构: ``` . @@ -63,7 +75,7 @@ ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### 测试文件 @@ -81,7 +93,7 @@ 因为这文件在同一个包中,所以你可以通过相对导入从 `main` 模块(`main.py`)导入`app`对象: ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ...然后测试代码和之前一样的。 @@ -110,48 +122,64 @@ 所有*路径操作* 都需要一个`X-Token` 头。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` - !!! tip - Prefer to use the `Annotated` version if possible. +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// tab | Python 3.10+ non-Annotated -=== "Python 3.8+ non-Annotated" +/// tip | 提示 - !!! tip - Prefer to use the `Annotated` version if possible. +Prefer to use the `Annotated` version if possible. - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 提示 + +Prefer to use the `Annotated` version if possible. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// ### 扩展后的测试文件 然后您可以使用扩展后的测试更新`test_main.py`: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` 每当你需要客户端在请求中传递信息,但你不知道如何传递时,你可以通过搜索(谷歌)如何用 `httpx`做,或者是用 `requests` 做,毕竟HTTPX的设计是基于Requests的设计的。 @@ -168,10 +196,13 @@ 关于如何传数据给后端的更多信息 (使用`httpx` 或 `TestClient`),请查阅 HTTPX 文档. -!!! 信息 - 注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。 +/// info | 信息 + +注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。 + +如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。 - 如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。 +/// ## 运行起来 diff --git a/docs/zh/docs/virtual-environments.md b/docs/zh/docs/virtual-environments.md new file mode 100644 index 000000000..9b3c0340a --- /dev/null +++ b/docs/zh/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# 虚拟环境 + +当你在 Python 工程中工作时,你可能会有必要用到一个**虚拟环境**(或类似的机制)来隔离你为每个工程安装的包。 + +/// info + +如果你已经了解虚拟环境,知道如何创建和使用它们,你可以考虑跳过这一部分。🤓 + +/// + +/// tip + +**虚拟环境**和**环境变量**是不同的。 + +**环境变量**是系统中的一个变量,可以被程序使用。 + +**虚拟环境**是一个包含一些文件的目录。 + +/// + +/// info + +这个页面将教你如何使用**虚拟环境**以及了解它们的工作原理。 + +如果你计划使用一个**可以为你管理一切的工具**(包括安装 Python),试试 uv。 + +/// + +## 创建一个工程 + +首先,为你的工程创建一个目录。 + +我 (指原作者 —— 译者注) 通常会在我的主目录下创建一个名为 `code` 的目录。 + +在这个目录下,我再为每个工程创建一个目录。 + +
+ +```console +// 进入主目录 +$ cd +// 创建一个用于存放所有代码工程的目录 +$ mkdir code +// 进入 code 目录 +$ cd code +// 创建一个用于存放这个工程的目录 +$ mkdir awesome-project +// 进入这个工程的目录 +$ cd awesome-project +``` + +
+ +## 创建一个虚拟环境 + +在开始一个 Python 工程的**第一时间**,**在你的工程内部**创建一个虚拟环境。 + +/// tip + +你只需要 **在每个工程中操作一次**,而不是每次工作时都操作。 + +/// + +//// tab | `venv` + +你可以使用 Python 自带的 `venv` 模块来创建一个虚拟环境。 + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | 上述命令的含义 + +* `python`: 使用名为 `python` 的程序 +* `-m`: 以脚本的方式调用一个模块,我们将告诉它接下来使用哪个模块 +* `venv`: 使用名为 `venv` 的模块,这个模块通常随 Python 一起安装 +* `.venv`: 在新目录 `.venv` 中创建虚拟环境 + +/// + +//// + +//// tab | `uv` + +如果你安装了 `uv`,你也可以使用它来创建一个虚拟环境。 + +
+ +```console +$ uv venv +``` + +
+ +/// tip + +默认情况下,`uv` 会在一个名为 `.venv` 的目录中创建一个虚拟环境。 + +但你可以通过传递一个额外的参数来自定义它,指定目录的名称。 + +/// + +//// + +这个命令会在一个名为 `.venv` 的目录中创建一个新的虚拟环境。 + +/// details | `.venv`,或是其他名称 + +你可以在不同的目录下创建虚拟环境,但通常我们会把它命名为 `.venv`。 + +/// + +## 激活虚拟环境 + +激活新的虚拟环境来确保你运行的任何 Python 命令或安装的包都能使用到它。 + +/// tip + +**每次**开始一个 **新的终端会话** 来工作在这个工程时,你都需要执行这个操作。 + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +或者,如果你在 Windows 上使用 Bash(例如 Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip + +每次你在这个环境中安装一个 **新的包** 时,都需要 **重新激活** 这个环境。 + +这么做确保了当你使用一个由这个包安装的 **终端(CLI)程序** 时,你使用的是你的虚拟环境中的程序,而不是全局安装、可能版本不同的程序。 + +/// + +## 检查虚拟环境是否激活 + +检查虚拟环境是否激活 (前面的命令是否生效)。 + +/// tip + +这是 **可选的**,但这是一个很好的方法,可以 **检查** 一切是否按预期工作,以及你是否使用了你打算使用的虚拟环境。 + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +如果它显示了在你工程 (在这个例子中是 `awesome-project`) 的 `.venv/bin/python` 中的 `python` 二进制文件,那么它就生效了。🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +如果它显示了在你工程 (在这个例子中是 `awesome-project`) 的 `.venv\Scripts\python` 中的 `python` 二进制文件,那么它就生效了。🎉 + +//// + +## 升级 `pip` + +/// tip + +如果你使用 `uv` 来安装内容,而不是 `pip`,那么你就不需要升级 `pip`。😎 + +/// + +如果你使用 `pip` 来安装包(它是 Python 的默认组件),你应该将它 **升级** 到最新版本。 + +在安装包时出现的许多奇怪的错误都可以通过先升级 `pip` 来解决。 + +/// tip + +通常你只需要在创建虚拟环境后 **执行一次** 这个操作。 + +/// + +确保虚拟环境是激活的 (使用上面的命令),然后运行: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## 添加 `.gitignore` + +如果你使用 **Git** (这是你应该使用的),添加一个 `.gitignore` 文件来排除你的 `.venv` 中的所有内容。 + +/// tip + +如果你使用 `uv` 来创建虚拟环境,它会自动为你完成这个操作,你可以跳过这一步。😎 + +/// + +/// tip + +通常你只需要在创建虚拟环境后 **执行一次** 这个操作。 + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | 上述命令的含义 + +* `echo "*"`: 将在终端中 "打印" 文本 `*`(接下来的部分会对这个操作进行一些修改) +* `>`: 使左边的命令打印到终端的任何内容实际上都不会被打印,而是会被写入到右边的文件中 +* `.gitignore`: 被写入文本的文件的名称 + +而 `*` 对于 Git 来说意味着 "所有内容"。所以,它会忽略 `.venv` 目录中的所有内容。 + +该命令会创建一个名为 `.gitignore` 的文件,内容如下: + +```gitignore +* +``` + +/// + +## 安装软件包 + +在激活虚拟环境后,你可以在其中安装软件包。 + +/// tip + +当你需要安装或升级软件包时,执行本操作**一次**; + +如果你需要再升级版本或添加新软件包,你可以**再次执行此操作**。 + +/// + +### 直接安装包 + +如果你急于安装,不想使用文件来声明工程的软件包依赖,您可以直接安装它们。 + +/// tip + +将程序所需的软件包及其版本放在文件中(例如 `requirements.txt` 或 `pyproject.toml`)是个好(并且非常好)的主意。 + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +如果你有 `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### 从 `requirements.txt` 安装 + +如果你有一个 `requirements.txt` 文件,你可以使用它来安装其中的软件包。 + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +如果你有 `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | 关于 `requirements.txt` + +一个包含一些软件包的 `requirements.txt` 文件看起来应该是这样的: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## 运行程序 + +在你激活虚拟环境后,你可以运行你的程序,它将使用虚拟环境中的 Python 和你在其中安装的软件包。 + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## 配置编辑器 + +你可能会用到编辑器(即 IDE —— 译者注),请确保配置它使用与你创建的相同的虚拟环境(它可能会自动检测到),以便你可以获得自动补全和内联错误提示。 + +例如: + +* VS Code +* PyCharm + +/// tip + +通常你只需要在创建虚拟环境时执行此操作**一次**。 + +/// + +## 退出虚拟环境 + +当你完成工作后,你可以**退出**虚拟环境。 + +
+ +```console +$ deactivate +``` + +
+ +这样,当你运行 `python` 时,它不会尝试从安装了软件包的虚拟环境中运行。(即,它将不再会尝试从虚拟环境中运行,也不会使用其中安装的软件包。—— 译者注) + +## 开始工作 + +现在你已经准备好开始你的工作了。 + + + +/// tip + +你想要理解上面的所有内容吗? + +继续阅读。👇🤓 + +/// + +## 为什么要使用虚拟环境 + +你需要安装 Python 才能使用 FastAPI。 + +之后,你需要**安装** FastAPI 和你想要使用的任何其他**软件包**。 + +要安装软件包,你通常会使用随 Python 一起提供的 `pip` 命令(或类似的替代方案)。 + +然而,如果你直接使用 `pip`,软件包将被安装在你的**全局 Python 环境**中(即 Python 的全局安装)。 + +### 存在的问题 + +那么,在全局 Python 环境中安装软件包有什么问题呢? + +有些时候,你可能会编写许多不同的程序,这些程序依赖于**不同的软件包**;你所做的一些工程也会依赖于**同一软件包的不同版本**。😱 + +例如,你可能会创建一个名为 `philosophers-stone` 的工程,这个程序依赖于另一个名为 **`harry` 的软件包,使用版本 `1`**。因此,你需要安装 `harry`。 + +```mermaid +flowchart LR + stone(philosophers-stone) -->|需要| harry-1[harry v1] +``` + +然而在此之后,你又创建了另一个名为 `prisoner-of-azkaban` 的工程,这个工程也依赖于 `harry`,但是这个工程需要 **`harry` 版本 `3`**。 + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |需要| harry-3[harry v3] +``` + +那么现在的问题是,如果你将软件包安装在全局环境中而不是在本地**虚拟环境**中,你将不得不面临选择安装哪个版本的 `harry` 的问题。 + +如果你想运行 `philosophers-stone`,你需要首先安装 `harry` 版本 `1`,例如: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +然后你将在全局 Python 环境中安装 `harry` 版本 `1`。 + +```mermaid +flowchart LR + subgraph global[全局环境] + harry-1[harry v1] + end + subgraph stone-project[工程 philosophers-stone] + stone(philosophers-stone) -->|需要| harry-1 + end +``` + +但是如果你想运行 `prisoner-of-azkaban`,你需要卸载 `harry` 版本 `1` 并安装 `harry` 版本 `3`(或者说,只要你安装版本 `3` ,版本 `1` 就会自动卸载)。 + +
+ +```console +$ pip install "harry==3" +``` + +
+ +于是,你在你的全局 Python 环境中安装了 `harry` 版本 `3`。 + +如果你再次尝试运行 `philosophers-stone`,有可能它**无法正常工作**,因为它需要 `harry` 版本 `1`。 + +```mermaid +flowchart LR + subgraph global[全局环境] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[工程 philosophers-stone] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[工程 prisoner-of-azkaban] + azkaban(prisoner-of-azkaban) --> |需要| harry-3 + end +``` + +/// tip + +Python 包在推出**新版本**时通常会尽量**避免破坏性更改**,但最好还是要小心,要想清楚再安装新版本,而且在运行测试以确保一切能正常工作时再安装。 + +/// + +现在,想象一下,如果有**许多**其他**软件包**,它们都是你的**工程所依赖的**。这是非常难以管理的。你可能会发现,有些工程使用了一些**不兼容的软件包版本**,而不知道为什么某些东西无法正常工作。 + +此外,取决于你的操作系统(例如 Linux、Windows、macOS),它可能已经预先安装了 Python。在这种情况下,它可能已经预先安装了一些软件包,这些软件包的特定版本是**系统所需的**。如果你在全局 Python 环境中安装软件包,你可能会**破坏**一些随操作系统一起安装的程序。 + +## 软件包安装在哪里 + +当你安装 Python 时,它会在你的计算机上创建一些目录,并在这些目录中放一些文件。 + +其中一些目录负责存放你安装的所有软件包。 + +当你运行: + +
+ +```console +// 先别去运行这个命令,这只是一个示例 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +这将会从 PyPI 下载一个压缩文件,其中包含 FastAPI 代码。 + +它还会**下载** FastAPI 依赖的其他软件包的文件。 + +然后它会**解压**所有这些文件,并将它们放在你的计算机上的一个目录中。 + +默认情况下,它会将下载并解压的这些文件放在随 Python 安装的目录中,这就是**全局环境**。 + +## 什么是虚拟环境 + +解决软件包都安装在全局环境中的问题的方法是为你所做的每个工程使用一个**虚拟环境**。 + +虚拟环境是一个**目录**,与全局环境非常相似,你可以在其中专为某个工程安装软件包。 + +这样,每个工程都会有自己的虚拟环境(`.venv` 目录),其中包含自己的软件包。 + +```mermaid +flowchart TB + subgraph stone-project[工程 philosophers-stone] + stone(philosophers-stone) --->|需要| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[工程 prisoner-of-azkaban] + azkaban(prisoner-of-azkaban) --->|需要| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## 激活虚拟环境意味着什么 + +当你激活了一个虚拟环境,例如: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +或者如果你在 Windows 上使用 Bash(例如 Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +这个命令会创建或修改一些[环境变量](environment-variables.md){.internal-link target=_blank},这些环境变量将在接下来的命令中可用。 + +其中之一是 `PATH` 变量。 + +/// tip + +你可以在 [环境变量](environment-variables.md#path-environment-variable){.internal-link target=_blank} 部分了解更多关于 `PATH` 环境变量的内容。 + +/// + +激活虚拟环境会将其路径 `.venv/bin`(在 Linux 和 macOS 上)或 `.venv\Scripts`(在 Windows 上)添加到 `PATH` 环境变量中。 + +假设在激活环境之前,`PATH` 变量看起来像这样: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +这意味着系统会在以下目录中查找程序: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +这意味着系统会在以下目录中查找程序: + +* `C:\Windows\System32` + +//// + +激活虚拟环境后,`PATH` 变量会变成这样: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +这意味着系统现在会首先在以下目录中查找程序: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +然后再在其他目录中查找。 + +因此,当你在终端中输入 `python` 时,系统会在以下目录中找到 Python 程序: + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +并使用这个。 + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +这意味着系统现在会首先在以下目录中查找程序: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +然后再在其他目录中查找。 + +因此,当你在终端中输入 `python` 时,系统会在以下目录中找到 Python 程序: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +并使用这个。 + +//// + +一个重要的细节是,虚拟环境路径会被放在 `PATH` 变量的**开头**。系统会在找到任何其他可用的 Python **之前**找到它。这样,当你运行 `python` 时,它会使用**虚拟环境中**的 Python,而不是任何其他 `python`(例如,全局环境中的 `python`)。 + +激活虚拟环境还会改变其他一些东西,但这是它所做的最重要的事情之一。 + +## 检查虚拟环境 + +当你检查虚拟环境是否激活时,例如: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +这意味着将使用的 `python` 程序是**在虚拟环境中**的那个。 + +在 Linux 和 macOS 中使用 `which`,在 Windows PowerShell 中使用 `Get-Command`。 + +这个命令的工作方式是,它会在 `PATH` 环境变量中查找,按顺序**逐个路径**查找名为 `python` 的程序。一旦找到,它会**显示该程序的路径**。 + +最重要的部分是,当你调用 `python` 时,将执行的就是这个确切的 "`python`"。 + +因此,你可以确认你是否在正确的虚拟环境中。 + +/// tip + +激活一个虚拟环境,获取一个 Python,然后**转到另一个工程**是一件很容易的事情; + +但如果第二个工程**无法工作**,那是因为你使用了来自另一个工程的虚拟环境的、**不正确的 Python**。 + +因此,会检查正在使用的 `python` 是很有用的。🤓 + +/// + +## 为什么要停用虚拟环境 + +例如,你可能正在一个工程 `philosophers-stone` 上工作,**激活了该虚拟环境**,安装了包并使用了该环境, + +然后你想要在**另一个工程** `prisoner-of-azkaban` 上工作, + +你进入那个工程: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +如果你不去停用 `philosophers-stone` 的虚拟环境,当你在终端中运行 `python` 时,它会尝试使用 `philosophers-stone` 中的 Python。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// 导入 sirius 报错,它没有安装 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +但是如果你停用虚拟环境并激活 `prisoner-of-askaban` 的新虚拟环境,那么当你运行 `python` 时,它会使用 `prisoner-of-askaban` 中的虚拟环境中的 Python。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// 你不需要在旧目录中操作停用,你可以在任何地方操作停用,甚至在转到另一个工程之后 😎 +$ deactivate + +// 激活 prisoner-of-azkaban/.venv 中的虚拟环境 🚀 +$ source .venv/bin/activate + +// 现在当你运行 python 时,它会在这个虚拟环境中找到安装的 sirius 包 ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
+ +## 替代方案 + +这是一个简单的指南,可以帮助你入门并教会你如何理解一切**底层**的东西。 + +有许多**替代方案**来管理虚拟环境、包依赖(requirements)、工程。 + +一旦你准备好并想要使用一个工具来**管理整个工程**、包依赖、虚拟环境等,建议你尝试 uv。 + +`uv` 可以做很多事情,它可以: + +* 为你**安装 Python**,包括不同的版本 +* 为你的工程管理**虚拟环境** +* 安装**软件包** +* 为你的工程管理软件包的**依赖和版本** +* 确保你有一个**确切**的软件包和版本集合来安装,包括它们的依赖项,这样你就可以确保在生产中运行你的工程与在开发时在你的计算机上运行的工程完全相同,这被称为**锁定** +* 还有很多其他功能 + +## 结论 + +如果你读过并理解了所有这些,现在**你对虚拟环境的了解比很多开发者都要多**。🤓 + +在未来当你调试看起来复杂的东西时,了解这些细节很可能会有用,你会知道**它是如何在底层工作的**。😎 diff --git a/docs_src/advanced_middleware/tutorial003.py b/docs_src/advanced_middleware/tutorial003.py index b99e3edd1..e2c87e67d 100644 --- a/docs_src/advanced_middleware/tutorial003.py +++ b/docs_src/advanced_middleware/tutorial003.py @@ -3,7 +3,7 @@ from fastapi.middleware.gzip import GZipMiddleware app = FastAPI() -app.add_middleware(GZipMiddleware, minimum_size=1000) +app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=5) @app.get("/") diff --git a/docs_src/app_testing/app_b_an/main.py b/docs_src/app_testing/app_b_an/main.py index c63134fc9..c66278fdd 100644 --- a/docs_src/app_testing/app_b_an/main.py +++ b/docs_src/app_testing/app_b_an/main.py @@ -34,6 +34,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an/test_main.py b/docs_src/app_testing/app_b_an/test_main.py index e2eda449d..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an/test_main.py +++ b/docs_src/app_testing/app_b_an/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_an_py310/main.py b/docs_src/app_testing/app_b_an_py310/main.py index 48c27a0b8..c5952be0b 100644 --- a/docs_src/app_testing/app_b_an_py310/main.py +++ b/docs_src/app_testing/app_b_an_py310/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an_py310/test_main.py b/docs_src/app_testing/app_b_an_py310/test_main.py index e2eda449d..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an_py310/test_main.py +++ b/docs_src/app_testing/app_b_an_py310/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_an_py39/main.py b/docs_src/app_testing/app_b_an_py39/main.py index 935a510b7..142e23a26 100644 --- a/docs_src/app_testing/app_b_an_py39/main.py +++ b/docs_src/app_testing/app_b_an_py39/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an_py39/test_main.py b/docs_src/app_testing/app_b_an_py39/test_main.py index e2eda449d..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an_py39/test_main.py +++ b/docs_src/app_testing/app_b_an_py39/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/async_sql_databases/tutorial001.py b/docs_src/async_sql_databases/tutorial001.py deleted file mode 100644 index cbf43d790..000000000 --- a/docs_src/async_sql_databases/tutorial001.py +++ /dev/null @@ -1,65 +0,0 @@ -from typing import List - -import databases -import sqlalchemy -from fastapi import FastAPI -from pydantic import BaseModel - -# SQLAlchemy specific code, as with any other app -DATABASE_URL = "sqlite:///./test.db" -# DATABASE_URL = "postgresql://user:password@postgresserver/db" - -database = databases.Database(DATABASE_URL) - -metadata = sqlalchemy.MetaData() - -notes = sqlalchemy.Table( - "notes", - metadata, - sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True), - sqlalchemy.Column("text", sqlalchemy.String), - sqlalchemy.Column("completed", sqlalchemy.Boolean), -) - - -engine = sqlalchemy.create_engine( - DATABASE_URL, connect_args={"check_same_thread": False} -) -metadata.create_all(engine) - - -class NoteIn(BaseModel): - text: str - completed: bool - - -class Note(BaseModel): - id: int - text: str - completed: bool - - -app = FastAPI() - - -@app.on_event("startup") -async def startup(): - await database.connect() - - -@app.on_event("shutdown") -async def shutdown(): - await database.disconnect() - - -@app.get("/notes/", response_model=List[Note]) -async def read_notes(): - query = notes.select() - return await database.fetch_all(query) - - -@app.post("/notes/", response_model=Note) -async def create_note(note: NoteIn): - query = notes.insert().values(text=note.text, completed=note.completed) - last_record_id = await database.execute(query) - return {**note.dict(), "id": last_record_id} diff --git a/docs_src/async_tests/test_main.py b/docs_src/async_tests/test_main.py index 9f1527d5f..a57a31f7d 100644 --- a/docs_src/async_tests/test_main.py +++ b/docs_src/async_tests/test_main.py @@ -1,12 +1,14 @@ import pytest -from httpx import AsyncClient +from httpx import ASGITransport, AsyncClient from .main import app @pytest.mark.anyio async def test_root(): - async with AsyncClient(app=app, base_url="http://test") as ac: + async with AsyncClient( + transport=ASGITransport(app=app), base_url="http://test" + ) as ac: response = await ac.get("/") assert response.status_code == 200 assert response.json() == {"message": "Tomato"} diff --git a/docs_src/cookie_param_models/tutorial001.py b/docs_src/cookie_param_models/tutorial001.py new file mode 100644 index 000000000..cc65c43e1 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001.py @@ -0,0 +1,17 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_an.py b/docs_src/cookie_param_models/tutorial001_an.py new file mode 100644 index 000000000..e5839ffd5 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_an.py @@ -0,0 +1,18 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_an_py310.py b/docs_src/cookie_param_models/tutorial001_an_py310.py new file mode 100644 index 000000000..24cc889a9 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_an_py310.py @@ -0,0 +1,17 @@ +from typing import Annotated + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_an_py39.py b/docs_src/cookie_param_models/tutorial001_an_py39.py new file mode 100644 index 000000000..3d90c2007 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_an_py39.py @@ -0,0 +1,17 @@ +from typing import Annotated, Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_py310.py b/docs_src/cookie_param_models/tutorial001_py310.py new file mode 100644 index 000000000..7cdee5a92 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_py310.py @@ -0,0 +1,15 @@ +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002.py b/docs_src/cookie_param_models/tutorial002.py new file mode 100644 index 000000000..9679e890f --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002.py @@ -0,0 +1,19 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_an.py b/docs_src/cookie_param_models/tutorial002_an.py new file mode 100644 index 000000000..ce5644b7b --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_an.py @@ -0,0 +1,20 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_an_py310.py b/docs_src/cookie_param_models/tutorial002_an_py310.py new file mode 100644 index 000000000..7fa70fe92 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_an_py310.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_an_py39.py b/docs_src/cookie_param_models/tutorial002_an_py39.py new file mode 100644 index 000000000..a906ce6a1 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_an_py39.py @@ -0,0 +1,19 @@ +from typing import Annotated, Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1.py b/docs_src/cookie_param_models/tutorial002_pv1.py new file mode 100644 index 000000000..13f78b850 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1.py @@ -0,0 +1,20 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an.py b/docs_src/cookie_param_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..ddfda9b6f --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_an.py @@ -0,0 +1,21 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py b/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py new file mode 100644 index 000000000..ac00360b6 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py @@ -0,0 +1,20 @@ +from typing import Annotated + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py b/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..573caea4b --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,20 @@ +from typing import Annotated, Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_py310.py b/docs_src/cookie_param_models/tutorial002_pv1_py310.py new file mode 100644 index 000000000..2c59aad12 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_py310.py @@ -0,0 +1,18 @@ +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_py310.py b/docs_src/cookie_param_models/tutorial002_py310.py new file mode 100644 index 000000000..f011aa1af --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_py310.py @@ -0,0 +1,17 @@ +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/custom_docs_ui/tutorial001.py b/docs_src/custom_docs_ui/tutorial001.py index 4384433e3..f7ceb0c2f 100644 --- a/docs_src/custom_docs_ui/tutorial001.py +++ b/docs_src/custom_docs_ui/tutorial001.py @@ -14,8 +14,8 @@ async def custom_swagger_ui_html(): openapi_url=app.openapi_url, title=app.title + " - Swagger UI", oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, - swagger_js_url="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-bundle.js", - swagger_css_url="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css", + swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js", + swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css", ) diff --git a/docs_src/dataclasses/tutorial002.py b/docs_src/dataclasses/tutorial002.py index 08a238080..ece2f150c 100644 --- a/docs_src/dataclasses/tutorial002.py +++ b/docs_src/dataclasses/tutorial002.py @@ -21,6 +21,6 @@ async def read_next_item(): return { "name": "Island In The Moon", "price": 12.99, - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", "tags": ["breater"], } diff --git a/docs_src/dataclasses/tutorial003.py b/docs_src/dataclasses/tutorial003.py index 34ce1199e..c61315513 100644 --- a/docs_src/dataclasses/tutorial003.py +++ b/docs_src/dataclasses/tutorial003.py @@ -33,7 +33,7 @@ def get_authors(): # (8) "items": [ { "name": "Island In The Moon", - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", }, {"name": "Holy Buddies"}, ], diff --git a/docs_src/extra_data_types/tutorial001.py b/docs_src/extra_data_types/tutorial001.py index 8ae8472a7..71de958ff 100644 --- a/docs_src/extra_data_types/tutorial001.py +++ b/docs_src/extra_data_types/tutorial001.py @@ -10,10 +10,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Union[datetime, None] = Body(default=None), - end_datetime: Union[datetime, None] = Body(default=None), + start_datetime: datetime = Body(), + end_datetime: datetime = Body(), + process_after: timedelta = Body(), repeat_at: Union[time, None] = Body(default=None), - process_after: Union[timedelta, None] = Body(default=None), ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -21,8 +21,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_an.py b/docs_src/extra_data_types/tutorial001_an.py index a4c074241..257d0c7c8 100644 --- a/docs_src/extra_data_types/tutorial001_an.py +++ b/docs_src/extra_data_types/tutorial001_an.py @@ -11,10 +11,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Annotated[Union[datetime, None], Body()] = None, - end_datetime: Annotated[Union[datetime, None], Body()] = None, + start_datetime: Annotated[datetime, Body()], + end_datetime: Annotated[datetime, Body()], + process_after: Annotated[timedelta, Body()], repeat_at: Annotated[Union[time, None], Body()] = None, - process_after: Annotated[Union[timedelta, None], Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -22,8 +22,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_an_py310.py b/docs_src/extra_data_types/tutorial001_an_py310.py index 4f69c40d9..668bf1909 100644 --- a/docs_src/extra_data_types/tutorial001_an_py310.py +++ b/docs_src/extra_data_types/tutorial001_an_py310.py @@ -10,10 +10,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Annotated[datetime | None, Body()] = None, - end_datetime: Annotated[datetime | None, Body()] = None, + start_datetime: Annotated[datetime, Body()], + end_datetime: Annotated[datetime, Body()], + process_after: Annotated[timedelta, Body()], repeat_at: Annotated[time | None, Body()] = None, - process_after: Annotated[timedelta | None, Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -21,8 +21,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_an_py39.py b/docs_src/extra_data_types/tutorial001_an_py39.py index 630d36ae3..fa3551d66 100644 --- a/docs_src/extra_data_types/tutorial001_an_py39.py +++ b/docs_src/extra_data_types/tutorial001_an_py39.py @@ -10,10 +10,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Annotated[Union[datetime, None], Body()] = None, - end_datetime: Annotated[Union[datetime, None], Body()] = None, + start_datetime: Annotated[datetime, Body()], + end_datetime: Annotated[datetime, Body()], + process_after: Annotated[timedelta, Body()], repeat_at: Annotated[Union[time, None], Body()] = None, - process_after: Annotated[Union[timedelta, None], Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -21,8 +21,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_py310.py b/docs_src/extra_data_types/tutorial001_py310.py index d22f81888..a275a0577 100644 --- a/docs_src/extra_data_types/tutorial001_py310.py +++ b/docs_src/extra_data_types/tutorial001_py310.py @@ -9,10 +9,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: datetime | None = Body(default=None), - end_datetime: datetime | None = Body(default=None), + start_datetime: datetime = Body(), + end_datetime: datetime = Body(), + process_after: timedelta = Body(), repeat_at: time | None = Body(default=None), - process_after: timedelta | None = Body(default=None), ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -20,8 +20,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/header_param_models/tutorial001.py b/docs_src/header_param_models/tutorial001.py new file mode 100644 index 000000000..4caaba87b --- /dev/null +++ b/docs_src/header_param_models/tutorial001.py @@ -0,0 +1,19 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial001_an.py b/docs_src/header_param_models/tutorial001_an.py new file mode 100644 index 000000000..b55c6b56b --- /dev/null +++ b/docs_src/header_param_models/tutorial001_an.py @@ -0,0 +1,20 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial001_an_py310.py b/docs_src/header_param_models/tutorial001_an_py310.py new file mode 100644 index 000000000..acfb6b9bf --- /dev/null +++ b/docs_src/header_param_models/tutorial001_an_py310.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial001_an_py39.py b/docs_src/header_param_models/tutorial001_an_py39.py new file mode 100644 index 000000000..51a5f94fc --- /dev/null +++ b/docs_src/header_param_models/tutorial001_an_py39.py @@ -0,0 +1,19 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial001_py310.py b/docs_src/header_param_models/tutorial001_py310.py new file mode 100644 index 000000000..7239c64ce --- /dev/null +++ b/docs_src/header_param_models/tutorial001_py310.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial001_py39.py b/docs_src/header_param_models/tutorial001_py39.py new file mode 100644 index 000000000..4c1137813 --- /dev/null +++ b/docs_src/header_param_models/tutorial001_py39.py @@ -0,0 +1,19 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002.py b/docs_src/header_param_models/tutorial002.py new file mode 100644 index 000000000..3f9aac58d --- /dev/null +++ b/docs_src/header_param_models/tutorial002.py @@ -0,0 +1,21 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_an.py b/docs_src/header_param_models/tutorial002_an.py new file mode 100644 index 000000000..771135d77 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_an.py @@ -0,0 +1,22 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_an_py310.py b/docs_src/header_param_models/tutorial002_an_py310.py new file mode 100644 index 000000000..e9535f045 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_an_py310.py @@ -0,0 +1,21 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_an_py39.py b/docs_src/header_param_models/tutorial002_an_py39.py new file mode 100644 index 000000000..ca5208c9d --- /dev/null +++ b/docs_src/header_param_models/tutorial002_an_py39.py @@ -0,0 +1,21 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1.py b/docs_src/header_param_models/tutorial002_pv1.py new file mode 100644 index 000000000..7e56cd993 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1.py @@ -0,0 +1,22 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_an.py b/docs_src/header_param_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..236778231 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_an.py @@ -0,0 +1,23 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_an_py310.py b/docs_src/header_param_models/tutorial002_pv1_an_py310.py new file mode 100644 index 000000000..e99e24ea5 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_an_py310.py @@ -0,0 +1,22 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_an_py39.py b/docs_src/header_param_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..18398b726 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,22 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_py310.py b/docs_src/header_param_models/tutorial002_pv1_py310.py new file mode 100644 index 000000000..3dbff9d7b --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_py310.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_py39.py b/docs_src/header_param_models/tutorial002_pv1_py39.py new file mode 100644 index 000000000..86e19be0d --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_py39.py @@ -0,0 +1,22 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_py310.py b/docs_src/header_param_models/tutorial002_py310.py new file mode 100644 index 000000000..3d2296345 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_py310.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_py39.py b/docs_src/header_param_models/tutorial002_py39.py new file mode 100644 index 000000000..f8ce559a7 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_py39.py @@ -0,0 +1,21 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/middleware/tutorial001.py b/docs_src/middleware/tutorial001.py index 6bab3410a..e65a7dade 100644 --- a/docs_src/middleware/tutorial001.py +++ b/docs_src/middleware/tutorial001.py @@ -7,8 +7,8 @@ app = FastAPI() @app.middleware("http") async def add_process_time_header(request: Request, call_next): - start_time = time.time() + start_time = time.perf_counter() response = await call_next(request) - process_time = time.time() - start_time + process_time = time.perf_counter() - start_time response.headers["X-Process-Time"] = str(process_time) return response diff --git a/docs_src/nosql_databases/tutorial001.py b/docs_src/nosql_databases/tutorial001.py deleted file mode 100644 index 91893e528..000000000 --- a/docs_src/nosql_databases/tutorial001.py +++ /dev/null @@ -1,53 +0,0 @@ -from typing import Union - -from couchbase import LOCKMODE_WAIT -from couchbase.bucket import Bucket -from couchbase.cluster import Cluster, PasswordAuthenticator -from fastapi import FastAPI -from pydantic import BaseModel - -USERPROFILE_DOC_TYPE = "userprofile" - - -def get_bucket(): - cluster = Cluster( - "couchbase://couchbasehost:8091?fetch_mutation_tokens=1&operation_timeout=30&n1ql_timeout=300" - ) - authenticator = PasswordAuthenticator("username", "password") - cluster.authenticate(authenticator) - bucket: Bucket = cluster.open_bucket("bucket_name", lockmode=LOCKMODE_WAIT) - bucket.timeout = 30 - bucket.n1ql_timeout = 300 - return bucket - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - type: str = USERPROFILE_DOC_TYPE - hashed_password: str - - -def get_user(bucket: Bucket, username: str): - doc_id = f"userprofile::{username}" - result = bucket.get(doc_id, quiet=True) - if not result.value: - return None - user = UserInDB(**result.value) - return user - - -# FastAPI specific code -app = FastAPI() - - -@app.get("/users/{username}", response_model=User) -def read_user(username: str): - bucket = get_bucket() - user = get_user(bucket=bucket, username=username) - return user diff --git a/docs_src/path_operation_advanced_configuration/tutorial007.py b/docs_src/path_operation_advanced_configuration/tutorial007.py index 972ddbd2c..54e2e9399 100644 --- a/docs_src/path_operation_advanced_configuration/tutorial007.py +++ b/docs_src/path_operation_advanced_configuration/tutorial007.py @@ -30,5 +30,5 @@ async def create_item(request: Request): try: item = Item.model_validate(data) except ValidationError as e: - raise HTTPException(status_code=422, detail=e.errors()) + raise HTTPException(status_code=422, detail=e.errors(include_url=False)) return item diff --git a/docs_src/path_params_numeric_validations/tutorial006.py b/docs_src/path_params_numeric_validations/tutorial006.py index 0ea32694a..f07629aa0 100644 --- a/docs_src/path_params_numeric_validations/tutorial006.py +++ b/docs_src/path_params_numeric_validations/tutorial006.py @@ -13,4 +13,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an.py b/docs_src/path_params_numeric_validations/tutorial006_an.py index 22a143623..ac4732573 100644 --- a/docs_src/path_params_numeric_validations/tutorial006_an.py +++ b/docs_src/path_params_numeric_validations/tutorial006_an.py @@ -14,4 +14,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py index 804751893..426ec3776 100644 --- a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py +++ b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py @@ -15,4 +15,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/query_param_models/tutorial001.py b/docs_src/query_param_models/tutorial001.py new file mode 100644 index 000000000..0c0ab315e --- /dev/null +++ b/docs_src/query_param_models/tutorial001.py @@ -0,0 +1,19 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_an.py b/docs_src/query_param_models/tutorial001_an.py new file mode 100644 index 000000000..28375057c --- /dev/null +++ b/docs_src/query_param_models/tutorial001_an.py @@ -0,0 +1,19 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_an_py310.py b/docs_src/query_param_models/tutorial001_an_py310.py new file mode 100644 index 000000000..71427acae --- /dev/null +++ b/docs_src/query_param_models/tutorial001_an_py310.py @@ -0,0 +1,18 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_an_py39.py b/docs_src/query_param_models/tutorial001_an_py39.py new file mode 100644 index 000000000..ba690d3e3 --- /dev/null +++ b/docs_src/query_param_models/tutorial001_an_py39.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_py310.py b/docs_src/query_param_models/tutorial001_py310.py new file mode 100644 index 000000000..3ebf9f4d7 --- /dev/null +++ b/docs_src/query_param_models/tutorial001_py310.py @@ -0,0 +1,18 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_py39.py b/docs_src/query_param_models/tutorial001_py39.py new file mode 100644 index 000000000..54b52a054 --- /dev/null +++ b/docs_src/query_param_models/tutorial001_py39.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002.py b/docs_src/query_param_models/tutorial002.py new file mode 100644 index 000000000..1633bc464 --- /dev/null +++ b/docs_src/query_param_models/tutorial002.py @@ -0,0 +1,21 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_an.py b/docs_src/query_param_models/tutorial002_an.py new file mode 100644 index 000000000..69705d4b4 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_an.py @@ -0,0 +1,21 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_an_py310.py b/docs_src/query_param_models/tutorial002_an_py310.py new file mode 100644 index 000000000..975956502 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_an_py310.py @@ -0,0 +1,20 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_an_py39.py b/docs_src/query_param_models/tutorial002_an_py39.py new file mode 100644 index 000000000..2d4c1a62b --- /dev/null +++ b/docs_src/query_param_models/tutorial002_an_py39.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1.py b/docs_src/query_param_models/tutorial002_pv1.py new file mode 100644 index 000000000..71ccd961d --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1.py @@ -0,0 +1,22 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_an.py b/docs_src/query_param_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..1dd29157a --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_an.py @@ -0,0 +1,22 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_an_py310.py b/docs_src/query_param_models/tutorial002_pv1_an_py310.py new file mode 100644 index 000000000..d635aae88 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_an_py310.py @@ -0,0 +1,21 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_an_py39.py b/docs_src/query_param_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..494fef11f --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_py310.py b/docs_src/query_param_models/tutorial002_pv1_py310.py new file mode 100644 index 000000000..9ffdeefc0 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_py310.py @@ -0,0 +1,21 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_py39.py b/docs_src/query_param_models/tutorial002_pv1_py39.py new file mode 100644 index 000000000..7fa456a79 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_py39.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_py310.py b/docs_src/query_param_models/tutorial002_py310.py new file mode 100644 index 000000000..6ec418499 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_py310.py @@ -0,0 +1,20 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_py39.py b/docs_src/query_param_models/tutorial002_py39.py new file mode 100644 index 000000000..f9bba028c --- /dev/null +++ b/docs_src/query_param_models/tutorial002_py39.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_params_str_validations/tutorial006d.py b/docs_src/query_params_str_validations/tutorial006d.py index 42c5bf4eb..a8d69c889 100644 --- a/docs_src/query_params_str_validations/tutorial006d.py +++ b/docs_src/query_params_str_validations/tutorial006d.py @@ -1,11 +1,10 @@ from fastapi import FastAPI, Query -from pydantic import Required app = FastAPI() @app.get("/items/") -async def read_items(q: str = Query(default=Required, min_length=3)): +async def read_items(q: str = Query(default=..., min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006d_an.py b/docs_src/query_params_str_validations/tutorial006d_an.py index bc8283e15..ea3b02583 100644 --- a/docs_src/query_params_str_validations/tutorial006d_an.py +++ b/docs_src/query_params_str_validations/tutorial006d_an.py @@ -1,12 +1,11 @@ from fastapi import FastAPI, Query -from pydantic import Required from typing_extensions import Annotated app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = Required): +async def read_items(q: Annotated[str, Query(min_length=3)] = ...): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006d_an_py39.py b/docs_src/query_params_str_validations/tutorial006d_an_py39.py index 035d9e3bd..687a9f544 100644 --- a/docs_src/query_params_str_validations/tutorial006d_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial006d_an_py39.py @@ -1,13 +1,12 @@ from typing import Annotated from fastapi import FastAPI, Query -from pydantic import Required app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = Required): +async def read_items(q: Annotated[str, Query(min_length=3)] = ...): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/request_form_models/tutorial001.py b/docs_src/request_form_models/tutorial001.py new file mode 100644 index 000000000..98feff0b9 --- /dev/null +++ b/docs_src/request_form_models/tutorial001.py @@ -0,0 +1,14 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial001_an.py b/docs_src/request_form_models/tutorial001_an.py new file mode 100644 index 000000000..30483d445 --- /dev/null +++ b/docs_src/request_form_models/tutorial001_an.py @@ -0,0 +1,15 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial001_an_py39.py b/docs_src/request_form_models/tutorial001_an_py39.py new file mode 100644 index 000000000..7cc81aae9 --- /dev/null +++ b/docs_src/request_form_models/tutorial001_an_py39.py @@ -0,0 +1,16 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002.py b/docs_src/request_form_models/tutorial002.py new file mode 100644 index 000000000..59b329e8d --- /dev/null +++ b/docs_src/request_form_models/tutorial002.py @@ -0,0 +1,15 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial002_an.py b/docs_src/request_form_models/tutorial002_an.py new file mode 100644 index 000000000..bcb022795 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_an.py @@ -0,0 +1,16 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002_an_py39.py b/docs_src/request_form_models/tutorial002_an_py39.py new file mode 100644 index 000000000..3004e0852 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_an_py39.py @@ -0,0 +1,17 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002_pv1.py b/docs_src/request_form_models/tutorial002_pv1.py new file mode 100644 index 000000000..d5f7db2a6 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_pv1.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + class Config: + extra = "forbid" + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial002_pv1_an.py b/docs_src/request_form_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..fe9dbc344 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_pv1_an.py @@ -0,0 +1,18 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + class Config: + extra = "forbid" + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002_pv1_an_py39.py b/docs_src/request_form_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..942d5d411 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + class Config: + extra = "forbid" + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/schema_extra_example/tutorial001_py310_pv1.py b/docs_src/schema_extra_example/tutorial001_pv1_py310.py similarity index 100% rename from docs_src/schema_extra_example/tutorial001_py310_pv1.py rename to docs_src/schema_extra_example/tutorial001_pv1_py310.py diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index d0fbaa572..91d161b8a 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Union +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -98,7 +99,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index eebd36d64..df50754af 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Union +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel from typing_extensions import Annotated @@ -99,7 +100,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 4e50ada7c..eff54ef01 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Annotated +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -98,7 +99,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index eb49aaa67..0455b500c 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Annotated, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -98,7 +99,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 5a905783d..78bee22a3 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -1,8 +1,9 @@ from datetime import datetime, timedelta, timezone +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -97,7 +98,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py index d4a6975da..ccad07969 100644 --- a/docs_src/security/tutorial005.py +++ b/docs_src/security/tutorial005.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import List, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -120,7 +121,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index 982daed2f..5b67cb145 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import List, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError from typing_extensions import Annotated @@ -121,7 +122,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 79aafbff1..297193e35 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import Annotated +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -120,7 +121,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index 3bdab5507..1acf47bdc 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import Annotated, List, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -120,7 +121,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index 9f75aa0be..b244ef08e 100644 --- a/docs_src/security/tutorial005_py310.py +++ b/docs_src/security/tutorial005_py310.py @@ -1,12 +1,13 @@ from datetime import datetime, timedelta, timezone +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -119,7 +120,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py index bac248932..8f0e93376 100644 --- a/docs_src/security/tutorial005_py39.py +++ b/docs_src/security/tutorial005_py39.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -120,7 +121,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: diff --git a/docs_src/sql_databases/sql_app/alt_main.py b/docs_src/sql_databases/sql_app/alt_main.py deleted file mode 100644 index f7206bcb4..000000000 --- a/docs_src/sql_databases/sql_app/alt_main.py +++ /dev/null @@ -1,62 +0,0 @@ -from typing import List - -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=List[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app/crud.py b/docs_src/sql_databases/sql_app/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app/database.py b/docs_src/sql_databases/sql_app/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app/main.py b/docs_src/sql_databases/sql_app/main.py deleted file mode 100644 index e7508c59d..000000000 --- a/docs_src/sql_databases/sql_app/main.py +++ /dev/null @@ -1,55 +0,0 @@ -from typing import List - -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=List[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app/models.py b/docs_src/sql_databases/sql_app/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app/schemas.py b/docs_src/sql_databases/sql_app/schemas.py deleted file mode 100644 index c49beba88..000000000 --- a/docs_src/sql_databases/sql_app/schemas.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import List, Union - -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: List[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app/tests/test_sql_app.py b/docs_src/sql_databases/sql_app/tests/test_sql_app.py deleted file mode 100644 index 5f55add0a..000000000 --- a/docs_src/sql_databases/sql_app/tests/test_sql_app.py +++ /dev/null @@ -1,50 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import StaticPool - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite://" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, - connect_args={"check_same_thread": False}, - poolclass=StaticPool, -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/sql_app_py310/alt_main.py b/docs_src/sql_databases/sql_app_py310/alt_main.py deleted file mode 100644 index 5de88ec3a..000000000 --- a/docs_src/sql_databases/sql_app_py310/alt_main.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py310/crud.py b/docs_src/sql_databases/sql_app_py310/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app_py310/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app_py310/database.py b/docs_src/sql_databases/sql_app_py310/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app_py310/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app_py310/main.py b/docs_src/sql_databases/sql_app_py310/main.py deleted file mode 100644 index a9856d0b6..000000000 --- a/docs_src/sql_databases/sql_app_py310/main.py +++ /dev/null @@ -1,53 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py310/models.py b/docs_src/sql_databases/sql_app_py310/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app_py310/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app_py310/schemas.py b/docs_src/sql_databases/sql_app_py310/schemas.py deleted file mode 100644 index aea2e3f10..000000000 --- a/docs_src/sql_databases/sql_app_py310/schemas.py +++ /dev/null @@ -1,35 +0,0 @@ -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: str | None = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: list[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py deleted file mode 100644 index c60c3356f..000000000 --- a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py +++ /dev/null @@ -1,47 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/sql_app_py39/__init__.py b/docs_src/sql_databases/sql_app_py39/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py39/alt_main.py b/docs_src/sql_databases/sql_app_py39/alt_main.py deleted file mode 100644 index 5de88ec3a..000000000 --- a/docs_src/sql_databases/sql_app_py39/alt_main.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py39/crud.py b/docs_src/sql_databases/sql_app_py39/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app_py39/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app_py39/database.py b/docs_src/sql_databases/sql_app_py39/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app_py39/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app_py39/main.py b/docs_src/sql_databases/sql_app_py39/main.py deleted file mode 100644 index a9856d0b6..000000000 --- a/docs_src/sql_databases/sql_app_py39/main.py +++ /dev/null @@ -1,53 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py39/models.py b/docs_src/sql_databases/sql_app_py39/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app_py39/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app_py39/schemas.py b/docs_src/sql_databases/sql_app_py39/schemas.py deleted file mode 100644 index dadc403d9..000000000 --- a/docs_src/sql_databases/sql_app_py39/schemas.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Union - -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: list[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app_py39/tests/__init__.py b/docs_src/sql_databases/sql_app_py39/tests/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py deleted file mode 100644 index c60c3356f..000000000 --- a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py +++ /dev/null @@ -1,47 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/tutorial001.py b/docs_src/sql_databases/tutorial001.py new file mode 100644 index 000000000..be86ec0ee --- /dev/null +++ b/docs_src/sql_databases/tutorial001.py @@ -0,0 +1,71 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> List[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an.py b/docs_src/sql_databases/tutorial001_an.py new file mode 100644 index 000000000..8c000d31c --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an.py @@ -0,0 +1,74 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select +from typing_extensions import Annotated + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> List[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an_py310.py b/docs_src/sql_databases/tutorial001_an_py310.py new file mode 100644 index 000000000..de1fb81fa --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an_py310.py @@ -0,0 +1,73 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an_py39.py b/docs_src/sql_databases/tutorial001_an_py39.py new file mode 100644 index 000000000..595892746 --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an_py39.py @@ -0,0 +1,73 @@ +from typing import Annotated, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_py310.py b/docs_src/sql_databases/tutorial001_py310.py new file mode 100644 index 000000000..b58462e6a --- /dev/null +++ b/docs_src/sql_databases/tutorial001_py310.py @@ -0,0 +1,69 @@ +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_py39.py b/docs_src/sql_databases/tutorial001_py39.py new file mode 100644 index 000000000..410a52d0c --- /dev/null +++ b/docs_src/sql_databases/tutorial001_py39.py @@ -0,0 +1,71 @@ +from typing import Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002.py b/docs_src/sql_databases/tutorial002.py new file mode 100644 index 000000000..4350d19c6 --- /dev/null +++ b/docs_src/sql_databases/tutorial002.py @@ -0,0 +1,104 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=List[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an.py b/docs_src/sql_databases/tutorial002_an.py new file mode 100644 index 000000000..15e3d7c3a --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an.py @@ -0,0 +1,104 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select +from typing_extensions import Annotated + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=List[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an_py310.py b/docs_src/sql_databases/tutorial002_an_py310.py new file mode 100644 index 000000000..64c554b8a --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an_py310.py @@ -0,0 +1,103 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: int | None = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: str | None = None + age: int | None = None + secret_name: str | None = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an_py39.py b/docs_src/sql_databases/tutorial002_an_py39.py new file mode 100644 index 000000000..a8a0721ff --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an_py39.py @@ -0,0 +1,103 @@ +from typing import Annotated, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_py310.py b/docs_src/sql_databases/tutorial002_py310.py new file mode 100644 index 000000000..ec3d68db5 --- /dev/null +++ b/docs_src/sql_databases/tutorial002_py310.py @@ -0,0 +1,102 @@ +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: int | None = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: str | None = None + age: int | None = None + secret_name: str | None = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_py39.py b/docs_src/sql_databases/tutorial002_py39.py new file mode 100644 index 000000000..d8f5dd090 --- /dev/null +++ b/docs_src/sql_databases/tutorial002_py39.py @@ -0,0 +1,104 @@ +from typing import Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 234969256..51e3ca510 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.110.0" +__version__ = "0.115.4" from starlette import status as status diff --git a/fastapi/__main__.py b/fastapi/__main__.py new file mode 100644 index 000000000..fc36465f5 --- /dev/null +++ b/fastapi/__main__.py @@ -0,0 +1,3 @@ +from fastapi.cli import main + +main() diff --git a/fastapi/_compat.py b/fastapi/_compat.py index 35d4a8723..56c5d744e 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -2,6 +2,7 @@ from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum +from functools import lru_cache from typing import ( Any, Callable, @@ -20,10 +21,12 @@ from typing import ( from fastapi.exceptions import RequestErrorModel from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, create_model -from pydantic.version import VERSION as PYDANTIC_VERSION +from pydantic.version import VERSION as P_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin +# Reassign variable to make it reexported for mypy +PYDANTIC_VERSION = P_VERSION PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") @@ -68,7 +71,7 @@ if PYDANTIC_V2: general_plain_validator_function as with_info_plain_validator_function, # noqa: F401 ) - Required = PydanticUndefined + RequiredParam = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient @@ -127,7 +130,7 @@ if PYDANTIC_V2: ) except ValidationError as exc: return None, _regenerate_error_with_loc( - errors=exc.errors(), loc_prefix=loc + errors=exc.errors(include_url=False), loc_prefix=loc ) def serialize( @@ -266,7 +269,7 @@ if PYDANTIC_V2: def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: error = ValidationError.from_exception_data( "Field required", [{"type": "missing", "loc": loc, "input": {}}] - ).errors()[0] + ).errors(include_url=False)[0] error["input"] = None return error # type: ignore[return-value] @@ -277,6 +280,12 @@ if PYDANTIC_V2: BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] return BodyModel + def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return [ + ModelField(field_info=field_info, name=name) + for name, field_info in model.model_fields.items() + ] + else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 @@ -304,9 +313,10 @@ else: from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) - from pydantic.fields import ( # type: ignore[no-redef,attr-defined] - Required as Required, # noqa: F401 - ) + + # Keeping old "Required" functionality from Pydantic V1, without + # shadowing typing.Required. + RequiredParam: Any = Ellipsis # type: ignore[no-redef] from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) @@ -511,6 +521,9 @@ else: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel + def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return list(model.__fields__.values()) # type: ignore[attr-defined] + def _regenerate_error_with_loc( *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...] @@ -530,6 +543,12 @@ def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if field_annotation_is_sequence(arg): + return True + return False return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) @@ -632,3 +651,8 @@ def is_uploadfile_sequence_annotation(annotation: Any) -> bool: is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation) for sub_annotation in get_args(annotation) ) + + +@lru_cache +def get_cached_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return get_model_fields(model) diff --git a/fastapi/applications.py b/fastapi/applications.py index d3edcc880..6d427cdc2 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -40,7 +40,7 @@ from starlette.requests import Request from starlette.responses import HTMLResponse, JSONResponse, Response from starlette.routing import BaseRoute from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send -from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, deprecated AppType = TypeVar("AppType", bound="FastAPI") @@ -902,7 +902,7 @@ class FastAPI(Starlette): A state object for the application. This is the same object for the entire application, it doesn't change from request to request. - You normally woudln't use this in FastAPI, for most of the cases you + You normally wouldn't use this in FastAPI, for most of the cases you would instead use FastAPI dependencies. This is simply inherited from Starlette. @@ -1056,7 +1056,7 @@ class FastAPI(Starlette): def add_api_route( self, path: str, - endpoint: Callable[..., Coroutine[Any, Any, Response]], + endpoint: Callable[..., Any], *, response_model: Any = Default(None), status_code: Optional[int] = None, diff --git a/fastapi/background.py b/fastapi/background.py index 35ab1b227..203578a41 100644 --- a/fastapi/background.py +++ b/fastapi/background.py @@ -1,7 +1,7 @@ from typing import Any, Callable from starlette.background import BackgroundTasks as StarletteBackgroundTasks -from typing_extensions import Annotated, Doc, ParamSpec # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, ParamSpec P = ParamSpec("P") diff --git a/fastapi/cli.py b/fastapi/cli.py new file mode 100644 index 000000000..8d3301e9d --- /dev/null +++ b/fastapi/cli.py @@ -0,0 +1,13 @@ +try: + from fastapi_cli.cli import main as cli_main + +except ImportError: # pragma: no cover + cli_main = None # type: ignore + + +def main() -> None: + if not cli_main: # type: ignore[truthy-function] + message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n' + print(message) + raise RuntimeError(message) # noqa: B904 + cli_main() diff --git a/fastapi/datastructures.py b/fastapi/datastructures.py index ce03e3ce4..cf8406b0f 100644 --- a/fastapi/datastructures.py +++ b/fastapi/datastructures.py @@ -24,7 +24,7 @@ from starlette.datastructures import Headers as Headers # noqa: F401 from starlette.datastructures import QueryParams as QueryParams # noqa: F401 from starlette.datastructures import State as State # noqa: F401 from starlette.datastructures import UploadFile as StarletteUploadFile -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class UploadFile(StarletteUploadFile): diff --git a/fastapi/dependencies/models.py b/fastapi/dependencies/models.py index 61ef00638..418c11725 100644 --- a/fastapi/dependencies/models.py +++ b/fastapi/dependencies/models.py @@ -1,58 +1,37 @@ -from typing import Any, Callable, List, Optional, Sequence +from dataclasses import dataclass, field +from typing import Any, Callable, List, Optional, Sequence, Tuple from fastapi._compat import ModelField from fastapi.security.base import SecurityBase +@dataclass class SecurityRequirement: - def __init__( - self, security_scheme: SecurityBase, scopes: Optional[Sequence[str]] = None - ): - self.security_scheme = security_scheme - self.scopes = scopes + security_scheme: SecurityBase + scopes: Optional[Sequence[str]] = None +@dataclass class Dependant: - def __init__( - self, - *, - path_params: Optional[List[ModelField]] = None, - query_params: Optional[List[ModelField]] = None, - header_params: Optional[List[ModelField]] = None, - cookie_params: Optional[List[ModelField]] = None, - body_params: Optional[List[ModelField]] = None, - dependencies: Optional[List["Dependant"]] = None, - security_schemes: Optional[List[SecurityRequirement]] = None, - name: Optional[str] = None, - call: Optional[Callable[..., Any]] = None, - request_param_name: Optional[str] = None, - websocket_param_name: Optional[str] = None, - http_connection_param_name: Optional[str] = None, - response_param_name: Optional[str] = None, - background_tasks_param_name: Optional[str] = None, - security_scopes_param_name: Optional[str] = None, - security_scopes: Optional[List[str]] = None, - use_cache: bool = True, - path: Optional[str] = None, - ) -> None: - self.path_params = path_params or [] - self.query_params = query_params or [] - self.header_params = header_params or [] - self.cookie_params = cookie_params or [] - self.body_params = body_params or [] - self.dependencies = dependencies or [] - self.security_requirements = security_schemes or [] - self.request_param_name = request_param_name - self.websocket_param_name = websocket_param_name - self.http_connection_param_name = http_connection_param_name - self.response_param_name = response_param_name - self.background_tasks_param_name = background_tasks_param_name - self.security_scopes = security_scopes - self.security_scopes_param_name = security_scopes_param_name - self.name = name - self.call = call - self.use_cache = use_cache - # Store the path to be able to re-generate a dependable from it in overrides - self.path = path - # Save the cache key at creation to optimize performance + path_params: List[ModelField] = field(default_factory=list) + query_params: List[ModelField] = field(default_factory=list) + header_params: List[ModelField] = field(default_factory=list) + cookie_params: List[ModelField] = field(default_factory=list) + body_params: List[ModelField] = field(default_factory=list) + dependencies: List["Dependant"] = field(default_factory=list) + security_requirements: List[SecurityRequirement] = field(default_factory=list) + name: Optional[str] = None + call: Optional[Callable[..., Any]] = None + request_param_name: Optional[str] = None + websocket_param_name: Optional[str] = None + http_connection_param_name: Optional[str] = None + response_param_name: Optional[str] = None + background_tasks_param_name: Optional[str] = None + security_scopes_param_name: Optional[str] = None + security_scopes: Optional[List[str]] = None + use_cache: bool = True + path: Optional[str] = None + cache_key: Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] = field(init=False) + + def __post_init__(self) -> None: self.cache_key = (self.call, tuple(sorted(set(self.security_scopes or [])))) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 02284b4ed..e2866b488 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -1,6 +1,7 @@ import inspect from contextlib import AsyncExitStack, contextmanager -from copy import deepcopy +from copy import copy, deepcopy +from dataclasses import dataclass from typing import ( Any, Callable, @@ -23,7 +24,7 @@ from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, - Required, + RequiredParam, Undefined, _regenerate_error_with_loc, copy_field_info, @@ -31,6 +32,7 @@ from fastapi._compat import ( evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, + get_cached_model_fields, get_missing_field_error, is_bytes_field, is_bytes_sequence_field, @@ -54,11 +56,18 @@ from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect -from fastapi.utils import create_response_field, get_path_param_names +from fastapi.utils import create_model_field, get_path_param_names +from pydantic import BaseModel from pydantic.fields import FieldInfo from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool -from starlette.datastructures import FormData, Headers, QueryParams, UploadFile +from starlette.datastructures import ( + FormData, + Headers, + ImmutableMultiDict, + QueryParams, + UploadFile, +) from starlette.requests import HTTPConnection, Request from starlette.responses import Response from starlette.websockets import WebSocket @@ -79,17 +88,23 @@ multipart_incorrect_install_error = ( ) -def check_file_field(field: ModelField) -> None: - field_info = field.field_info - if isinstance(field_info, params.Form): +def ensure_multipart_is_installed() -> None: + try: + from python_multipart import __version__ + + # Import an attribute that can be mocked/deleted in testing + assert __version__ > "0.0.12" + except (ImportError, AssertionError): try: # __version__ is available in both multiparts, and can be mocked - from multipart import __version__ # type: ignore + from multipart import __version__ # type: ignore[no-redef,import-untyped] assert __version__ try: # parse_options_header is only available in the right multipart - from multipart.multipart import parse_options_header # type: ignore + from multipart.multipart import ( # type: ignore[import-untyped] + parse_options_header, + ) assert parse_options_header except ImportError: @@ -175,7 +190,7 @@ def get_flat_dependant( header_params=dependant.header_params.copy(), cookie_params=dependant.cookie_params.copy(), body_params=dependant.body_params.copy(), - security_schemes=dependant.security_requirements.copy(), + security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) @@ -194,14 +209,23 @@ def get_flat_dependant( return flat_dependant +def _get_flat_fields_from_params(fields: List[ModelField]) -> List[ModelField]: + if not fields: + return fields + first_field = fields[0] + if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + return fields_to_extract + return fields + + def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) - return ( - flat_dependant.path_params - + flat_dependant.query_params - + flat_dependant.header_params - + flat_dependant.cookie_params - ) + path_params = _get_flat_fields_from_params(flat_dependant.path_params) + query_params = _get_flat_fields_from_params(flat_dependant.query_params) + header_params = _get_flat_fields_from_params(flat_dependant.header_params) + cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) + return path_params + query_params + header_params + cookie_params def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: @@ -258,16 +282,16 @@ def get_dependant( ) for param_name, param in signature_params.items(): is_path_param = param_name in path_param_names - type_annotation, depends, param_field = analyze_param( + param_details = analyze_param( param_name=param_name, annotation=param.annotation, value=param.default, is_path_param=is_path_param, ) - if depends is not None: + if param_details.depends is not None: sub_dependant = get_param_sub_dependant( param_name=param_name, - depends=depends, + depends=param_details.depends, path=path, security_scopes=security_scopes, ) @@ -275,18 +299,18 @@ def get_dependant( continue if add_non_field_param_to_dependency( param_name=param_name, - type_annotation=type_annotation, + type_annotation=param_details.type_annotation, dependant=dependant, ): assert ( - param_field is None + param_details.field is None ), f"Cannot specify multiple FastAPI annotations for {param_name!r}" continue - assert param_field is not None - if is_body_param(param_field=param_field, is_path_param=is_path_param): - dependant.body_params.append(param_field) + assert param_details.field is not None + if isinstance(param_details.field.field_info, params.Body): + dependant.body_params.append(param_details.field) else: - add_param_to_fields(field=param_field, dependant=dependant) + add_param_to_fields(field=param_details.field, dependant=dependant) return dependant @@ -314,13 +338,20 @@ def add_non_field_param_to_dependency( return None +@dataclass +class ParamDetails: + type_annotation: Any + depends: Optional[params.Depends] + field: Optional[ModelField] + + def analyze_param( *, param_name: str, annotation: Any, value: Any, is_path_param: bool, -) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]: +) -> ParamDetails: field_info = None depends = None type_annotation: Any = Any @@ -328,6 +359,7 @@ def analyze_param( if annotation is not inspect.Signature.empty: use_annotation = annotation type_annotation = annotation + # Extract Annotated info if get_origin(use_annotation) is Annotated: annotated_args = get_args(annotation) type_annotation = annotated_args[0] @@ -342,17 +374,20 @@ def analyze_param( if isinstance(arg, (params.Param, params.Body, params.Depends)) ] if fastapi_specific_annotations: - fastapi_annotation: Union[ - FieldInfo, params.Depends, None - ] = fastapi_specific_annotations[-1] + fastapi_annotation: Union[FieldInfo, params.Depends, None] = ( + fastapi_specific_annotations[-1] + ) else: fastapi_annotation = None + # Set default for Annotated FieldInfo if isinstance(fastapi_annotation, FieldInfo): # Copy `field_info` because we mutate `field_info.default` below. field_info = copy_field_info( field_info=fastapi_annotation, annotation=use_annotation ) - assert field_info.default is Undefined or field_info.default is Required, ( + assert ( + field_info.default is Undefined or field_info.default is RequiredParam + ), ( f"`{field_info.__class__.__name__}` default value cannot be set in" f" `Annotated` for {param_name!r}. Set the default value with `=` instead." ) @@ -360,10 +395,11 @@ def analyze_param( assert not is_path_param, "Path parameters cannot have default values" field_info.default = value else: - field_info.default = Required + field_info.default = RequiredParam + # Get Annotated Depends elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation - + # Get Depends from default value if isinstance(value, params.Depends): assert depends is None, ( "Cannot specify `Depends` in `Annotated` and default value" @@ -374,6 +410,7 @@ def analyze_param( f" default value together for {param_name!r}" ) depends = value + # Get FieldInfo from default value elif isinstance(value, FieldInfo): assert field_info is None, ( "Cannot specify FastAPI annotations in `Annotated` and default value" @@ -383,9 +420,13 @@ def analyze_param( if PYDANTIC_V2: field_info.annotation = type_annotation + # Get Depends from type annotation if depends is not None and depends.dependency is None: + # Copy `depends` before mutating it + depends = copy(depends) depends.dependency = type_annotation + # Handle non-param type annotations like Request if lenient_issubclass( type_annotation, ( @@ -401,10 +442,11 @@ def analyze_param( assert ( field_info is None ), f"Cannot specify FastAPI annotation for type {type_annotation!r}" + # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value elif field_info is None and depends is None: - default_value = value if value is not inspect.Signature.empty else Required + default_value = value if value is not inspect.Signature.empty else RequiredParam if is_path_param: - # We might check here that `default_value is Required`, but the fact is that the same + # We might check here that `default_value is RequiredParam`, but the fact is that the same # parameter might sometimes be a path parameter and sometimes not. See # `tests/test_infer_param_optionality.py` for an example. field_info = params.Path(annotation=use_annotation) @@ -418,7 +460,9 @@ def analyze_param( field_info = params.Query(annotation=use_annotation, default=default_value) field = None + # It's a field_info, not a dependency if field_info is not None: + # Handle field_info.in_ if is_path_param: assert isinstance(field_info, params.Path), ( f"Cannot use `{field_info.__class__.__name__}` for path param" @@ -434,40 +478,37 @@ def analyze_param( field_info, param_name, ) + if isinstance(field_info, params.Form): + ensure_multipart_is_installed() if not field_info.alias and getattr(field_info, "convert_underscores", None): alias = param_name.replace("_", "-") else: alias = field_info.alias or param_name field_info.alias = alias - field = create_response_field( + field = create_model_field( name=param_name, type_=use_annotation_from_field_info, default=field_info.default, alias=alias, - required=field_info.default in (Required, Undefined), + required=field_info.default in (RequiredParam, Undefined), field_info=field_info, ) + if is_path_param: + assert is_scalar_field( + field=field + ), "Path params must be of one of the supported types" + elif isinstance(field_info, params.Query): + assert ( + is_scalar_field(field) + or is_scalar_sequence_field(field) + or ( + lenient_issubclass(field.type_, BaseModel) + # For Pydantic v1 + and getattr(field, "shape", 1) == 1 + ) + ) - return type_annotation, depends, field - - -def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool: - if is_path_param: - assert is_scalar_field( - field=param_field - ), "Path params must be of one of the supported types" - return False - elif is_scalar_field(field=param_field): - return False - elif isinstance( - param_field.field_info, (params.Query, params.Header) - ) and is_scalar_sequence_field(param_field): - return False - else: - assert isinstance( - param_field.field_info, params.Body - ), f"Param: {param_field.name} can only be a request body, using Body()" - return True + return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: @@ -519,6 +560,15 @@ async def solve_generator( return await stack.enter_async_context(cm) +@dataclass +class SolvedDependency: + values: Dict[str, Any] + errors: List[Any] + background_tasks: Optional[StarletteBackgroundTasks] + response: Response + dependency_cache: Dict[Tuple[Callable[..., Any], Tuple[str]], Any] + + async def solve_dependencies( *, request: Union[Request, WebSocket], @@ -529,13 +579,8 @@ async def solve_dependencies( dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, -) -> Tuple[ - Dict[str, Any], - List[Any], - Optional[StarletteBackgroundTasks], - Response, - Dict[Tuple[Callable[..., Any], Tuple[str]], Any], -]: + embed_body_fields: bool, +) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: @@ -576,28 +621,23 @@ async def solve_dependencies( dependency_overrides_provider=dependency_overrides_provider, dependency_cache=dependency_cache, async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, ) - ( - sub_values, - sub_errors, - background_tasks, - _, # the subdependency returns the same response we have - sub_dependency_cache, - ) = solved_result - dependency_cache.update(sub_dependency_cache) - if sub_errors: - errors.extend(sub_errors) + background_tasks = solved_result.background_tasks + dependency_cache.update(solved_result.dependency_cache) + if solved_result.errors: + errors.extend(solved_result.errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( - call=call, stack=async_exit_stack, sub_values=sub_values + call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): - solved = await call(**sub_values) + solved = await call(**solved_result.values) else: - solved = await run_in_threadpool(call, **sub_values) + solved = await run_in_threadpool(call, **solved_result.values) if sub_dependant.name is not None: values[sub_dependant.name] = solved if sub_dependant.cache_key not in dependency_cache: @@ -624,7 +664,9 @@ async def solve_dependencies( body_values, body_errors, ) = await request_body_to_args( # body_params checked above - required_params=dependant.body_params, received_body=body + body_fields=dependant.body_params, + received_body=body, + embed_body_fields=embed_body_fields, ) values.update(body_values) errors.extend(body_errors) @@ -644,142 +686,257 @@ async def solve_dependencies( values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.security_scopes ) - return values, errors, background_tasks, response, dependency_cache + return SolvedDependency( + values=values, + errors=errors, + background_tasks=background_tasks, + response=response, + dependency_cache=dependency_cache, + ) + + +def _validate_value_with_model_field( + *, field: ModelField, value: Any, values: Dict[str, Any], loc: Tuple[str, ...] +) -> Tuple[Any, List[Any]]: + if value is None: + if field.required: + return None, [get_missing_field_error(loc=loc)] + else: + return deepcopy(field.default), [] + v_, errors_ = field.validate(value, values, loc=loc) + if isinstance(errors_, ErrorWrapper): + return None, [errors_] + elif isinstance(errors_, list): + new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=()) + return None, new_errors + else: + return v_, [] + + +def _get_multidict_value( + field: ModelField, values: Mapping[str, Any], alias: Union[str, None] = None +) -> Any: + alias = alias or field.alias + if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): + value = values.getlist(alias) + else: + value = values.get(alias, None) + if ( + value is None + or ( + isinstance(field.field_info, params.Form) + and isinstance(value, str) # For type checks + and value == "" + ) + or (is_sequence_field(field) and len(value) == 0) + ): + if field.required: + return + else: + return deepcopy(field.default) + return value def request_params_to_args( - required_params: Sequence[ModelField], + fields: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[Any]]: - values = {} - errors = [] - for field in required_params: - if is_scalar_sequence_field(field) and isinstance( - received_params, (QueryParams, Headers) - ): - value = received_params.getlist(field.alias) or field.default - else: - value = received_params.get(field.alias) + values: Dict[str, Any] = {} + errors: List[Dict[str, Any]] = [] + + if not fields: + return values, errors + + first_field = fields[0] + fields_to_extract = fields + single_not_embedded_field = False + if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + single_not_embedded_field = True + + params_to_process: Dict[str, Any] = {} + + processed_keys = set() + + for field in fields_to_extract: + alias = None + if isinstance(received_params, Headers): + # Handle fields extracted from a Pydantic Model for a header, each field + # doesn't have a FieldInfo of type Header with the default convert_underscores=True + convert_underscores = getattr(field.field_info, "convert_underscores", True) + if convert_underscores: + alias = ( + field.alias + if field.alias != field.name + else field.name.replace("_", "-") + ) + value = _get_multidict_value(field, received_params, alias=alias) + if value is not None: + params_to_process[field.name] = value + processed_keys.add(alias or field.alias) + processed_keys.add(field.name) + + for key, value in received_params.items(): + if key not in processed_keys: + params_to_process[key] = value + + if single_not_embedded_field: + field_info = first_field.field_info + assert isinstance( + field_info, params.Param + ), "Params must be subclasses of Param" + loc: Tuple[str, ...] = (field_info.in_.value,) + v_, errors_ = _validate_value_with_model_field( + field=first_field, value=params_to_process, values=values, loc=loc + ) + return {first_field.name: v_}, errors_ + + for field in fields: + value = _get_multidict_value(field, received_params) field_info = field.field_info assert isinstance( field_info, params.Param ), "Params must be subclasses of Param" loc = (field_info.in_.value, field.alias) - if value is None: - if field.required: - errors.append(get_missing_field_error(loc=loc)) - else: - values[field.name] = deepcopy(field.default) - continue - v_, errors_ = field.validate(value, values, loc=loc) - if isinstance(errors_, ErrorWrapper): - errors.append(errors_) - elif isinstance(errors_, list): - new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=()) - errors.extend(new_errors) + v_, errors_ = _validate_value_with_model_field( + field=field, value=value, values=values, loc=loc + ) + if errors_: + errors.extend(errors_) else: values[field.name] = v_ return values, errors +def _should_embed_body_fields(fields: List[ModelField]) -> bool: + if not fields: + return False + # More than one dependency could have the same field, it would show up as multiple + # fields but it's the same one, so count them by name + body_param_names_set = {field.name for field in fields} + # A top level field has to be a single field, not multiple + if len(body_param_names_set) > 1: + return True + first_field = fields[0] + # If it explicitly specifies it is embedded, it has to be embedded + if getattr(first_field.field_info, "embed", None): + return True + # If it's a Form (or File) field, it has to be a BaseModel to be top level + # otherwise it has to be embedded, so that the key value pair can be extracted + if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( + first_field.type_, BaseModel + ): + return True + return False + + +async def _extract_form_body( + body_fields: List[ModelField], + received_body: FormData, +) -> Dict[str, Any]: + values = {} + first_field = body_fields[0] + first_field_info = first_field.field_info + + for field in body_fields: + value = _get_multidict_value(field, received_body) + if ( + isinstance(first_field_info, params.File) + and is_bytes_field(field) + and isinstance(value, UploadFile) + ): + value = await value.read() + elif ( + is_bytes_sequence_field(field) + and isinstance(first_field_info, params.File) + and value_is_sequence(value) + ): + # For types + assert isinstance(value, sequence_types) # type: ignore[arg-type] + results: List[Union[bytes, str]] = [] + + async def process_fn( + fn: Callable[[], Coroutine[Any, Any, Any]], + ) -> None: + result = await fn() + results.append(result) # noqa: B023 + + async with anyio.create_task_group() as tg: + for sub_value in value: + tg.start_soon(process_fn, sub_value.read) + value = serialize_sequence_value(field=field, value=results) + if value is not None: + values[field.alias] = value + for key, value in received_body.items(): + if key not in values: + values[key] = value + return values + + async def request_body_to_args( - required_params: List[ModelField], + body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], + embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: - values = {} + values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] - if required_params: - field = required_params[0] - field_info = field.field_info - embed = getattr(field_info, "embed", None) - field_alias_omitted = len(required_params) == 1 and not embed - if field_alias_omitted: - received_body = {field.alias: received_body} - - for field in required_params: - loc: Tuple[str, ...] - if field_alias_omitted: - loc = ("body",) - else: - loc = ("body", field.alias) - - value: Optional[Any] = None - if received_body is not None: - if (is_sequence_field(field)) and isinstance(received_body, FormData): - value = received_body.getlist(field.alias) - else: - try: - value = received_body.get(field.alias) - except AttributeError: - errors.append(get_missing_field_error(loc)) - continue - if ( - value is None - or (isinstance(field_info, params.Form) and value == "") - or ( - isinstance(field_info, params.Form) - and is_sequence_field(field) - and len(value) == 0 - ) - ): - if field.required: - errors.append(get_missing_field_error(loc)) - else: - values[field.name] = deepcopy(field.default) + assert body_fields, "request_body_to_args() should be called with fields" + single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields + first_field = body_fields[0] + body_to_process = received_body + + fields_to_extract: List[ModelField] = body_fields + + if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + + if isinstance(received_body, FormData): + body_to_process = await _extract_form_body(fields_to_extract, received_body) + + if single_not_embedded_field: + loc: Tuple[str, ...] = ("body",) + v_, errors_ = _validate_value_with_model_field( + field=first_field, value=body_to_process, values=values, loc=loc + ) + return {first_field.name: v_}, errors_ + for field in body_fields: + loc = ("body", field.alias) + value: Optional[Any] = None + if body_to_process is not None: + try: + value = body_to_process.get(field.alias) + # If the received body is a list, not a dict + except AttributeError: + errors.append(get_missing_field_error(loc)) continue - if ( - isinstance(field_info, params.File) - and is_bytes_field(field) - and isinstance(value, UploadFile) - ): - value = await value.read() - elif ( - is_bytes_sequence_field(field) - and isinstance(field_info, params.File) - and value_is_sequence(value) - ): - # For types - assert isinstance(value, sequence_types) # type: ignore[arg-type] - results: List[Union[bytes, str]] = [] - - async def process_fn( - fn: Callable[[], Coroutine[Any, Any, Any]], - ) -> None: - result = await fn() - results.append(result) # noqa: B023 - - async with anyio.create_task_group() as tg: - for sub_value in value: - tg.start_soon(process_fn, sub_value.read) - value = serialize_sequence_value(field=field, value=results) - - v_, errors_ = field.validate(value, values, loc=loc) - - if isinstance(errors_, list): - errors.extend(errors_) - elif errors_: - errors.append(errors_) - else: - values[field.name] = v_ + v_, errors_ = _validate_value_with_model_field( + field=field, value=value, values=values, loc=loc + ) + if errors_: + errors.extend(errors_) + else: + values[field.name] = v_ return values, errors -def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: - flat_dependant = get_flat_dependant(dependant) +def get_body_field( + *, flat_dependant: Dependant, name: str, embed_body_fields: bool +) -> Optional[ModelField]: + """ + Get a ModelField representing the request body for a path operation, combining + all body parameters into a single field if necessary. + + Used to check if it's form data (with `isinstance(body_field, params.Form)`) + or JSON and to generate the JSON Schema for a request body. + + This is **not** used to validate/parse the request body, that's done with each + individual body parameter. + """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] - field_info = first_param.field_info - embed = getattr(field_info, "embed", None) - body_param_names_set = {param.name for param in flat_dependant.body_params} - if len(body_param_names_set) == 1 and not embed: - check_file_field(first_param) + if not embed_body_fields: return first_param - # If one field requires to embed, all have to be embedded - # in case a sub-dependency is evaluated with a single unique body field - # That is combined (embedded) with other body fields - for param in flat_dependant.body_params: - setattr(param.field_info, "embed", True) # noqa: B010 model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name @@ -805,12 +962,11 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] - final_field = create_response_field( + final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) - check_file_field(final_field) return final_field diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 431387f71..451ea0760 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -22,9 +22,9 @@ from pydantic import BaseModel from pydantic.color import Color from pydantic.networks import AnyUrl, NameEmail from pydantic.types import SecretBytes, SecretStr -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc -from ._compat import PYDANTIC_V2, Url, _model_dump +from ._compat import PYDANTIC_V2, UndefinedType, Url, _model_dump # Taken from Pydantic v1 as is @@ -259,6 +259,8 @@ def jsonable_encoder( return str(obj) if isinstance(obj, (str, int, float, type(None))): return obj + if isinstance(obj, UndefinedType): + return None if isinstance(obj, dict): encoded_dict = {} allowed_keys = set(obj.keys()) diff --git a/fastapi/exceptions.py b/fastapi/exceptions.py index 680d288e4..44d4ada86 100644 --- a/fastapi/exceptions.py +++ b/fastapi/exceptions.py @@ -3,7 +3,7 @@ from typing import Any, Dict, Optional, Sequence, Type, Union from pydantic import BaseModel, create_model from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import WebSocketException as StarletteWebSocketException -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class HTTPException(StarletteHTTPException): diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py index 69473d19c..c2ec358d2 100644 --- a/fastapi/openapi/docs.py +++ b/fastapi/openapi/docs.py @@ -3,7 +3,7 @@ from typing import Any, Dict, Optional from fastapi.encoders import jsonable_encoder from starlette.responses import HTMLResponse -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc swagger_ui_default_parameters: Annotated[ Dict[str, Any], @@ -53,7 +53,7 @@ def get_swagger_ui_html( It is normally set to a CDN URL. """ ), - ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js", + ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js", swagger_css_url: Annotated[ str, Doc( @@ -63,7 +63,7 @@ def get_swagger_ui_html( It is normally set to a CDN URL. """ ), - ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css", + ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css", swagger_favicon_url: Annotated[ str, Doc( diff --git a/fastapi/openapi/models.py b/fastapi/openapi/models.py index 5f3bdbb20..ed07b40f5 100644 --- a/fastapi/openapi/models.py +++ b/fastapi/openapi/models.py @@ -55,11 +55,7 @@ except ImportError: # pragma: no cover return with_info_plain_validator_function(cls._validate) -class Contact(BaseModel): - name: Optional[str] = None - url: Optional[AnyUrl] = None - email: Optional[EmailStr] = None - +class BaseModelWithConfig(BaseModel): if PYDANTIC_V2: model_config = {"extra": "allow"} @@ -69,21 +65,19 @@ class Contact(BaseModel): extra = "allow" -class License(BaseModel): - name: str - identifier: Optional[str] = None +class Contact(BaseModelWithConfig): + name: Optional[str] = None url: Optional[AnyUrl] = None + email: Optional[EmailStr] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" +class License(BaseModelWithConfig): + name: str + identifier: Optional[str] = None + url: Optional[AnyUrl] = None -class Info(BaseModel): +class Info(BaseModelWithConfig): title: str summary: Optional[str] = None description: Optional[str] = None @@ -92,42 +86,18 @@ class Info(BaseModel): license: Optional[License] = None version: str - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class ServerVariable(BaseModel): +class ServerVariable(BaseModelWithConfig): enum: Annotated[Optional[List[str]], Field(min_length=1)] = None default: str description: Optional[str] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class Server(BaseModel): +class Server(BaseModelWithConfig): url: Union[AnyUrl, str] description: Optional[str] = None variables: Optional[Dict[str, ServerVariable]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class Reference(BaseModel): ref: str = Field(alias="$ref") @@ -138,36 +108,20 @@ class Discriminator(BaseModel): mapping: Optional[Dict[str, str]] = None -class XML(BaseModel): +class XML(BaseModelWithConfig): name: Optional[str] = None namespace: Optional[str] = None prefix: Optional[str] = None attribute: Optional[bool] = None wrapped: Optional[bool] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class ExternalDocumentation(BaseModel): +class ExternalDocumentation(BaseModelWithConfig): description: Optional[str] = None url: AnyUrl - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Schema(BaseModel): +class Schema(BaseModelWithConfig): # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu # Core Vocabulary schema_: Optional[str] = Field(default=None, alias="$schema") @@ -253,14 +207,6 @@ class Schema(BaseModel): ), ] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - # Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents # A JSON Schema MUST be an object or a boolean. @@ -289,38 +235,22 @@ class ParameterInType(Enum): cookie = "cookie" -class Encoding(BaseModel): +class Encoding(BaseModelWithConfig): contentType: Optional[str] = None headers: Optional[Dict[str, Union["Header", Reference]]] = None style: Optional[str] = None explode: Optional[bool] = None allowReserved: Optional[bool] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class MediaType(BaseModel): +class MediaType(BaseModelWithConfig): schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") example: Optional[Any] = None examples: Optional[Dict[str, Union[Example, Reference]]] = None encoding: Optional[Dict[str, Encoding]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class ParameterBase(BaseModel): +class ParameterBase(BaseModelWithConfig): description: Optional[str] = None required: Optional[bool] = None deprecated: Optional[bool] = None @@ -334,14 +264,6 @@ class ParameterBase(BaseModel): # Serialization rules for more complex scenarios content: Optional[Dict[str, MediaType]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class Parameter(ParameterBase): name: str @@ -352,21 +274,13 @@ class Header(ParameterBase): pass -class RequestBody(BaseModel): +class RequestBody(BaseModelWithConfig): description: Optional[str] = None content: Dict[str, MediaType] required: Optional[bool] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class Link(BaseModel): +class Link(BaseModelWithConfig): operationRef: Optional[str] = None operationId: Optional[str] = None parameters: Optional[Dict[str, Union[Any, str]]] = None @@ -374,31 +288,15 @@ class Link(BaseModel): description: Optional[str] = None server: Optional[Server] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Response(BaseModel): +class Response(BaseModelWithConfig): description: str headers: Optional[Dict[str, Union[Header, Reference]]] = None content: Optional[Dict[str, MediaType]] = None links: Optional[Dict[str, Union[Link, Reference]]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Operation(BaseModel): +class Operation(BaseModelWithConfig): tags: Optional[List[str]] = None summary: Optional[str] = None description: Optional[str] = None @@ -413,16 +311,8 @@ class Operation(BaseModel): security: Optional[List[Dict[str, List[str]]]] = None servers: Optional[List[Server]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class PathItem(BaseModel): +class PathItem(BaseModelWithConfig): ref: Optional[str] = Field(default=None, alias="$ref") summary: Optional[str] = None description: Optional[str] = None @@ -437,14 +327,6 @@ class PathItem(BaseModel): servers: Optional[List[Server]] = None parameters: Optional[List[Union[Parameter, Reference]]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class SecuritySchemeType(Enum): apiKey = "apiKey" @@ -453,18 +335,10 @@ class SecuritySchemeType(Enum): openIdConnect = "openIdConnect" -class SecurityBase(BaseModel): +class SecurityBase(BaseModelWithConfig): type_: SecuritySchemeType = Field(alias="type") description: Optional[str] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class APIKeyIn(Enum): query = "query" @@ -488,18 +362,10 @@ class HTTPBearer(HTTPBase): bearerFormat: Optional[str] = None -class OAuthFlow(BaseModel): +class OAuthFlow(BaseModelWithConfig): refreshUrl: Optional[str] = None scopes: Dict[str, str] = {} - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class OAuthFlowImplicit(OAuthFlow): authorizationUrl: str @@ -518,20 +384,12 @@ class OAuthFlowAuthorizationCode(OAuthFlow): tokenUrl: str -class OAuthFlows(BaseModel): +class OAuthFlows(BaseModelWithConfig): implicit: Optional[OAuthFlowImplicit] = None password: Optional[OAuthFlowPassword] = None clientCredentials: Optional[OAuthFlowClientCredentials] = None authorizationCode: Optional[OAuthFlowAuthorizationCode] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class OAuth2(SecurityBase): type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias="type") @@ -548,7 +406,7 @@ class OpenIdConnect(SecurityBase): SecurityScheme = Union[APIKey, HTTPBase, OAuth2, OpenIdConnect, HTTPBearer] -class Components(BaseModel): +class Components(BaseModelWithConfig): schemas: Optional[Dict[str, Union[Schema, Reference]]] = None responses: Optional[Dict[str, Union[Response, Reference]]] = None parameters: Optional[Dict[str, Union[Parameter, Reference]]] = None @@ -561,30 +419,14 @@ class Components(BaseModel): callbacks: Optional[Dict[str, Union[Dict[str, PathItem], Reference, Any]]] = None pathItems: Optional[Dict[str, Union[PathItem, Reference]]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Tag(BaseModel): +class Tag(BaseModelWithConfig): name: str description: Optional[str] = None externalDocs: Optional[ExternalDocumentation] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class OpenAPI(BaseModel): +class OpenAPI(BaseModelWithConfig): openapi: str info: Info jsonSchemaDialect: Optional[str] = None @@ -597,14 +439,6 @@ class OpenAPI(BaseModel): tags: Optional[List[Tag]] = None externalDocs: Optional[ExternalDocumentation] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - _model_rebuild(Schema) _model_rebuild(Operation) diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 5bfb5acef..947eca948 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -16,11 +16,15 @@ from fastapi._compat import ( ) from fastapi.datastructures import DefaultPlaceholder from fastapi.dependencies.models import Dependant -from fastapi.dependencies.utils import get_flat_dependant, get_flat_params +from fastapi.dependencies.utils import ( + _get_flat_fields_from_params, + get_flat_dependant, + get_flat_params, +) from fastapi.encoders import jsonable_encoder from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX, REF_TEMPLATE from fastapi.openapi.models import OpenAPI -from fastapi.params import Body, Param +from fastapi.params import Body, ParamTypes from fastapi.responses import Response from fastapi.types import ModelNameMap from fastapi.utils import ( @@ -87,9 +91,9 @@ def get_openapi_security_definitions( return security_definitions, operation_security -def get_openapi_operation_parameters( +def _get_openapi_operation_parameters( *, - all_route_params: Sequence[ModelField], + dependant: Dependant, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ @@ -98,33 +102,47 @@ def get_openapi_operation_parameters( separate_input_output_schemas: bool = True, ) -> List[Dict[str, Any]]: parameters = [] - for param in all_route_params: - field_info = param.field_info - field_info = cast(Param, field_info) - if not field_info.include_in_schema: - continue - param_schema = get_schema_from_model_field( - field=param, - schema_generator=schema_generator, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - parameter = { - "name": param.alias, - "in": field_info.in_.value, - "required": param.required, - "schema": param_schema, - } - if field_info.description: - parameter["description"] = field_info.description - if field_info.openapi_examples: - parameter["examples"] = jsonable_encoder(field_info.openapi_examples) - elif field_info.example != Undefined: - parameter["example"] = jsonable_encoder(field_info.example) - if field_info.deprecated: - parameter["deprecated"] = field_info.deprecated - parameters.append(parameter) + flat_dependant = get_flat_dependant(dependant, skip_repeats=True) + path_params = _get_flat_fields_from_params(flat_dependant.path_params) + query_params = _get_flat_fields_from_params(flat_dependant.query_params) + header_params = _get_flat_fields_from_params(flat_dependant.header_params) + cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) + parameter_groups = [ + (ParamTypes.path, path_params), + (ParamTypes.query, query_params), + (ParamTypes.header, header_params), + (ParamTypes.cookie, cookie_params), + ] + for param_type, param_group in parameter_groups: + for param in param_group: + field_info = param.field_info + # field_info = cast(Param, field_info) + if not getattr(field_info, "include_in_schema", True): + continue + param_schema = get_schema_from_model_field( + field=param, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + parameter = { + "name": param.alias, + "in": param_type.value, + "required": param.required, + "schema": param_schema, + } + if field_info.description: + parameter["description"] = field_info.description + openapi_examples = getattr(field_info, "openapi_examples", None) + example = getattr(field_info, "example", None) + if openapi_examples: + parameter["examples"] = jsonable_encoder(openapi_examples) + elif example != Undefined: + parameter["example"] = jsonable_encoder(example) + if getattr(field_info, "deprecated", None): + parameter["deprecated"] = True + parameters.append(parameter) return parameters @@ -247,9 +265,8 @@ def get_openapi_path( operation.setdefault("security", []).extend(operation_security) if security_definitions: security_schemes.update(security_definitions) - all_route_params = get_flat_params(route.dependant) - operation_parameters = get_openapi_operation_parameters( - all_route_params=all_route_params, + operation_parameters = _get_openapi_operation_parameters( + dependant=route.dependant, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, @@ -379,6 +396,7 @@ def get_openapi_path( deep_dict_update(openapi_response, process_response) openapi_response["description"] = description http422 = str(HTTP_422_UNPROCESSABLE_ENTITY) + all_route_params = get_flat_params(route.dependant) if (all_route_params or route.body_field) and not any( status in operation["responses"] for status in [http422, "4XX", "default"] diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py index 3f6dbc959..b3621626c 100644 --- a/fastapi/param_functions.py +++ b/fastapi/param_functions.py @@ -3,7 +3,7 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Union from fastapi import params from fastapi._compat import Undefined from fastapi.openapi.models import Example -from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, deprecated _Unset: Any = Undefined @@ -240,7 +240,7 @@ def Path( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -565,7 +565,7 @@ def Query( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -880,7 +880,7 @@ def Header( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -1185,7 +1185,7 @@ def Cookie( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -1282,7 +1282,7 @@ def Body( # noqa: N802 ), ] = _Unset, embed: Annotated[ - bool, + Union[bool, None], Doc( """ When `embed` is `True`, the parameter will be expected in a JSON body as a @@ -1294,7 +1294,7 @@ def Body( # noqa: N802 [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). """ ), - ] = False, + ] = None, media_type: Annotated[ str, Doc( @@ -1512,7 +1512,7 @@ def Body( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -1827,7 +1827,7 @@ def Form( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -2141,7 +2141,7 @@ def File( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -2298,7 +2298,7 @@ def Security( # noqa: N802 dependency. The term "scope" comes from the OAuth2 specification, it seems to be - intentionaly vague and interpretable. It normally refers to permissions, + intentionally vague and interpretable. It normally refers to permissions, in cases to roles. These scopes are integrated with OpenAPI (and the API docs at `/docs`). @@ -2343,7 +2343,7 @@ def Security( # noqa: N802 ```python from typing import Annotated - from fastapi import Depends, FastAPI + from fastapi import Security, FastAPI from .db import User from .security import get_current_active_user diff --git a/fastapi/params.py b/fastapi/params.py index b40944dba..90ca7cb01 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -6,7 +6,7 @@ from fastapi.openapi.models import Example from pydantic.fields import FieldInfo from typing_extensions import Annotated, deprecated -from ._compat import PYDANTIC_V2, Undefined +from ._compat import PYDANTIC_V2, PYDANTIC_VERSION, Undefined _Unset: Any = Undefined @@ -63,12 +63,11 @@ class Param(FieldInfo): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): - self.deprecated = deprecated if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", @@ -92,7 +91,7 @@ class Param(FieldInfo): max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, - allow_nan=allow_inf_nan, + allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, @@ -106,6 +105,10 @@ class Param(FieldInfo): stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra + if PYDANTIC_VERSION < "2.7.0": + self.deprecated = deprecated + else: + kwargs["deprecated"] = deprecated if PYDANTIC_V2: kwargs.update( { @@ -174,7 +177,7 @@ class Path(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -260,7 +263,7 @@ class Query(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -345,7 +348,7 @@ class Header(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -430,7 +433,7 @@ class Cookie(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -476,7 +479,7 @@ class Body(FieldInfo): *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, - embed: bool = False, + embed: Union[bool, None] = None, media_type: str = "application/json", alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, @@ -514,14 +517,13 @@ class Body(FieldInfo): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): self.embed = embed self.media_type = media_type - self.deprecated = deprecated if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", @@ -545,7 +547,7 @@ class Body(FieldInfo): max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, - allow_nan=allow_inf_nan, + allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, @@ -554,11 +556,15 @@ class Body(FieldInfo): kwargs["examples"] = examples if regex is not None: warnings.warn( - "`regex` has been depreacated, please use `pattern` instead", + "`regex` has been deprecated, please use `pattern` instead", category=DeprecationWarning, stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra + if PYDANTIC_VERSION < "2.7.0": + self.deprecated = deprecated + else: + kwargs["deprecated"] = deprecated if PYDANTIC_V2: kwargs.update( { @@ -627,7 +633,7 @@ class Form(Body): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -636,7 +642,6 @@ class Form(Body): default=default, default_factory=default_factory, annotation=annotation, - embed=True, media_type=media_type, alias=alias, alias_priority=alias_priority, @@ -712,7 +717,7 @@ class File(Form): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, diff --git a/fastapi/routing.py b/fastapi/routing.py index 23a32d15f..8ea4bb219 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -3,14 +3,16 @@ import dataclasses import email.message import inspect import json -from contextlib import AsyncExitStack +from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, + AsyncIterator, Callable, Coroutine, Dict, List, + Mapping, Optional, Sequence, Set, @@ -31,8 +33,10 @@ from fastapi._compat import ( from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( + _should_embed_body_fields, get_body_field, get_dependant, + get_flat_dependant, get_parameterless_sub_dependant, get_typed_return_annotation, solve_dependencies, @@ -47,7 +51,7 @@ from fastapi.exceptions import ( from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import ( create_cloned_field, - create_response_field, + create_model_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, @@ -67,9 +71,9 @@ from starlette.routing import ( websocket_session, ) from starlette.routing import Mount as Mount # noqa -from starlette.types import ASGIApp, Lifespan, Scope +from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket -from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( @@ -119,6 +123,23 @@ def _prepare_response_content( return res +def _merge_lifespan_context( + original_context: Lifespan[Any], nested_context: Lifespan[Any] +) -> Lifespan[Any]: + @asynccontextmanager + async def merged_lifespan( + app: AppType, + ) -> AsyncIterator[Optional[Mapping[str, Any]]]: + async with original_context(app) as maybe_original_state: + async with nested_context(app) as maybe_nested_state: + if maybe_nested_state is None and maybe_original_state is None: + yield None # old ASGI compatibility + else: + yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} + + return merged_lifespan # type: ignore[return-value] + + async def serialize_response( *, field: Optional[ModelField] = None, @@ -206,6 +227,7 @@ def get_request_handler( response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, dependency_overrides_provider: Optional[Any] = None, + embed_body_fields: bool = False, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) @@ -272,27 +294,36 @@ def get_request_handler( body=body, dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, ) - values, errors, background_tasks, sub_response, _ = solved_result + errors = solved_result.errors if not errors: raw_response = await run_endpoint_function( - dependant=dependant, values=values, is_coroutine=is_coroutine + dependant=dependant, + values=solved_result.values, + is_coroutine=is_coroutine, ) if isinstance(raw_response, Response): if raw_response.background is None: - raw_response.background = background_tasks + raw_response.background = solved_result.background_tasks response = raw_response else: - response_args: Dict[str, Any] = {"background": background_tasks} + response_args: Dict[str, Any] = { + "background": solved_result.background_tasks + } # If status_code was set, use it, otherwise use the default from the # response class, in the case of redirect it's 307 current_status_code = ( - status_code if status_code else sub_response.status_code + status_code + if status_code + else solved_result.response.status_code ) if current_status_code is not None: response_args["status_code"] = current_status_code - if sub_response.status_code: - response_args["status_code"] = sub_response.status_code + if solved_result.response.status_code: + response_args["status_code"] = ( + solved_result.response.status_code + ) content = await serialize_response( field=response_field, response_content=raw_response, @@ -307,7 +338,7 @@ def get_request_handler( response = actual_response_class(content, **response_args) if not is_body_allowed_for_status_code(response.status_code): response.body = b"" - response.headers.raw.extend(sub_response.headers.raw) + response.headers.raw.extend(solved_result.response.headers.raw) if errors: validation_error = RequestValidationError( _normalize_errors(errors), body=body @@ -327,7 +358,9 @@ def get_request_handler( def get_websocket_app( - dependant: Dependant, dependency_overrides_provider: Optional[Any] = None + dependant: Dependant, + dependency_overrides_provider: Optional[Any] = None, + embed_body_fields: bool = False, ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: async with AsyncExitStack() as async_exit_stack: @@ -340,12 +373,14 @@ def get_websocket_app( dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, ) - values, errors, _, _2, _3 = solved_result - if errors: - raise WebSocketRequestValidationError(_normalize_errors(errors)) + if solved_result.errors: + raise WebSocketRequestValidationError( + _normalize_errors(solved_result.errors) + ) assert dependant.call is not None, "dependant.call must be a function" - await dependant.call(**values) + await dependant.call(**solved_result.values) return app @@ -371,11 +406,15 @@ class APIWebSocketRoute(routing.WebSocketRoute): 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) - + self._flat_dependant = get_flat_dependant(self.dependant) + self._embed_body_fields = _should_embed_body_fields( + self._flat_dependant.body_params + ) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, + embed_body_fields=self._embed_body_fields, ) ) @@ -454,9 +493,9 @@ class APIRoute(routing.Route): methods = ["GET"] self.methods: Set[str] = {method.upper() for method in methods} if isinstance(generate_unique_id_function, DefaultPlaceholder): - current_generate_unique_id: Callable[ - ["APIRoute"], str - ] = generate_unique_id_function.value + current_generate_unique_id: Callable[[APIRoute], str] = ( + generate_unique_id_function.value + ) else: current_generate_unique_id = generate_unique_id_function self.unique_id = self.operation_id or current_generate_unique_id(self) @@ -469,7 +508,7 @@ class APIRoute(routing.Route): status_code ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id - self.response_field = create_response_field( + self.response_field = create_model_field( name=response_name, type_=self.response_model, mode="serialization", @@ -482,9 +521,9 @@ class APIRoute(routing.Route): # By being a new field, no inheritance will be passed as is. A new model # will always be created. # TODO: remove when deprecating Pydantic v1 - self.secure_cloned_response_field: Optional[ - ModelField - ] = create_cloned_field(self.response_field) + self.secure_cloned_response_field: Optional[ModelField] = ( + create_cloned_field(self.response_field) + ) else: self.response_field = None # type: ignore self.secure_cloned_response_field = None @@ -502,7 +541,9 @@ class APIRoute(routing.Route): additional_status_code ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" - response_field = create_response_field(name=response_name, type_=model) + response_field = create_model_field( + name=response_name, type_=model, mode="serialization" + ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields @@ -516,7 +557,15 @@ class APIRoute(routing.Route): 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) - self.body_field = get_body_field(dependant=self.dependant, name=self.unique_id) + self._flat_dependant = get_flat_dependant(self.dependant) + self._embed_body_fields = _should_embed_body_fields( + self._flat_dependant.body_params + ) + self.body_field = get_body_field( + flat_dependant=self._flat_dependant, + name=self.unique_id, + embed_body_fields=self._embed_body_fields, + ) self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: @@ -533,6 +582,7 @@ class APIRoute(routing.Route): response_model_exclude_defaults=self.response_model_exclude_defaults, response_model_exclude_none=self.response_model_exclude_none, dependency_overrides_provider=self.dependency_overrides_provider, + embed_body_fields=self._embed_body_fields, ) def matches(self, scope: Scope) -> Tuple[Match, Scope]: @@ -1308,6 +1358,10 @@ class APIRouter(routing.Router): self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) + self.lifespan_context = _merge_lifespan_context( + self.lifespan_context, + router.lifespan_context, + ) def get( self, diff --git a/fastapi/security/api_key.py b/fastapi/security/api_key.py index b1a6b4f94..d68bdb037 100644 --- a/fastapi/security/api_key.py +++ b/fastapi/security/api_key.py @@ -5,7 +5,7 @@ from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class APIKeyBase(SecurityBase): @@ -76,7 +76,7 @@ class APIKeyQuery(APIKeyBase): Doc( """ By default, if the query parameter is not provided, `APIKeyQuery` will - automatically cancel the request and sebd the client an error. + automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the query parameter is not available, instead of erroring out, the dependency result will be diff --git a/fastapi/security/http.py b/fastapi/security/http.py index 738455de3..e06f3d66d 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -10,12 +10,12 @@ from fastapi.security.utils import get_authorization_scheme_param from pydantic import BaseModel from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class HTTPBasicCredentials(BaseModel): """ - The HTTP Basic credendials given as the result of using `HTTPBasic` in a + The HTTP Basic credentials given as the result of using `HTTPBasic` in a dependency. Read more about it in the @@ -277,7 +277,7 @@ class HTTPBearer(HTTPBase): bool, Doc( """ - By default, if the HTTP Bearer token not provided (in an + By default, if the HTTP Bearer token is not provided (in an `Authorization` header), `HTTPBearer` will automatically cancel the request and send the client an error. @@ -380,7 +380,7 @@ class HTTPDigest(HTTPBase): bool, Doc( """ - By default, if the HTTP Digest not provided, `HTTPDigest` will + By default, if the HTTP Digest is not provided, `HTTPDigest` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Digest is not diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index d7ba44bce..6adc55bfe 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -10,7 +10,7 @@ from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN # TODO: import from typing when deprecating Python 3.9 -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class OAuth2PasswordRequestForm: @@ -52,7 +52,7 @@ class OAuth2PasswordRequestForm: ``` Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. - You could have custom internal logic to separate it by colon caracters (`:`) or + You could have custom internal logic to separate it by colon characters (`:`) or similar, and get the two parts `items` and `read`. Many applications do that to group and organize permissions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification. @@ -194,7 +194,7 @@ class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): ``` Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. - You could have custom internal logic to separate it by colon caracters (`:`) or + You could have custom internal logic to separate it by colon characters (`:`) or similar, and get the two parts `items` and `read`. Many applications do that to group and organize permissions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification. diff --git a/fastapi/security/open_id_connect_url.py b/fastapi/security/open_id_connect_url.py index 1d255877d..c8cceb911 100644 --- a/fastapi/security/open_id_connect_url.py +++ b/fastapi/security/open_id_connect_url.py @@ -5,7 +5,7 @@ from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class OpenIdConnect(SecurityBase): diff --git a/fastapi/utils.py b/fastapi/utils.py index 53b2fa0c3..4c7350fea 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -34,9 +34,9 @@ if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` -_CLONED_TYPES_CACHE: MutableMapping[ - Type[BaseModel], Type[BaseModel] -] = WeakKeyDictionary() +_CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( + WeakKeyDictionary() +) def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: @@ -60,9 +60,9 @@ def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) -def create_response_field( +def create_model_field( name: str, - type_: Type[Any], + type_: Any, class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = Undefined, required: Union[bool, UndefinedType] = Undefined, @@ -71,9 +71,6 @@ def create_response_field( alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: - """ - Create a new response field. Raises if type_ is invalid. - """ class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( @@ -135,7 +132,7 @@ def create_cloned_field( use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) - new_field = create_response_field(name=field.name, type_=use_type) + new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] @@ -221,9 +218,3 @@ def get_value_or_default( if not isinstance(item, DefaultPlaceholder): return item return first_item - - -def match_pydantic_error_url(error_type: str) -> Any: - from dirty_equals import IsStr - - return IsStr(regex=rf"^https://errors\.pydantic\.dev/.*/v/{error_type}") diff --git a/pdm_build.py b/pdm_build.py new file mode 100644 index 000000000..c83222b33 --- /dev/null +++ b/pdm_build.py @@ -0,0 +1,20 @@ +import os +from typing import Any, Dict + +from pdm.backend.hooks import Context + +TIANGOLO_BUILD_PACKAGE = os.getenv("TIANGOLO_BUILD_PACKAGE", "fastapi") + + +def pdm_build_initialize(context: Context) -> None: + metadata = context.config.metadata + # Get custom config for the current package, from the env var + config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][ + "_internal-slim-build" + ]["packages"].get(TIANGOLO_BUILD_PACKAGE) + if not config: + return + project_config: Dict[str, Any] = config["project"] + # Override main [project] configs with custom configs for this package + for key, value in project_config.items(): + metadata[key] = value diff --git a/pyproject.toml b/pyproject.toml index c3801600a..edfa81522 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,13 +1,13 @@ [build-system] -requires = ["hatchling >= 1.13.0"] -build-backend = "hatchling.build" +requires = ["pdm-backend"] +build-backend = "pdm.backend" [project] name = "fastapi" +dynamic = ["version"] description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" readme = "README.md" requires-python = ">=3.8" -license = "MIT" authors = [ { name = "Sebastián Ramírez", email = "tiangolo@gmail.com" }, ] @@ -41,34 +41,84 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.36.3,<0.37.0", + "starlette>=0.40.0,<0.42.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] -dynamic = ["version"] [project.urls] -Homepage = "https://github.com/tiangolo/fastapi" +Homepage = "https://github.com/fastapi/fastapi" Documentation = "https://fastapi.tiangolo.com/" -Repository = "https://github.com/tiangolo/fastapi" +Repository = "https://github.com/fastapi/fastapi" +Issues = "https://github.com/fastapi/fastapi/issues" +Changelog = "https://fastapi.tiangolo.com/release-notes/" [project.optional-dependencies] + +standard = [ + "fastapi-cli[standard] >=0.0.5", + # For the test client + "httpx >=0.23.0", + # For templates + "jinja2 >=2.11.2", + # For forms and file uploads + "python-multipart >=0.0.7", + # To validate email fields + "email-validator >=2.0.0", + # Uvicorn with uvloop + "uvicorn[standard] >=0.12.0", + # TODO: this should be part of some pydantic optional extra dependencies + # # Settings management + # "pydantic-settings >=2.0.0", + # # Extra Pydantic data types + # "pydantic-extra-types >=2.0.0", +] + all = [ + "fastapi-cli[standard] >=0.0.5", + # # For the test client "httpx >=0.23.0", + # For templates "jinja2 >=2.11.2", + # For forms and file uploads "python-multipart >=0.0.7", + # For Starlette's SessionMiddleware, not commonly used with FastAPI "itsdangerous >=1.1.0", + # For Starlette's schema generation, would not be used with FastAPI "pyyaml >=5.3.1", + # For UJSONResponse "ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0", + # For ORJSONResponse "orjson >=3.2.1", - "email_validator >=2.0.0", + # To validate email fields + "email-validator >=2.0.0", + # Uvicorn with uvloop "uvicorn[standard] >=0.12.0", + # Settings management "pydantic-settings >=2.0.0", + # Extra Pydantic data types "pydantic-extra-types >=2.0.0", ] -[tool.hatch.version] -path = "fastapi/__init__.py" +[project.scripts] +fastapi = "fastapi.cli:main" + +[tool.pdm] +version = { source = "file", path = "fastapi/__init__.py" } +distribution = true + +[tool.pdm.build] +source-includes = [ + "tests/", + "docs_src/", + "requirements*.txt", + "scripts/", + # For a test + "docs/en/docs/img/favicon.png", + ] + +[tool.tiangolo._internal-slim-build.packages.fastapi-slim.project] +name = "fastapi-slim" [tool.mypy] strict = true @@ -99,46 +149,42 @@ xfail_strict = true junit_family = "xunit2" filterwarnings = [ "error", - # TODO: needed by asyncio in Python 3.9.7 https://bugs.python.org/issue45097, try to remove on 3.9.8 - 'ignore:The loop argument is deprecated since Python 3\.8, and scheduled for removal in Python 3\.10:DeprecationWarning:asyncio', 'ignore:starlette.middleware.wsgi is deprecated and will be removed in a future release\..*:DeprecationWarning:starlette', - # TODO: remove after upgrading HTTPX to a version newer than 0.23.0 - # Including PR: https://github.com/encode/httpx/pull/2309 - "ignore:'cgi' is deprecated:DeprecationWarning", # For passlib "ignore:'crypt' is deprecated and slated for removal in Python 3.13:DeprecationWarning", # see https://trio.readthedocs.io/en/stable/history.html#trio-0-22-0-2022-09-28 "ignore:You seem to already have a custom.*:RuntimeWarning:trio", - "ignore::trio.TrioDeprecationWarning", - # TODO remove pytest-cov - 'ignore::pytest.PytestDeprecationWarning:pytest_cov', # TODO: remove after upgrading SQLAlchemy to a version that includes the following changes # https://github.com/sqlalchemy/sqlalchemy/commit/59521abcc0676e936b31a523bd968fc157fef0c2 'ignore:datetime\.datetime\.utcfromtimestamp\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:sqlalchemy', - # TODO: remove after upgrading python-jose to a version that explicitly supports Python 3.12 - # also, if it won't receive an update, consider replacing python-jose with some alternative - # related issues: - # - https://github.com/mpdavis/python-jose/issues/332 - # - https://github.com/mpdavis/python-jose/issues/334 - 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', - # TODO: remove after upgrading Starlette to a version including https://github.com/encode/starlette/pull/2406 - # Probably Starlette 0.36.0 - "ignore: The 'method' parameter is not used, and it will be removed.:DeprecationWarning:starlette", + # Trio 24.1.0 raises a warning from attrs + # Ref: https://github.com/python-trio/trio/pull/3054 + # Remove once there's a new version of Trio + 'ignore:The `hash` argument is deprecated*:DeprecationWarning:trio', ] [tool.coverage.run] parallel = true +data_file = "coverage/.coverage" source = [ "docs_src", "tests", "fastapi" ] context = '${CONTEXT}' +dynamic_context = "test_function" omit = [ "docs_src/response_model/tutorial003_04.py", "docs_src/response_model/tutorial003_04_py310.py", ] +[tool.coverage.report] +show_missing = true +sort = "-Cover" + +[tool.coverage.html] +show_contexts = true + [tool.ruff.lint] select = [ "E", # pycodestyle errors @@ -195,3 +241,7 @@ known-third-party = ["fastapi", "pydantic", "starlette"] [tool.ruff.lint.pyupgrade] # Preserve types, even if a file imports `from __future__ import annotations`. keep-runtime-typing = true + +[tool.inline-snapshot] +# default-flags=["fix"] +# default-flags=["create"] diff --git a/requirements-docs-insiders.txt b/requirements-docs-insiders.txt new file mode 100644 index 000000000..d8d3c37a9 --- /dev/null +++ b/requirements-docs-insiders.txt @@ -0,0 +1,3 @@ +git+https://${TOKEN}@github.com/squidfunk/mkdocs-material-insiders.git@9.5.30-insiders-4.53.11 +git+https://${TOKEN}@github.com/pawamoy-insiders/griffe-typing-deprecated.git +git+https://${TOKEN}@github.com/pawamoy-insiders/mkdocstrings-python.git diff --git a/requirements-docs-tests.txt b/requirements-docs-tests.txt index b82df4933..331d2a5b3 100644 --- a/requirements-docs-tests.txt +++ b/requirements-docs-tests.txt @@ -1,2 +1,4 @@ # For mkdocstrings and tests -httpx >=0.23.0,<0.25.0 +httpx >=0.23.0,<0.28.0 +# For linting and generating docs versions +ruff ==0.6.4 diff --git a/requirements-docs.txt b/requirements-docs.txt index 28408a9f1..9754eaa4a 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -1,19 +1,19 @@ -e . -r requirements-docs-tests.txt -mkdocs-material==9.4.7 +mkdocs-material==9.5.18 mdx-include >=1.4.1,<2.0.0 -mkdocs-markdownextradata-plugin >=0.1.7,<0.3.0 mkdocs-redirects>=1.2.1,<1.3.0 -typer-cli >=0.0.13,<0.0.14 -typer[all] >=0.6.1,<0.8.0 +typer == 0.12.5 pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 # For image processing by Material for MkDocs -pillow==10.1.0 +pillow==11.0.0 # For image processing by Material for MkDocs -cairosvg==2.7.0 -mkdocstrings[python]==0.23.0 -griffe-typingdoc==0.2.2 +cairosvg==2.7.1 +mkdocstrings[python]==0.26.1 +griffe-typingdoc==0.2.7 # For griffe, it formats with black -black==23.3.0 +black==24.3.0 +mkdocs-macros-plugin==1.0.5 +markdown-include-variants==0.0.3 diff --git a/.github/actions/comment-docs-preview-in-pr/requirements.txt b/requirements-github-actions.txt similarity index 50% rename from .github/actions/comment-docs-preview-in-pr/requirements.txt rename to requirements-github-actions.txt index 74a3631f4..a6dace544 100644 --- a/.github/actions/comment-docs-preview-in-pr/requirements.txt +++ b/requirements-github-actions.txt @@ -1,4 +1,5 @@ -PyGithub +PyGithub>=2.3.0,<3.0.0 pydantic>=2.5.3,<3.0.0 pydantic-settings>=2.1.0,<3.0.0 -httpx +httpx>=0.27.0,<0.28.0 +smokeshow diff --git a/requirements-tests.txt b/requirements-tests.txt index 09ca9cb52..95ec09884 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -1,25 +1,16 @@ --e . +-e .[all] -r requirements-docs-tests.txt -pydantic-settings >=2.0.0 -pytest >=7.1.3,<8.0.0 +pytest >=7.1.3,<9.0.0 coverage[toml] >= 6.5.0,< 8.0 -mypy ==1.4.1 -ruff ==0.2.0 -email_validator >=1.1.1,<3.0.0 +mypy ==1.8.0 dirty-equals ==0.6.0 -# TODO: once removing databases from tutorial, upgrade SQLAlchemy -# probably when including SQLModel -sqlalchemy >=1.3.18,<1.4.43 -databases[sqlite] >=0.3.2,<0.7.0 -orjson >=3.2.1,<4.0.0 -ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0,<6.0.0 -python-multipart >=0.0.7,<0.1.0 -flask >=1.1.2,<3.0.0 +sqlmodel==0.0.22 +flask >=1.1.2,<4.0.0 anyio[trio] >=3.2.1,<4.0.0 -python-jose[cryptography] >=3.3.0,<4.0.0 +PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 - +inline-snapshot==0.13.0 # types types-ujson ==5.7.0.1 types-orjson ==3.6.2 diff --git a/requirements.txt b/requirements.txt index ef25ec483..9180bf1be 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,6 @@ -e .[all] -r requirements-tests.txt -r requirements-docs.txt -uvicorn[standard] >=0.12.0,<0.23.0 -pre-commit >=2.17.0,<4.0.0 +pre-commit >=2.17.0,<5.0.0 # For generating screenshots playwright diff --git a/scripts/build-docs.sh b/scripts/build-docs.sh deleted file mode 100755 index 7aa0a9a47..000000000 --- a/scripts/build-docs.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash - -set -e -set -x - -# Check README.md is up to date -python ./scripts/docs.py verify-docs -python ./scripts/docs.py build-all diff --git a/scripts/clean.sh b/scripts/clean.sh deleted file mode 100755 index d5a4b790a..000000000 --- a/scripts/clean.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/sh -e - -if [ -d 'dist' ] ; then - rm -r dist -fi -if [ -d 'site' ] ; then - rm -r site -fi diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py new file mode 100644 index 000000000..c652cdb6e --- /dev/null +++ b/scripts/deploy_docs_status.py @@ -0,0 +1,125 @@ +import logging +import re + +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + + +class Settings(BaseSettings): + github_repository: str + github_token: SecretStr + deploy_url: str | None = None + commit_sha: str + run_id: int + is_done: bool = False + + +class LinkData(BaseModel): + previous_link: str + preview_link: str + en_link: str | None = None + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + settings = Settings() + + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + use_pr = next( + (pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None + ) + if not use_pr: + logging.error(f"No PR found for hash: {settings.commit_sha}") + return + commits = list(use_pr.get_commits()) + current_commit = [c for c in commits if c.sha == settings.commit_sha][0] + run_url = f"https://github.com/{settings.github_repository}/actions/runs/{settings.run_id}" + if settings.is_done and not settings.deploy_url: + current_commit.create_status( + state="success", + description="No Docs Changes", + context="deploy-docs", + target_url=run_url, + ) + logging.info("No docs changes found") + return + if not settings.deploy_url: + current_commit.create_status( + state="pending", + description="Deploying Docs", + context="deploy-docs", + target_url=run_url, + ) + logging.info("No deploy URL available yet") + return + current_commit.create_status( + state="success", + description="Docs Deployed", + context="deploy-docs", + target_url=run_url, + ) + + files = list(use_pr.get_files()) + docs_files = [f for f in files if f.filename.startswith("docs/")] + + deploy_url = settings.deploy_url.rstrip("/") + lang_links: dict[str, list[LinkData]] = {} + for f in docs_files: + match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename) + if not match: + continue + lang = match.group(1) + path = match.group(2) + if path.endswith("index.md"): + path = path.replace("index.md", "") + else: + path = path.replace(".md", "/") + en_path = path + if lang == "en": + use_path = en_path + else: + use_path = f"{lang}/{path}" + link = LinkData( + previous_link=f"https://fastapi.tiangolo.com/{use_path}", + preview_link=f"{deploy_url}/{use_path}", + ) + if lang != "en": + link.en_link = f"https://fastapi.tiangolo.com/{en_path}" + lang_links.setdefault(lang, []).append(link) + + links: list[LinkData] = [] + en_links = lang_links.get("en", []) + en_links.sort(key=lambda x: x.preview_link) + links.extend(en_links) + + langs = list(lang_links.keys()) + langs.sort() + for lang in langs: + if lang == "en": + continue + current_lang_links = lang_links[lang] + current_lang_links.sort(key=lambda x: x.preview_link) + links.extend(current_lang_links) + + message = f"📝 Docs preview for commit {settings.commit_sha} at: {deploy_url}" + + if links: + message += "\n\n### Modified Pages\n\n" + for link in links: + message += f"* {link.preview_link}" + message += f" - ([before]({link.previous_link}))" + if link.en_link: + message += f" - ([English]({link.en_link}))" + message += "\n" + + print(message) + use_pr.as_issue().create_comment(message) + + logging.info("Finished") + + +if __name__ == "__main__": + main() diff --git a/scripts/docs-live.sh b/scripts/docs-live.sh deleted file mode 100755 index 30637a528..000000000 --- a/scripts/docs-live.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -set -e - -mkdocs serve --dev-addr 0.0.0.0:8008 diff --git a/scripts/docs.py b/scripts/docs.py index 59578a820..f26f96d85 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -11,13 +11,11 @@ from multiprocessing import Pool from pathlib import Path from typing import Any, Dict, List, Optional, Union -import mkdocs.commands.build -import mkdocs.commands.serve -import mkdocs.config import mkdocs.utils import typer import yaml from jinja2 import Template +from ruff.__main__ import find_ruff_bin logging.basicConfig(level=logging.INFO) @@ -26,9 +24,19 @@ app = typer.Typer() mkdocs_name = "mkdocs.yml" missing_translation_snippet = """ -{!../../../docs/missing-translation.md!} +{!../../docs/missing-translation.md!} """ +non_translated_sections = [ + "reference/", + "release-notes.md", + "fastapi-people.md", + "external-links.md", + "newsletter.md", + "management-tasks.md", + "management.md", +] + docs_path = Path("docs") en_docs_path = Path("docs/en") en_config_path: Path = en_docs_path / mkdocs_name @@ -165,6 +173,13 @@ def generate_readme_content() -> str: pre_content = content[frontmatter_end:pre_end] post_content = content[post_start:] new_content = pre_content + message + post_content + # Remove content between and + new_content = re.sub( + r".*?", + "", + new_content, + flags=re.DOTALL, + ) return new_content @@ -247,6 +262,7 @@ def live( lang: str = typer.Argument( None, callback=lang_callback, autocompletion=complete_existing_lang ), + dirty: bool = False, ) -> None: """ Serve with livereload a docs site for a specific language. @@ -258,12 +274,16 @@ def live( en. """ # Enable line numbers during local development to make it easier to highlight - os.environ["LINENUMS"] = "true" if lang is None: lang = "en" lang_path: Path = docs_path / lang - os.chdir(lang_path) - mkdocs.commands.serve.serve(dev_addr="127.0.0.1:8008") + # Enable line numbers during local development to make it easier to highlight + args = ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008"] + if dirty: + args.append("--dirty") + subprocess.run( + args, env={**os.environ, "LINENUMS": "true"}, cwd=lang_path, check=True + ) def get_updated_config_content() -> Dict[str, Any]: @@ -324,10 +344,34 @@ def verify_config() -> None: typer.echo("Valid mkdocs.yml ✅") +@app.command() +def verify_non_translated() -> None: + """ + Verify there are no files in the non translatable pages. + """ + print("Verifying non translated pages") + lang_paths = get_lang_paths() + error_paths = [] + for lang in lang_paths: + if lang.name == "en": + continue + for non_translatable in non_translated_sections: + non_translatable_path = lang / "docs" / non_translatable + if non_translatable_path.exists(): + error_paths.append(non_translatable_path) + if error_paths: + print("Non-translated pages found, remove them:") + for error_path in error_paths: + print(error_path) + raise typer.Abort() + print("No non-translated pages found ✅") + + @app.command() def verify_docs(): verify_readme() verify_config() + verify_non_translated() @app.command() @@ -339,5 +383,41 @@ def langs_json(): print(json.dumps(langs)) +@app.command() +def generate_docs_src_versions_for_file(file_path: Path) -> None: + target_versions = ["py39", "py310"] + base_content = file_path.read_text(encoding="utf-8") + previous_content = {base_content} + for target_version in target_versions: + version_result = subprocess.run( + [ + find_ruff_bin(), + "check", + "--target-version", + target_version, + "--fix", + "--unsafe-fixes", + "-", + ], + input=base_content.encode("utf-8"), + capture_output=True, + ) + content_target = version_result.stdout.decode("utf-8") + format_result = subprocess.run( + [find_ruff_bin(), "format", "-"], + input=content_target.encode("utf-8"), + capture_output=True, + ) + content_format = format_result.stdout.decode("utf-8") + if content_format in previous_content: + continue + previous_content.add(content_format) + version_file = file_path.with_name( + file_path.name.replace(".py", f"_{target_version}.py") + ) + logging.info(f"Writing to {version_file}") + version_file.write_text(content_format, encoding="utf-8") + + if __name__ == "__main__": app() diff --git a/scripts/format.sh b/scripts/format.sh index 11f25f1ce..bf70f42e5 100755 --- a/scripts/format.sh +++ b/scripts/format.sh @@ -1,5 +1,5 @@ -#!/bin/sh -e +#!/usr/bin/env bash set -x -ruff fastapi tests docs_src scripts --fix +ruff check fastapi tests docs_src scripts --fix ruff format fastapi tests docs_src scripts diff --git a/scripts/label_approved.py b/scripts/label_approved.py new file mode 100644 index 000000000..271444504 --- /dev/null +++ b/scripts/label_approved.py @@ -0,0 +1,60 @@ +import logging +from typing import Literal + +from github import Github +from github.PullRequestReview import PullRequestReview +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + + +class LabelSettings(BaseModel): + await_label: str | None = None + number: int + + +default_config = {"approved-2": LabelSettings(await_label="awaiting-review", number=2)} + + +class Settings(BaseSettings): + github_repository: str + token: SecretStr + debug: bool | None = False + config: dict[str, LabelSettings] | Literal[""] = default_config + + +settings = Settings() +if settings.debug: + logging.basicConfig(level=logging.DEBUG) +else: + logging.basicConfig(level=logging.INFO) +logging.debug(f"Using config: {settings.json()}") +g = Github(settings.token.get_secret_value()) +repo = g.get_repo(settings.github_repository) +for pr in repo.get_pulls(state="open"): + logging.info(f"Checking PR: #{pr.number}") + pr_labels = list(pr.get_labels()) + pr_label_by_name = {label.name: label for label in pr_labels} + reviews = list(pr.get_reviews()) + review_by_user: dict[str, PullRequestReview] = {} + for review in reviews: + if review.user.login in review_by_user: + stored_review = review_by_user[review.user.login] + if review.submitted_at >= stored_review.submitted_at: + review_by_user[review.user.login] = review + else: + review_by_user[review.user.login] = review + approved_reviews = [ + review for review in review_by_user.values() if review.state == "APPROVED" + ] + config = settings.config or default_config + for approved_label, conf in config.items(): + logging.debug(f"Processing config: {conf.json()}") + if conf.await_label is None or (conf.await_label in pr_label_by_name): + logging.debug(f"Processable PR: {pr.number}") + if len(approved_reviews) >= conf.number: + logging.info(f"Adding label to PR: {pr.number}") + pr.add_to_labels(approved_label) + if conf.await_label: + logging.info(f"Removing label from PR: {pr.number}") + pr.remove_from_labels(conf.await_label) +logging.info("Finished") diff --git a/scripts/lint.sh b/scripts/lint.sh index c0e24db9f..18cf52a84 100755 --- a/scripts/lint.sh +++ b/scripts/lint.sh @@ -4,5 +4,5 @@ set -e set -x mypy fastapi -ruff fastapi tests docs_src scripts +ruff check fastapi tests docs_src scripts ruff format fastapi tests --check diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py index 8335a13f6..0bc4929a4 100644 --- a/scripts/mkdocs_hooks.py +++ b/scripts/mkdocs_hooks.py @@ -8,9 +8,14 @@ from mkdocs.structure.files import File, Files from mkdocs.structure.nav import Link, Navigation, Section from mkdocs.structure.pages import Page -non_traslated_sections = [ +non_translated_sections = [ "reference/", "release-notes.md", + "fastapi-people.md", + "external-links.md", + "newsletter.md", + "management-tasks.md", + "management.md", ] @@ -39,7 +44,7 @@ def on_config(config: MkDocsConfig, **kwargs: Any) -> MkDocsConfig: lang = dir_path.parent.name if lang in available_langs: config.theme["language"] = lang - if not (config.site_url or "").endswith(f"{lang}/") and not lang == "en": + if not (config.site_url or "").endswith(f"{lang}/") and lang != "en": config.site_url = f"{config.site_url}{lang}/" return config @@ -128,7 +133,7 @@ def on_page_markdown( markdown: str, *, page: Page, config: MkDocsConfig, files: Files ) -> str: if isinstance(page.file, EnFile): - for excluded_section in non_traslated_sections: + for excluded_section in non_translated_sections: if page.file.src_path.startswith(excluded_section): return markdown missing_translation_content = get_missing_translation_content(config.docs_dir) diff --git a/scripts/netlify-docs.sh b/scripts/netlify-docs.sh deleted file mode 100755 index 8f9065e23..000000000 --- a/scripts/netlify-docs.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -set -x -set -e -# Install pip -cd /tmp -curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py -python3.6 get-pip.py --user -cd - -# Install Flit to be able to install all -python3.6 -m pip install --user flit -# Install with Flit -python3.6 -m flit install --user --extras doc -# Finally, run mkdocs -python3.6 -m mkdocs build diff --git a/scripts/playwright/cookie_param_models/image01.py b/scripts/playwright/cookie_param_models/image01.py new file mode 100644 index 000000000..77c91bfe2 --- /dev/null +++ b/scripts/playwright/cookie_param_models/image01.py @@ -0,0 +1,39 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + browser = playwright.chromium.launch(headless=False) + context = browser.new_context() + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("link", name="/items/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/cookie-param-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/cookie_param_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/header_param_models/image01.py b/scripts/playwright/header_param_models/image01.py new file mode 100644 index 000000000..53914251e --- /dev/null +++ b/scripts/playwright/header_param_models/image01.py @@ -0,0 +1,38 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="GET /items/ Read Items").click() + page.get_by_role("button", name="Try it out").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/header-param-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/header_param_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/query_param_models/image01.py b/scripts/playwright/query_param_models/image01.py new file mode 100644 index 000000000..0ea1d0df4 --- /dev/null +++ b/scripts/playwright/query_param_models/image01.py @@ -0,0 +1,41 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + browser = playwright.chromium.launch(headless=False) + context = browser.new_context() + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="GET /items/ Read Items").click() + page.get_by_role("button", name="Try it out").click() + page.get_by_role("heading", name="Servers").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/query-param-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/query_param_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/request_form_models/image01.py b/scripts/playwright/request_form_models/image01.py new file mode 100644 index 000000000..fe4da32fc --- /dev/null +++ b/scripts/playwright/request_form_models/image01.py @@ -0,0 +1,38 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="POST /login/ Login").click() + page.get_by_role("button", name="Try it out").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/request-form-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/request_form_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/separate_openapi_schemas/image01.py b/scripts/playwright/separate_openapi_schemas/image01.py index 0b40f3bbc..0eb55fb73 100644 --- a/scripts/playwright/separate_openapi_schemas/image01.py +++ b/scripts/playwright/separate_openapi_schemas/image01.py @@ -3,13 +3,16 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_text("POST/items/Create Item").click() page.get_by_role("tab", name="Schema").first.click() + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image01.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image02.py b/scripts/playwright/separate_openapi_schemas/image02.py index f76af7ee2..0eb6c3c79 100644 --- a/scripts/playwright/separate_openapi_schemas/image02.py +++ b/scripts/playwright/separate_openapi_schemas/image02.py @@ -3,14 +3,17 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_text("GET/items/Read Items").click() page.get_by_role("button", name="Try it out").click() page.get_by_role("button", name="Execute").click() + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image02.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image03.py b/scripts/playwright/separate_openapi_schemas/image03.py index 127f5c428..b68e9d7db 100644 --- a/scripts/playwright/separate_openapi_schemas/image03.py +++ b/scripts/playwright/separate_openapi_schemas/image03.py @@ -3,14 +3,17 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_text("GET/items/Read Items").click() page.get_by_role("tab", name="Schema").click() page.get_by_label("Schema").get_by_role("button", name="Expand all").click() + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image03.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image04.py b/scripts/playwright/separate_openapi_schemas/image04.py index 208eaf8a0..a36c2f6b2 100644 --- a/scripts/playwright/separate_openapi_schemas/image04.py +++ b/scripts/playwright/separate_openapi_schemas/image04.py @@ -3,14 +3,17 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_role("button", name="Item-Input").click() page.get_by_role("button", name="Item-Output").click() page.set_viewport_size({"width": 960, "height": 820}) + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image04.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image05.py b/scripts/playwright/separate_openapi_schemas/image05.py index 83966b449..0da5db0cf 100644 --- a/scripts/playwright/separate_openapi_schemas/image05.py +++ b/scripts/playwright/separate_openapi_schemas/image05.py @@ -3,13 +3,16 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_role("button", name="Item", exact=True).click() page.set_viewport_size({"width": 960, "height": 700}) + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png" ) diff --git a/scripts/playwright/sql_databases/image01.py b/scripts/playwright/sql_databases/image01.py new file mode 100644 index 000000000..0dd6f2514 --- /dev/null +++ b/scripts/playwright/sql_databases/image01.py @@ -0,0 +1,37 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_label("post /heroes/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/sql_databases/tutorial001.py"], +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/sql_databases/image02.py b/scripts/playwright/sql_databases/image02.py new file mode 100644 index 000000000..6c4f685e8 --- /dev/null +++ b/scripts/playwright/sql_databases/image02.py @@ -0,0 +1,37 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_label("post /heroes/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image02.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/sql_databases/tutorial002.py"], +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/publish.sh b/scripts/publish.sh deleted file mode 100755 index 122728a60..000000000 --- a/scripts/publish.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -set -e - -flit publish diff --git a/scripts/test-cov-html.sh b/scripts/test-cov-html.sh index d1bdfced2..517ac6422 100755 --- a/scripts/test-cov-html.sh +++ b/scripts/test-cov-html.sh @@ -5,5 +5,5 @@ set -x bash scripts/test.sh ${@} coverage combine -coverage report --show-missing +coverage report coverage html diff --git a/tests/main.py b/tests/main.py index 15760c039..6927eab61 100644 --- a/tests/main.py +++ b/tests/main.py @@ -1,5 +1,5 @@ import http -from typing import FrozenSet, Optional +from typing import FrozenSet, List, Optional from fastapi import FastAPI, Path, Query @@ -192,3 +192,13 @@ def get_enum_status_code(): @app.get("/query/frozenset") def get_query_type_frozenset(query: FrozenSet[int] = Query(...)): return ",".join(map(str, sorted(query))) + + +@app.get("/query/list") +def get_query_list(device_ids: List[int] = Query()) -> List[int]: + return device_ids + + +@app.get("/query/list-default") +def get_query_list_default(device_ids: List[int] = Query(default=[])) -> List[int]: + return device_ids diff --git a/tests/test_allow_inf_nan_in_enforcing.py b/tests/test_allow_inf_nan_in_enforcing.py new file mode 100644 index 000000000..9e855fdf8 --- /dev/null +++ b/tests/test_allow_inf_nan_in_enforcing.py @@ -0,0 +1,83 @@ +import pytest +from fastapi import Body, FastAPI, Query +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + + +@app.post("/") +async def get( + x: Annotated[float, Query(allow_inf_nan=True)] = 0, + y: Annotated[float, Query(allow_inf_nan=False)] = 0, + z: Annotated[float, Query()] = 0, + b: Annotated[float, Body(allow_inf_nan=False)] = 0, +) -> str: + return "OK" + + +client = TestClient(app) + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 200), + ("-inf", 200), + ("nan", 200), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_true(value: str, code: int): + response = client.post(f"/?x={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 422), + ("-inf", 422), + ("nan", 422), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_false(value: str, code: int): + response = client.post(f"/?y={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 200), + ("-inf", 200), + ("nan", 200), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_default(value: str, code: int): + response = client.post(f"/?z={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 422), + ("-inf", 422), + ("nan", 422), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_body(value: str, code: int): + response = client.post("/", json=value) + assert response.status_code == code, response.text diff --git a/tests/test_annotated.py b/tests/test_annotated.py index 2222be978..473d33e52 100644 --- a/tests/test_annotated.py +++ b/tests/test_annotated.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import APIRouter, FastAPI, Query from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from typing_extensions import Annotated app = FastAPI() @@ -38,7 +37,6 @@ foo_is_missing = { "msg": "Field required", "type": "missing", "input": None, - "url": match_pydantic_error_url("missing"), } ) # TODO: remove when deprecating Pydantic v1 @@ -60,7 +58,6 @@ foo_is_short = { "msg": "String should have at least 1 character", "type": "string_too_short", "input": "", - "url": match_pydantic_error_url("string_too_short"), } ) # TODO: remove when deprecating Pydantic v1 diff --git a/tests/test_application.py b/tests/test_application.py index ea7a80128..5c62f5f6e 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -1163,6 +1163,91 @@ def test_openapi_schema(): }, } }, + "/query/list": { + "get": { + "summary": "Get Query List", + "operationId": "get_query_list_query_list_get", + "parameters": [ + { + "name": "device_ids", + "in": "query", + "required": True, + "schema": { + "type": "array", + "items": {"type": "integer"}, + "title": "Device Ids", + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": {"type": "integer"}, + "title": "Response Get Query List Query List Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/query/list-default": { + "get": { + "summary": "Get Query List Default", + "operationId": "get_query_list_default_query_list_default_get", + "parameters": [ + { + "name": "device_ids", + "in": "query", + "required": False, + "schema": { + "type": "array", + "items": {"type": "integer"}, + "default": [], + "title": "Device Ids", + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": {"type": "integer"}, + "title": "Response Get Query List Default Query List Default Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, }, "components": { "schemas": { diff --git a/tests/test_compat.py b/tests/test_compat.py index bf268b860..f4a3093c5 100644 --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -1,11 +1,14 @@ -from typing import List, Union +from typing import Any, Dict, List, Union from fastapi import FastAPI, UploadFile from fastapi._compat import ( ModelField, Undefined, _get_model_config, + get_cached_model_fields, + get_model_fields, is_bytes_sequence_annotation, + is_scalar_field, is_uploadfile_sequence_annotation, ) from fastapi.testclient import TestClient @@ -91,3 +94,27 @@ def test_is_uploadfile_sequence_annotation(): # and other types, but I'm not even sure it's a good idea to support it as a first # class "feature" assert is_uploadfile_sequence_annotation(Union[List[str], List[UploadFile]]) + + +def test_is_pv1_scalar_field(): + # For coverage + class Model(BaseModel): + foo: Union[str, Dict[str, Any]] + + fields = get_model_fields(Model) + assert not is_scalar_field(fields[0]) + + +def test_get_model_fields_cached(): + class Model(BaseModel): + foo: str + + non_cached_fields = get_model_fields(Model) + non_cached_fields2 = get_model_fields(Model) + cached_fields = get_cached_model_fields(Model) + cached_fields2 = get_cached_model_fields(Model) + for f1, f2 in zip(cached_fields, cached_fields2): + assert f1 is f2 + + assert non_cached_fields is not non_cached_fields2 + assert cached_fields is cached_fields2 diff --git a/tests/test_computed_fields.py b/tests/test_computed_fields.py index 5286507b2..a1b412168 100644 --- a/tests/test_computed_fields.py +++ b/tests/test_computed_fields.py @@ -24,13 +24,18 @@ def get_client(): def read_root() -> Rectangle: return Rectangle(width=3, length=4) + @app.get("/responses", responses={200: {"model": Rectangle}}) + def read_responses() -> Rectangle: + return Rectangle(width=3, length=4) + client = TestClient(app) return client +@pytest.mark.parametrize("path", ["/", "/responses"]) @needs_pydanticv2 -def test_get(client: TestClient): - response = client.get("/") +def test_get(client: TestClient, path: str): + response = client.get(path) assert response.status_code == 200, response.text assert response.json() == {"width": 3, "length": 4, "area": 12} @@ -58,7 +63,23 @@ def test_openapi_schema(client: TestClient): } }, } - } + }, + "/responses": { + "get": { + "summary": "Read Responses", + "operationId": "read_responses_responses_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Rectangle"} + } + }, + } + }, + } + }, }, "components": { "schemas": { diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py index 008dab7bc..039c423b9 100644 --- a/tests/test_dependency_contextmanager.py +++ b/tests/test_dependency_contextmanager.py @@ -196,9 +196,9 @@ async def get_sync_context_b_bg( tasks: BackgroundTasks, state: dict = Depends(context_b) ): async def bg(state: dict): - state[ - "sync_bg" - ] = f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}" + state["sync_bg"] = ( + f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}" + ) tasks.add_task(bg, state) return state diff --git a/tests/test_dependency_duplicates.py b/tests/test_dependency_duplicates.py index 0882cc41d..8e8d07c2d 100644 --- a/tests/test_dependency_duplicates.py +++ b/tests/test_dependency_duplicates.py @@ -3,7 +3,6 @@ from typing import List from dirty_equals import IsDict from fastapi import Depends, FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -57,7 +56,6 @@ def test_no_duplicates_invalid(): "loc": ["body", "item2"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_dependency_overrides.py b/tests/test_dependency_overrides.py index 21cff998d..154937fa0 100644 --- a/tests/test_dependency_overrides.py +++ b/tests/test_dependency_overrides.py @@ -4,7 +4,6 @@ import pytest from dirty_equals import IsDict from fastapi import APIRouter, Depends, FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url app = FastAPI() @@ -63,7 +62,6 @@ def test_main_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -110,7 +108,6 @@ def test_decorator_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -151,7 +148,6 @@ def test_router_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -198,7 +194,6 @@ def test_router_decorator_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -285,7 +280,6 @@ def test_override_with_sub_main_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -316,7 +310,6 @@ def test_override_with_sub__main_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -355,7 +348,6 @@ def test_override_with_sub_decorator_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -386,7 +378,6 @@ def test_override_with_sub_decorator_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -425,7 +416,6 @@ def test_override_with_sub_router_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -456,7 +446,6 @@ def test_override_with_sub_router_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -495,7 +484,6 @@ def test_override_with_sub_router_decorator_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -526,7 +514,6 @@ def test_override_with_sub_router_decorator_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_fastapi_cli.py b/tests/test_fastapi_cli.py new file mode 100644 index 000000000..20c928157 --- /dev/null +++ b/tests/test_fastapi_cli.py @@ -0,0 +1,32 @@ +import subprocess +import sys +from unittest.mock import patch + +import fastapi.cli +import pytest + + +def test_fastapi_cli(): + result = subprocess.run( + [ + sys.executable, + "-m", + "coverage", + "run", + "-m", + "fastapi", + "dev", + "non_existent_file.py", + ], + capture_output=True, + encoding="utf-8", + ) + assert result.returncode == 1, result.stdout + assert "Using path non_existent_file.py" in result.stdout + + +def test_fastapi_cli_not_installed(): + with patch.object(fastapi.cli, "cli_main", None): + with pytest.raises(RuntimeError) as exc_info: + fastapi.cli.main() + assert "To use the fastapi command, please install" in str(exc_info.value) diff --git a/tests/test_filter_pydantic_sub_model_pv2.py b/tests/test_filter_pydantic_sub_model_pv2.py index 9097d2ce5..2e2c26ddc 100644 --- a/tests/test_filter_pydantic_sub_model_pv2.py +++ b/tests/test_filter_pydantic_sub_model_pv2.py @@ -5,7 +5,6 @@ from dirty_equals import HasRepr, IsDict, IsOneOf from fastapi import Depends, FastAPI from fastapi.exceptions import ResponseValidationError from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from .utils import needs_pydanticv2 @@ -67,7 +66,6 @@ def test_validator_is_cloned(client: TestClient): "msg": "Value error, name must end in A", "input": "modelX", "ctx": {"error": HasRepr("ValueError('name must end in A')")}, - "url": match_pydantic_error_url("value_error"), } ) | IsDict( diff --git a/tests/test_forms_single_model.py b/tests/test_forms_single_model.py new file mode 100644 index 000000000..880ab3820 --- /dev/null +++ b/tests/test_forms_single_model.py @@ -0,0 +1,133 @@ +from typing import List, Optional + +from dirty_equals import IsDict +from fastapi import FastAPI, Form +from fastapi.testclient import TestClient +from pydantic import BaseModel, Field +from typing_extensions import Annotated + +app = FastAPI() + + +class FormModel(BaseModel): + username: str + lastname: str + age: Optional[int] = None + tags: List[str] = ["foo", "bar"] + alias_with: str = Field(alias="with", default="nothing") + + +@app.post("/form/") +def post_form(user: Annotated[FormModel, Form()]): + return user + + +client = TestClient(app) + + +def test_send_all_data(): + response = client.post( + "/form/", + data={ + "username": "Rick", + "lastname": "Sanchez", + "age": "70", + "tags": ["plumbus", "citadel"], + "with": "something", + }, + ) + assert response.status_code == 200, response.text + assert response.json() == { + "username": "Rick", + "lastname": "Sanchez", + "age": 70, + "tags": ["plumbus", "citadel"], + "with": "something", + } + + +def test_defaults(): + response = client.post("/form/", data={"username": "Rick", "lastname": "Sanchez"}) + assert response.status_code == 200, response.text + assert response.json() == { + "username": "Rick", + "lastname": "Sanchez", + "age": None, + "tags": ["foo", "bar"], + "with": "nothing", + } + + +def test_invalid_data(): + response = client.post( + "/form/", + data={ + "username": "Rick", + "lastname": "Sanchez", + "age": "seventy", + "tags": ["plumbus", "citadel"], + }, + ) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["body", "age"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "seventy", + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "age"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_no_data(): + response = client.post("/form/") + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"tags": ["foo", "bar"], "with": "nothing"}, + }, + { + "type": "missing", + "loc": ["body", "lastname"], + "msg": "Field required", + "input": {"tags": ["foo", "bar"], "with": "nothing"}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "lastname"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) diff --git a/tests/test_forms_single_param.py b/tests/test_forms_single_param.py new file mode 100644 index 000000000..3bb951441 --- /dev/null +++ b/tests/test_forms_single_param.py @@ -0,0 +1,99 @@ +from fastapi import FastAPI, Form +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + + +@app.post("/form/") +def post_form(username: Annotated[str, Form()]): + return username + + +client = TestClient(app) + + +def test_single_form_field(): + response = client.post("/form/", data={"username": "Rick"}) + assert response.status_code == 200, response.text + assert response.json() == "Rick" + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/form/": { + "post": { + "summary": "Post Form", + "operationId": "post_form_form__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "$ref": "#/components/schemas/Body_post_form_form__post" + } + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "Body_post_form_form__post": { + "properties": {"username": {"type": "string", "title": "Username"}}, + "type": "object", + "required": ["username"], + "title": "Body_post_form_form__post", + }, + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_generic_parameterless_depends.py b/tests/test_generic_parameterless_depends.py new file mode 100644 index 000000000..fe13ff89b --- /dev/null +++ b/tests/test_generic_parameterless_depends.py @@ -0,0 +1,77 @@ +from typing import TypeVar + +from fastapi import Depends, FastAPI +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + +T = TypeVar("T") + +Dep = Annotated[T, Depends()] + + +class A: + pass + + +class B: + pass + + +@app.get("/a") +async def a(dep: Dep[A]): + return {"cls": dep.__class__.__name__} + + +@app.get("/b") +async def b(dep: Dep[B]): + return {"cls": dep.__class__.__name__} + + +client = TestClient(app) + + +def test_generic_parameterless_depends(): + response = client.get("/a") + assert response.status_code == 200, response.text + assert response.json() == {"cls": "A"} + + response = client.get("/b") + assert response.status_code == 200, response.text + assert response.json() == {"cls": "B"} + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "info": {"title": "FastAPI", "version": "0.1.0"}, + "openapi": "3.1.0", + "paths": { + "/a": { + "get": { + "operationId": "a_a_get", + "responses": { + "200": { + "content": {"application/json": {"schema": {}}}, + "description": "Successful " "Response", + } + }, + "summary": "A", + } + }, + "/b": { + "get": { + "operationId": "b_b_get", + "responses": { + "200": { + "content": {"application/json": {"schema": {}}}, + "description": "Successful " "Response", + } + }, + "summary": "B", + } + }, + }, + } diff --git a/tests/test_inherited_custom_class.py b/tests/test_inherited_custom_class.py index 42b249211..fe9350f4e 100644 --- a/tests/test_inherited_custom_class.py +++ b/tests/test_inherited_custom_class.py @@ -36,7 +36,7 @@ def test_pydanticv2(): def return_fast_uuid(): asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") assert isinstance(asyncpg_uuid, uuid.UUID) - assert type(asyncpg_uuid) != uuid.UUID + assert type(asyncpg_uuid) is not uuid.UUID with pytest.raises(TypeError): vars(asyncpg_uuid) return {"fast_uuid": asyncpg_uuid} @@ -79,7 +79,7 @@ def test_pydanticv1(): def return_fast_uuid(): asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") assert isinstance(asyncpg_uuid, uuid.UUID) - assert type(asyncpg_uuid) != uuid.UUID + assert type(asyncpg_uuid) is not uuid.UUID with pytest.raises(TypeError): vars(asyncpg_uuid) return {"fast_uuid": asyncpg_uuid} diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index 7c8338ff3..1906d6bf1 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -7,7 +7,7 @@ from pathlib import PurePath, PurePosixPath, PureWindowsPath from typing import Optional import pytest -from fastapi._compat import PYDANTIC_V2 +from fastapi._compat import PYDANTIC_V2, Undefined from fastapi.encoders import jsonable_encoder from pydantic import BaseModel, Field, ValidationError @@ -310,3 +310,9 @@ def test_encode_deque_encodes_child_models(): dq = deque([Model(test="test")]) assert jsonable_encoder(dq)[0]["test"] == "test" + + +@needs_pydanticv2 +def test_encode_pydantic_undefined(): + data = {"value": Undefined} + assert jsonable_encoder(data) == {"value": None} diff --git a/tests/test_multi_body_errors.py b/tests/test_multi_body_errors.py index a51ca7253..0102f0f1a 100644 --- a/tests/test_multi_body_errors.py +++ b/tests/test_multi_body_errors.py @@ -4,7 +4,6 @@ from typing import List from dirty_equals import IsDict, IsOneOf from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel, condecimal app = FastAPI() @@ -52,7 +51,6 @@ def test_jsonable_encoder_requiring_error(): "msg": "Input should be greater than 0", "input": -1.0, "ctx": {"gt": 0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -82,28 +80,24 @@ def test_put_incorrect_body_multiple(): "loc": ["body", 0, "name"], "msg": "Field required", "input": {"age": "five"}, - "url": match_pydantic_error_url("missing"), }, { "type": "decimal_parsing", "loc": ["body", 0, "age"], "msg": "Input should be a valid decimal", "input": "five", - "url": match_pydantic_error_url("decimal_parsing"), }, { "type": "missing", "loc": ["body", 1, "name"], "msg": "Field required", "input": {"age": "six"}, - "url": match_pydantic_error_url("missing"), }, { "type": "decimal_parsing", "loc": ["body", 1, "age"], "msg": "Input should be a valid decimal", "input": "six", - "url": match_pydantic_error_url("decimal_parsing"), }, ] } diff --git a/tests/test_multi_query_errors.py b/tests/test_multi_query_errors.py index 470a35808..8162d986c 100644 --- a/tests/test_multi_query_errors.py +++ b/tests/test_multi_query_errors.py @@ -3,7 +3,6 @@ from typing import List from dirty_equals import IsDict from fastapi import FastAPI, Query from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url app = FastAPI() @@ -33,14 +32,12 @@ def test_multi_query_incorrect(): "loc": ["query", "q", 0], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "five", - "url": match_pydantic_error_url("int_parsing"), }, { "type": "int_parsing", "loc": ["query", "q", 1], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "six", - "url": match_pydantic_error_url("int_parsing"), }, ] } diff --git a/tests/test_multipart_installation.py b/tests/test_multipart_installation.py index 788d9ef5a..9c3e47c49 100644 --- a/tests/test_multipart_installation.py +++ b/tests/test_multipart_installation.py @@ -1,3 +1,5 @@ +import warnings + import pytest from fastapi import FastAPI, File, Form, UploadFile from fastapi.dependencies.utils import ( @@ -7,7 +9,10 @@ from fastapi.dependencies.utils import ( def test_incorrect_multipart_installed_form(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -17,7 +22,10 @@ def test_incorrect_multipart_installed_form(monkeypatch): def test_incorrect_multipart_installed_file_upload(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -27,7 +35,10 @@ def test_incorrect_multipart_installed_file_upload(monkeypatch): def test_incorrect_multipart_installed_file_bytes(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -37,7 +48,10 @@ def test_incorrect_multipart_installed_file_bytes(monkeypatch): def test_incorrect_multipart_installed_multi_form(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -47,7 +61,10 @@ def test_incorrect_multipart_installed_multi_form(monkeypatch): def test_incorrect_multipart_installed_form_file(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -57,50 +74,76 @@ def test_incorrect_multipart_installed_form_file(monkeypatch): def test_no_multipart_installed(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(username: str = Form()): - return username # pragma: nocover + @app.post("/") + async def root(username: str = Form()): + return username # pragma: nocover def test_no_multipart_installed_file(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(f: UploadFile = File()): - return f # pragma: nocover + @app.post("/") + async def root(f: UploadFile = File()): + return f # pragma: nocover def test_no_multipart_installed_file_bytes(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(f: bytes = File()): - return f # pragma: nocover + @app.post("/") + async def root(f: bytes = File()): + return f # pragma: nocover def test_no_multipart_installed_multi_form(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(username: str = Form(), password: str = Form()): - return username # pragma: nocover + @app.post("/") + async def root(username: str = Form(), password: str = Form()): + return username # pragma: nocover def test_no_multipart_installed_form_file(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() + + @app.post("/") + async def root(username: str = Form(), f: UploadFile = File()): + return username # pragma: nocover + + +def test_old_multipart_installed(monkeypatch): + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") app = FastAPI() @app.post("/") - async def root(username: str = Form(), f: UploadFile = File()): + async def root(username: str = Form()): return username # pragma: nocover diff --git a/tests/test_openapi_examples.py b/tests/test_openapi_examples.py index 6597e5058..b3f83ae23 100644 --- a/tests/test_openapi_examples.py +++ b/tests/test_openapi_examples.py @@ -155,13 +155,26 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": { - "allOf": [{"$ref": "#/components/schemas/Item"}], - "title": "Item", - "examples": [ - {"data": "Data in Body examples, example1"} - ], - }, + "schema": IsDict( + { + "$ref": "#/components/schemas/Item", + "examples": [ + {"data": "Data in Body examples, example1"} + ], + } + ) + | IsDict( + { + # TODO: remove when deprecating Pydantic v1 + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + "examples": [ + {"data": "Data in Body examples, example1"} + ], + } + ), "examples": { "Example One": { "summary": "Example One Summary", diff --git a/tests/test_openapi_separate_input_output_schemas.py b/tests/test_openapi_separate_input_output_schemas.py index aeb85f735..f7e045259 100644 --- a/tests/test_openapi_separate_input_output_schemas.py +++ b/tests/test_openapi_separate_input_output_schemas.py @@ -26,8 +26,8 @@ class Item(BaseModel): def get_app_client(separate_input_output_schemas: bool = True) -> TestClient: app = FastAPI(separate_input_output_schemas=separate_input_output_schemas) - @app.post("/items/") - def create_item(item: Item): + @app.post("/items/", responses={402: {"model": Item}}) + def create_item(item: Item) -> Item: return item @app.post("/items-list/") @@ -174,7 +174,23 @@ def test_openapi_schema(): "responses": { "200": { "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item-Output" + } + } + }, + }, + "402": { + "description": "Payment Required", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item-Output" + } + } + }, }, "422": { "description": "Validation Error", @@ -374,7 +390,19 @@ def test_openapi_schema_no_separate(): "responses": { "200": { "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "402": { + "description": "Payment Required", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, }, "422": { "description": "Validation Error", diff --git a/tests/test_path.py b/tests/test_path.py index 848b245e2..09c1f13fb 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from .main import app @@ -54,7 +53,6 @@ def test_path_int_foobar(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foobar", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -83,7 +81,6 @@ def test_path_int_True(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "True", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -118,7 +115,6 @@ def test_path_int_42_5(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "42.5", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -147,7 +143,6 @@ def test_path_float_foobar(): "loc": ["path", "item_id"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "foobar", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -176,7 +171,6 @@ def test_path_float_True(): "loc": ["path", "item_id"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "True", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -217,7 +211,6 @@ def test_path_bool_foobar(): "loc": ["path", "item_id"], "msg": "Input should be a valid boolean, unable to interpret input", "input": "foobar", - "url": match_pydantic_error_url("bool_parsing"), } ] } @@ -252,7 +245,6 @@ def test_path_bool_42(): "loc": ["path", "item_id"], "msg": "Input should be a valid boolean, unable to interpret input", "input": "42", - "url": match_pydantic_error_url("bool_parsing"), } ] } @@ -281,7 +273,6 @@ def test_path_bool_42_5(): "loc": ["path", "item_id"], "msg": "Input should be a valid boolean, unable to interpret input", "input": "42.5", - "url": match_pydantic_error_url("bool_parsing"), } ] } @@ -353,7 +344,6 @@ def test_path_param_minlength_fo(): "msg": "String should have at least 3 characters", "input": "fo", "ctx": {"min_length": 3}, - "url": match_pydantic_error_url("string_too_short"), } ] } @@ -390,7 +380,6 @@ def test_path_param_maxlength_foobar(): "msg": "String should have at most 3 characters", "input": "foobar", "ctx": {"max_length": 3}, - "url": match_pydantic_error_url("string_too_long"), } ] } @@ -427,7 +416,6 @@ def test_path_param_min_maxlength_foobar(): "msg": "String should have at most 3 characters", "input": "foobar", "ctx": {"max_length": 3}, - "url": match_pydantic_error_url("string_too_long"), } ] } @@ -458,7 +446,6 @@ def test_path_param_min_maxlength_f(): "msg": "String should have at least 2 characters", "input": "f", "ctx": {"min_length": 2}, - "url": match_pydantic_error_url("string_too_short"), } ] } @@ -494,7 +481,6 @@ def test_path_param_gt_2(): "msg": "Input should be greater than 3", "input": "2", "ctx": {"gt": 3.0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -531,7 +517,6 @@ def test_path_param_gt0_0(): "msg": "Input should be greater than 0", "input": "0", "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -574,7 +559,6 @@ def test_path_param_ge_2(): "msg": "Input should be greater than or equal to 3", "input": "2", "ctx": {"ge": 3.0}, - "url": match_pydantic_error_url("greater_than_equal"), } ] } @@ -605,7 +589,6 @@ def test_path_param_lt_42(): "msg": "Input should be less than 3", "input": "42", "ctx": {"lt": 3.0}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -648,7 +631,6 @@ def test_path_param_lt0_0(): "msg": "Input should be less than 0", "input": "0", "ctx": {"lt": 0.0}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -679,7 +661,6 @@ def test_path_param_le_42(): "msg": "Input should be less than or equal to 3", "input": "42", "ctx": {"le": 3.0}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -728,7 +709,6 @@ def test_path_param_lt_gt_4(): "msg": "Input should be less than 3", "input": "4", "ctx": {"lt": 3.0}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -759,7 +739,6 @@ def test_path_param_lt_gt_0(): "msg": "Input should be greater than 1", "input": "0", "ctx": {"gt": 1.0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -807,7 +786,6 @@ def test_path_param_le_ge_4(): "msg": "Input should be less than or equal to 3", "input": "4", "ctx": {"le": 3.0}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -844,7 +822,6 @@ def test_path_param_lt_int_42(): "msg": "Input should be less than 3", "input": "42", "ctx": {"lt": 3}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -874,7 +851,6 @@ def test_path_param_lt_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -910,7 +886,6 @@ def test_path_param_gt_int_2(): "msg": "Input should be greater than 3", "input": "2", "ctx": {"gt": 3}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -940,7 +915,6 @@ def test_path_param_gt_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -970,7 +944,6 @@ def test_path_param_le_int_42(): "msg": "Input should be less than or equal to 3", "input": "42", "ctx": {"le": 3}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -1012,7 +985,6 @@ def test_path_param_le_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -1054,7 +1026,6 @@ def test_path_param_ge_int_2(): "msg": "Input should be greater than or equal to 3", "input": "2", "ctx": {"ge": 3}, - "url": match_pydantic_error_url("greater_than_equal"), } ] } @@ -1084,7 +1055,6 @@ def test_path_param_ge_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -1120,7 +1090,6 @@ def test_path_param_lt_gt_int_4(): "msg": "Input should be less than 3", "input": "4", "ctx": {"lt": 3}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -1151,7 +1120,6 @@ def test_path_param_lt_gt_int_0(): "msg": "Input should be greater than 1", "input": "0", "ctx": {"gt": 1}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -1181,7 +1149,6 @@ def test_path_param_lt_gt_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -1229,7 +1196,6 @@ def test_path_param_le_ge_int_4(): "msg": "Input should be less than or equal to 3", "input": "4", "ctx": {"le": 3}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -1259,7 +1225,6 @@ def test_path_param_le_ge_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_query.py b/tests/test_query.py index 5bb9995d6..57f551d2a 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from .main import app @@ -18,7 +17,6 @@ def test_query(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -53,7 +51,6 @@ def test_query_not_declared_baz(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -100,7 +97,6 @@ def test_query_int(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -135,7 +131,6 @@ def test_query_int_query_42_5(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "42.5", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -164,7 +159,6 @@ def test_query_int_query_baz(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "baz", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -193,7 +187,6 @@ def test_query_int_not_declared_baz(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -234,7 +227,6 @@ def test_query_int_optional_query_foo(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -275,7 +267,6 @@ def test_query_int_default_query_foo(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -316,7 +307,6 @@ def test_query_param_required(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -351,7 +341,6 @@ def test_query_param_required_int(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -386,7 +375,6 @@ def test_query_param_required_int_query_foo(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -408,3 +396,26 @@ def test_query_frozenset_query_1_query_1_query_2(): response = client.get("/query/frozenset/?query=1&query=1&query=2") assert response.status_code == 200 assert response.json() == "1,2" + + +def test_query_list(): + response = client.get("/query/list/?device_ids=1&device_ids=2") + assert response.status_code == 200 + assert response.json() == [1, 2] + + +def test_query_list_empty(): + response = client.get("/query/list/") + assert response.status_code == 422 + + +def test_query_list_default(): + response = client.get("/query/list-default/?device_ids=1&device_ids=2") + assert response.status_code == 200 + assert response.json() == [1, 2] + + +def test_query_list_default_empty(): + response = client.get("/query/list-default/") + assert response.status_code == 200 + assert response.json() == [] diff --git a/tests/test_regex_deprecated_body.py b/tests/test_regex_deprecated_body.py index 7afddd9ae..74654ff3c 100644 --- a/tests/test_regex_deprecated_body.py +++ b/tests/test_regex_deprecated_body.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI, Form from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from typing_extensions import Annotated from .utils import needs_py310 @@ -55,7 +54,6 @@ def test_query_nonregexquery(): "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_regex_deprecated_params.py b/tests/test_regex_deprecated_params.py index 7190b543c..2ce64c686 100644 --- a/tests/test_regex_deprecated_params.py +++ b/tests/test_regex_deprecated_params.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI, Query from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from typing_extensions import Annotated from .utils import needs_py310 @@ -55,7 +54,6 @@ def test_query_params_str_validations_item_query_nonregexquery(): "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_router_events.py b/tests/test_router_events.py index 1b9de18ae..dd7ff3314 100644 --- a/tests/test_router_events.py +++ b/tests/test_router_events.py @@ -1,8 +1,8 @@ from contextlib import asynccontextmanager -from typing import AsyncGenerator, Dict +from typing import AsyncGenerator, Dict, Union import pytest -from fastapi import APIRouter, FastAPI +from fastapi import APIRouter, FastAPI, Request from fastapi.testclient import TestClient from pydantic import BaseModel @@ -109,3 +109,134 @@ def test_app_lifespan_state(state: State) -> None: assert response.json() == {"message": "Hello World"} assert state.app_startup is True assert state.app_shutdown is True + + +def test_router_nested_lifespan_state(state: State) -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.app_startup = True + yield {"app": True} + state.app_shutdown = True + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.router_startup = True + yield {"router": True} + state.router_shutdown = True + + @asynccontextmanager + async def subrouter_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.sub_router_startup = True + yield {"sub_router": True} + state.sub_router_shutdown = True + + sub_router = APIRouter(lifespan=subrouter_lifespan) + + router = APIRouter(lifespan=router_lifespan) + router.include_router(sub_router) + + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + @app.get("/") + def main(request: Request) -> Dict[str, str]: + assert request.state.app + assert request.state.router + assert request.state.sub_router + return {"message": "Hello World"} + + assert state.app_startup is False + assert state.router_startup is False + assert state.sub_router_startup is False + assert state.app_shutdown is False + assert state.router_shutdown is False + assert state.sub_router_shutdown is False + + with TestClient(app) as client: + assert state.app_startup is True + assert state.router_startup is True + assert state.sub_router_startup is True + assert state.app_shutdown is False + assert state.router_shutdown is False + assert state.sub_router_shutdown is False + response = client.get("/") + assert response.status_code == 200, response.text + assert response.json() == {"message": "Hello World"} + + assert state.app_startup is True + assert state.router_startup is True + assert state.sub_router_startup is True + assert state.app_shutdown is True + assert state.router_shutdown is True + assert state.sub_router_shutdown is True + + +def test_router_nested_lifespan_state_overriding_by_parent() -> None: + @asynccontextmanager + async def lifespan( + app: FastAPI, + ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]: + yield { + "app_specific": True, + "overridden": "app", + } + + @asynccontextmanager + async def router_lifespan( + app: FastAPI, + ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]: + yield { + "router_specific": True, + "overridden": "router", # should override parent + } + + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + with TestClient(app) as client: + assert client.app_state == { + "app_specific": True, + "router_specific": True, + "overridden": "app", + } + + +def test_merged_no_return_lifespans_return_none() -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + with TestClient(app) as client: + assert not client.app_state + + +def test_merged_mixed_state_lifespans() -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + yield {"router": True} + + @asynccontextmanager + async def sub_router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + sub_router = APIRouter(lifespan=sub_router_lifespan) + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + router.include_router(sub_router) + app.include_router(router) + + with TestClient(app) as client: + assert client.app_state == {"router": True} diff --git a/tests/test_security_oauth2.py b/tests/test_security_oauth2.py index e98f80ebf..7d914d034 100644 --- a/tests/test_security_oauth2.py +++ b/tests/test_security_oauth2.py @@ -2,7 +2,6 @@ from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -71,21 +70,18 @@ def test_strict_login_no_data(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -124,7 +120,6 @@ def test_strict_login_no_grant_type(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -157,7 +152,6 @@ def test_strict_login_incorrect_grant_type(): "msg": "String should match pattern 'password'", "input": "incorrect", "ctx": {"pattern": "password"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_security_oauth2_optional.py b/tests/test_security_oauth2_optional.py index d06c01bba..0da3b911e 100644 --- a/tests/test_security_oauth2_optional.py +++ b/tests/test_security_oauth2_optional.py @@ -4,7 +4,6 @@ from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -75,21 +74,18 @@ def test_strict_login_no_data(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -128,7 +124,6 @@ def test_strict_login_no_grant_type(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -161,7 +156,6 @@ def test_strict_login_incorrect_grant_type(): "msg": "String should match pattern 'password'", "input": "incorrect", "ctx": {"pattern": "password"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_security_oauth2_optional_description.py b/tests/test_security_oauth2_optional_description.py index 9287e4366..85a9f9b39 100644 --- a/tests/test_security_oauth2_optional_description.py +++ b/tests/test_security_oauth2_optional_description.py @@ -4,7 +4,6 @@ from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -76,21 +75,18 @@ def test_strict_login_None(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -129,7 +125,6 @@ def test_strict_login_no_grant_type(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -162,7 +157,6 @@ def test_strict_login_incorrect_grant_type(): "msg": "String should match pattern 'password'", "input": "incorrect", "ctx": {"pattern": "password"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_async_sql_databases/__init__.py b/tests/test_tutorial/test_async_sql_databases/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py deleted file mode 100644 index 13568a532..000000000 --- a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py +++ /dev/null @@ -1,146 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(name="app", scope="module") -def get_app(): - with pytest.warns(DeprecationWarning): - from docs_src.async_sql_databases.tutorial001 import app - yield app - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_read(app: FastAPI): - with TestClient(app) as client: - note = {"text": "Foo bar", "completed": False} - response = client.post("/notes/", json=note) - assert response.status_code == 200, response.text - data = response.json() - assert data["text"] == note["text"] - assert data["completed"] == note["completed"] - assert "id" in data - response = client.get("/notes/") - assert response.status_code == 200, response.text - assert data in response.json() - - -def test_openapi_schema(app: FastAPI): - with TestClient(app) as client: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/notes/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Notes Notes Get", - "type": "array", - "items": { - "$ref": "#/components/schemas/Note" - }, - } - } - }, - } - }, - "summary": "Read Notes", - "operationId": "read_notes_notes__get", - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Note"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Note", - "operationId": "create_note_notes__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/NoteIn"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "NoteIn": { - "title": "NoteIn", - "required": ["text", "completed"], - "type": "object", - "properties": { - "text": {"title": "Text", "type": "string"}, - "completed": {"title": "Completed", "type": "boolean"}, - }, - }, - "Note": { - "title": "Note", - "required": ["id", "text", "completed"], - "type": "object", - "properties": { - "id": {"title": "Id", "type": "integer"}, - "text": {"title": "Text", "type": "string"}, - "completed": {"title": "Completed", "type": "boolean"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": { - "$ref": "#/components/schemas/ValidationError" - }, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_bigger_applications/test_main.py b/tests/test_tutorial/test_bigger_applications/test_main.py index 526e265a6..35fdfa4a6 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main.py +++ b/tests/test_tutorial/test_bigger_applications/test_main.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -29,7 +28,6 @@ def test_users_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -64,7 +62,6 @@ def test_users_foo_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -99,7 +96,6 @@ def test_users_me_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -145,7 +141,6 @@ def test_items_with_no_token_jessica(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -192,7 +187,6 @@ def test_items_plumbus_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -233,7 +227,6 @@ def test_items_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -262,7 +255,6 @@ def test_items_plumbus_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -297,7 +289,6 @@ def test_root_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -326,14 +317,12 @@ def test_put_no_header(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an.py b/tests/test_tutorial/test_bigger_applications/test_main_an.py index c0b77d4a7..4e2e3e74d 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main_an.py +++ b/tests/test_tutorial/test_bigger_applications/test_main_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -29,7 +28,6 @@ def test_users_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -64,7 +62,6 @@ def test_users_foo_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -99,7 +96,6 @@ def test_users_me_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -145,7 +141,6 @@ def test_items_with_no_token_jessica(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -192,7 +187,6 @@ def test_items_plumbus_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -233,7 +227,6 @@ def test_items_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -262,7 +255,6 @@ def test_items_plumbus_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -297,7 +289,6 @@ def test_root_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -326,14 +317,12 @@ def test_put_no_header(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py b/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py index 948331b5d..8c9e976df 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py +++ b/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -33,7 +32,6 @@ def test_users_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -70,7 +68,6 @@ def test_users_foo_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -107,7 +104,6 @@ def test_users_me_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -156,7 +152,6 @@ def test_items_with_no_token_jessica(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -206,7 +201,6 @@ def test_items_plumbus_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -250,7 +244,6 @@ def test_items_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -280,7 +273,6 @@ def test_items_plumbus_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -317,7 +309,6 @@ def test_root_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -347,14 +338,12 @@ def test_put_no_header(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body/test_tutorial001.py b/tests/test_tutorial/test_body/test_tutorial001.py index 2476b773f..0d55d73eb 100644 --- a/tests/test_tutorial/test_body/test_tutorial001.py +++ b/tests/test_tutorial/test_body/test_tutorial001.py @@ -3,7 +3,6 @@ from unittest.mock import patch import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture @@ -74,7 +73,6 @@ def test_post_with_only_name(client: TestClient): "loc": ["body", "price"], "msg": "Field required", "input": {"name": "Foo"}, - "url": match_pydantic_error_url("missing"), } ] } @@ -103,7 +101,6 @@ def test_post_with_only_name_price(client: TestClient): "loc": ["body", "price"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "twenty", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -132,14 +129,12 @@ def test_post_with_no_data(client: TestClient): "loc": ["body", "name"], "msg": "Field required", "input": {}, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "price"], "msg": "Field required", "input": {}, - "url": match_pydantic_error_url("missing"), }, ] } @@ -173,7 +168,6 @@ def test_post_with_none(client: TestClient): "loc": ["body"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -244,7 +238,6 @@ def test_post_form_for_json(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": "name=Foo&price=50.5", - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -308,9 +301,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url( - "model_attributes_type" - ), # "https://errors.pydantic.dev/0.38.0/v/dict_attributes_type", } ] } @@ -339,7 +329,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -367,7 +356,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } diff --git a/tests/test_tutorial/test_body/test_tutorial001_py310.py b/tests/test_tutorial/test_body/test_tutorial001_py310.py index b64d86005..4b9c12806 100644 --- a/tests/test_tutorial/test_body/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_body/test_tutorial001_py310.py @@ -3,7 +3,6 @@ from unittest.mock import patch import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -81,7 +80,6 @@ def test_post_with_only_name(client: TestClient): "loc": ["body", "price"], "msg": "Field required", "input": {"name": "Foo"}, - "url": match_pydantic_error_url("missing"), } ] } @@ -111,7 +109,6 @@ def test_post_with_only_name_price(client: TestClient): "loc": ["body", "price"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "twenty", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -141,14 +138,12 @@ def test_post_with_no_data(client: TestClient): "loc": ["body", "name"], "msg": "Field required", "input": {}, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "price"], "msg": "Field required", "input": {}, - "url": match_pydantic_error_url("missing"), }, ] } @@ -183,7 +178,6 @@ def test_post_with_none(client: TestClient): "loc": ["body"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -256,7 +250,6 @@ def test_post_form_for_json(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": "name=Foo&price=50.5", - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -324,7 +317,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -353,7 +345,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -381,7 +372,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001.py b/tests/test_tutorial/test_body_fields/test_tutorial001.py index 1ff2d9576..fd6139eb9 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -57,7 +56,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an.py index 907d6842a..72c18c1f7 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -57,7 +56,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py index 431d2d181..1bc62868f 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -62,7 +61,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py index 8cef6c154..3c5557a1b 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -62,7 +61,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py index b48cd9ec2..8c1386aa6 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -62,7 +61,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py index e5dc13b26..6275ebe95 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -50,7 +49,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py index 51e8e3a4e..5cd3e2c4a 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -50,7 +49,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py index 8ac1f7261..0173ab21b 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -56,7 +55,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py index 7ada42c52..cda19918a 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -56,7 +55,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py index 0a832eaf6..663291933 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -56,7 +55,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py index 2046579a9..c26f8b89b 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -46,21 +45,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -99,21 +95,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py index 1282483e0..62c7e2fad 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -46,21 +45,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -99,21 +95,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py index 577c079d0..f46430fb5 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -50,21 +49,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -104,21 +100,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py index 0ec04151c..29071cddc 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -50,21 +49,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -104,21 +100,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py index 9caf5fe6c..133afe9b5 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -50,21 +49,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -104,21 +100,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py index f4a76be44..762073aea 100644 --- a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py +++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -31,7 +30,6 @@ def test_post_invalid_body(client: TestClient): "loc": ["body", "foo", "[key]"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py index 8ab9bcac8..24623cecc 100644 --- a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py +++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -35,7 +34,6 @@ def test_post_invalid_body(client: TestClient): "loc": ["body", "foo", "[key]"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/docs_src/sql_databases/sql_app/__init__.py b/tests/test_tutorial/test_cookie_param_models/__init__.py similarity index 100% rename from docs_src/sql_databases/sql_app/__init__.py rename to tests/test_tutorial/test_cookie_param_models/__init__.py diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py new file mode 100644 index 000000000..60643185a --- /dev/null +++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py @@ -0,0 +1,205 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.cookie_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_cookie_param_model(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("fatebook_tracker", "456") + c.cookies.set("googall_tracker", "789") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": "456", + "googall_tracker": "789", + } + + +def test_cookie_param_model_defaults(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": None, + "googall_tracker": None, + } + + +def test_cookie_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["cookie", "session_id"], + "msg": "Field required", + "input": {}, + } + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.missing", + "loc": ["cookie", "session_id"], + "msg": "field required", + } + ] + } + ) + ) + + +def test_cookie_param_model_extra(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("extra", "track-me-here-too") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == snapshot( + {"session_id": "123", "fatebook_tracker": None, "googall_tracker": None} + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "session_id", + "in": "cookie", + "required": True, + "schema": {"type": "string", "title": "Session Id"}, + }, + { + "name": "fatebook_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Fatebook Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Fatebook Tracker", + } + ), + }, + { + "name": "googall_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Googall Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Googall Tracker", + } + ), + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py new file mode 100644 index 000000000..30adadc8a --- /dev/null +++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py @@ -0,0 +1,233 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial002", marks=needs_pydanticv2), + pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_an", marks=needs_pydanticv2), + pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.cookie_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_cookie_param_model(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("fatebook_tracker", "456") + c.cookies.set("googall_tracker", "789") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": "456", + "googall_tracker": "789", + } + + +def test_cookie_param_model_defaults(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": None, + "googall_tracker": None, + } + + +def test_cookie_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["cookie", "session_id"], + "msg": "Field required", + "input": {}, + } + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.missing", + "loc": ["cookie", "session_id"], + "msg": "field required", + } + ] + } + ) + ) + + +def test_cookie_param_model_extra(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("extra", "track-me-here-too") + response = c.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "extra"], + "msg": "Extra inputs are not permitted", + "input": "track-me-here-too", + } + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.extra", + "loc": ["cookie", "extra"], + "msg": "extra fields not permitted", + } + ] + } + ) + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "session_id", + "in": "cookie", + "required": True, + "schema": {"type": "string", "title": "Session Id"}, + }, + { + "name": "fatebook_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Fatebook Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Fatebook Tracker", + } + ), + }, + { + "name": "googall_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Googall Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Googall Tracker", + } + ), + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py index 34a18b12c..aff070d74 100644 --- a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py +++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py @@ -20,10 +20,8 @@ def client(): def test_swagger_ui_html(client: TestClient): response = client.get("/docs") assert response.status_code == 200, response.text - assert ( - "https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-bundle.js" in response.text - ) - assert "https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css" in response.text + assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js" in response.text + assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" in response.text def test_swagger_ui_oauth2_redirect_html(client: TestClient): diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py index ad142ec88..6f7355aaa 100644 --- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py +++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.custom_request_and_route.tutorial002 import app @@ -23,7 +22,6 @@ def test_exception_handler_body_access(): "loc": ["body"], "msg": "Input should be a valid list", "input": {"numbers": [1, 2, 3]}, - "url": match_pydantic_error_url("list_type"), } ], "body": '{"numbers": [1, 2, 3]}', diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial001.py b/tests/test_tutorial/test_dataclasses/test_tutorial001.py index 9f1200f37..762654d29 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial001.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial001.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dataclasses.tutorial001 import app @@ -29,7 +28,6 @@ def test_post_invalid_item(): "loc": ["body", "price"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "invalid price", - "url": match_pydantic_error_url("float_parsing"), } ] } diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial002.py b/tests/test_tutorial/test_dataclasses/test_tutorial002.py index 4146f4cd6..e6d303cfc 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial002.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial002.py @@ -12,7 +12,7 @@ def test_get_item(): assert response.json() == { "name": "Island In The Moon", "price": 12.99, - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", "tags": ["breater"], "tax": None, } diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial003.py b/tests/test_tutorial/test_dataclasses/test_tutorial003.py index dd0e36735..e1fa45201 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial003.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial003.py @@ -31,7 +31,7 @@ def test_get_authors(): "items": [ { "name": "Island In The Moon", - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", }, {"name": "Holy Buddies", "description": None}, ], diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006.py b/tests/test_tutorial/test_dependencies/test_tutorial006.py index 704e389a5..5f14d9a3b 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial006 import app @@ -18,14 +17,12 @@ def test_get_no_headers(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an.py index 5034fceba..a307ff808 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006_an.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial006_an import app @@ -18,14 +17,12 @@ def test_get_no_headers(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py index 3fc22dd3c..b41b1537e 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -26,14 +25,12 @@ def test_get_no_headers(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012.py b/tests/test_tutorial/test_dependencies/test_tutorial012.py index 753e62e43..6b53c83bb 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial012 import app @@ -18,14 +17,12 @@ def test_get_no_headers_items(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -59,14 +56,12 @@ def test_get_no_headers_users(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an.py index 4157d4612..75adb69fc 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012_an.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dependencies.tutorial012_an import app @@ -18,14 +17,12 @@ def test_get_no_headers_items(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -59,14 +56,12 @@ def test_get_no_headers_users(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py index 9e46758cb..e0a3d1ec2 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -26,14 +25,12 @@ def test_get_no_headers_items(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -68,14 +65,12 @@ def test_get_no_headers_users(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py index 7710446ce..5558671b9 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py @@ -67,6 +67,7 @@ def test_openapi_schema(): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -86,7 +87,7 @@ def test_openapi_schema(): } ) } - } + }, }, } } @@ -97,40 +98,16 @@ def test_openapi_schema(): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -151,10 +128,8 @@ def test_openapi_schema(): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -166,6 +141,7 @@ def test_openapi_schema(): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py index 9951b3b51..e309f8bd6 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py @@ -67,6 +67,7 @@ def test_openapi_schema(): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -86,7 +87,7 @@ def test_openapi_schema(): } ) } - } + }, }, } } @@ -97,40 +98,16 @@ def test_openapi_schema(): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -151,10 +128,8 @@ def test_openapi_schema(): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -166,6 +141,7 @@ def test_openapi_schema(): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py index 7c482b8cb..ca110dc00 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py @@ -76,6 +76,7 @@ def test_openapi_schema(client: TestClient): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -95,7 +96,7 @@ def test_openapi_schema(client: TestClient): } ) } - } + }, }, } } @@ -106,40 +107,16 @@ def test_openapi_schema(client: TestClient): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -160,10 +137,8 @@ def test_openapi_schema(client: TestClient): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -175,6 +150,7 @@ def test_openapi_schema(client: TestClient): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py index 87473867b..3386fb1fd 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py @@ -76,6 +76,7 @@ def test_openapi_schema(client: TestClient): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -95,7 +96,7 @@ def test_openapi_schema(client: TestClient): } ) } - } + }, }, } } @@ -106,40 +107,16 @@ def test_openapi_schema(client: TestClient): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -160,10 +137,8 @@ def test_openapi_schema(client: TestClient): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -175,6 +150,7 @@ def test_openapi_schema(client: TestClient): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py index 0b71d9177..50c9aefdf 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py @@ -76,6 +76,7 @@ def test_openapi_schema(client: TestClient): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -95,7 +96,7 @@ def test_openapi_schema(client: TestClient): } ) } - } + }, }, } } @@ -106,40 +107,16 @@ def test_openapi_schema(client: TestClient): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -160,10 +137,8 @@ def test_openapi_schema(client: TestClient): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -175,6 +150,7 @@ def test_openapi_schema(client: TestClient): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial005.py b/tests/test_tutorial/test_handling_errors/test_tutorial005.py index 494c317ca..581b2e4c7 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial005.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial005.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.handling_errors.tutorial005 import app @@ -18,7 +17,6 @@ def test_post_validation_error(): "loc": ["body", "size"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "XL", - "url": match_pydantic_error_url("int_parsing"), } ], "body": {"title": "towel", "size": "XL"}, diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial006.py b/tests/test_tutorial/test_handling_errors/test_tutorial006.py index cc2b496a8..7d2f553aa 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial006.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial006.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.handling_errors.tutorial006 import app @@ -18,7 +17,6 @@ def test_get_validation_error(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/docs_src/sql_databases/sql_app/tests/__init__.py b/tests/test_tutorial/test_header_param_models/__init__.py similarity index 100% rename from docs_src/sql_databases/sql_app/tests/__init__.py rename to tests/test_tutorial/test_header_param_models/__init__.py diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial001.py b/tests/test_tutorial/test_header_param_models/test_tutorial001.py new file mode 100644 index 000000000..06b2404cf --- /dev/null +++ b/tests/test_tutorial/test_header_param_models/test_tutorial001.py @@ -0,0 +1,238 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py39", marks=needs_py39), + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_header_param_model(client: TestClient): + response = client.get( + "/items/", + headers=[ + ("save-data", "true"), + ("if-modified-since", "yesterday"), + ("traceparent", "123"), + ("x-tag", "one"), + ("x-tag", "two"), + ], + ) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": "yesterday", + "traceparent": "123", + "x_tag": ["one", "two"], + } + + +def test_header_param_model_defaults(client: TestClient): + response = client.get("/items/", headers=[("save-data", "true")]) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + + +def test_header_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "missing", + "loc": ["header", "save_data"], + "msg": "Field required", + "input": { + "x_tag": [], + "host": "testserver", + "accept": "*/*", + "accept-encoding": "gzip, deflate", + "connection": "keep-alive", + "user-agent": "testclient", + }, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.missing", + "loc": ["header", "save_data"], + "msg": "field required", + } + ) + ] + } + ) + + +def test_header_param_model_extra(client: TestClient): + response = client.get( + "/items/", headers=[("save-data", "true"), ("tool", "plumbus")] + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "host", + "in": "header", + "required": True, + "schema": {"type": "string", "title": "Host"}, + }, + { + "name": "save_data", + "in": "header", + "required": True, + "schema": {"type": "boolean", "title": "Save Data"}, + }, + { + "name": "if_modified_since", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "If Modified Since", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "If Modified Since", + } + ), + }, + { + "name": "traceparent", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Traceparent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Traceparent", + } + ), + }, + { + "name": "x_tag", + "in": "header", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "X Tag", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial002.py b/tests/test_tutorial/test_header_param_models/test_tutorial002.py new file mode 100644 index 000000000..e07655a0c --- /dev/null +++ b/tests/test_tutorial/test_header_param_models/test_tutorial002.py @@ -0,0 +1,249 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial002", marks=needs_pydanticv2), + pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_an", marks=needs_pydanticv2), + pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_param_models.{request.param}") + + client = TestClient(mod.app) + client.headers.clear() + return client + + +def test_header_param_model(client: TestClient): + response = client.get( + "/items/", + headers=[ + ("save-data", "true"), + ("if-modified-since", "yesterday"), + ("traceparent", "123"), + ("x-tag", "one"), + ("x-tag", "two"), + ], + ) + assert response.status_code == 200, response.text + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": "yesterday", + "traceparent": "123", + "x_tag": ["one", "two"], + } + + +def test_header_param_model_defaults(client: TestClient): + response = client.get("/items/", headers=[("save-data", "true")]) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + + +def test_header_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "missing", + "loc": ["header", "save_data"], + "msg": "Field required", + "input": {"x_tag": [], "host": "testserver"}, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.missing", + "loc": ["header", "save_data"], + "msg": "field required", + } + ) + ] + } + ) + + +def test_header_param_model_extra(client: TestClient): + response = client.get( + "/items/", headers=[("save-data", "true"), ("tool", "plumbus")] + ) + assert response.status_code == 422, response.text + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.extra", + "loc": ["header", "tool"], + "msg": "extra fields not permitted", + } + ) + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "host", + "in": "header", + "required": True, + "schema": {"type": "string", "title": "Host"}, + }, + { + "name": "save_data", + "in": "header", + "required": True, + "schema": {"type": "boolean", "title": "Save Data"}, + }, + { + "name": "if_modified_since", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "If Modified Since", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "If Modified Since", + } + ), + }, + { + "name": "traceparent", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Traceparent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Traceparent", + } + ), + }, + { + "name": "x_tag", + "in": "header", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "X Tag", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py index 2d2802269..8240b60a6 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py @@ -1,6 +1,5 @@ import pytest from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_pydanticv2 @@ -64,7 +63,6 @@ def test_post_invalid(client: TestClient): "loc": ["tags", 3], "msg": "Input should be a valid string", "input": {"sneaky": "object"}, - "url": match_pydantic_error_url("string_type"), } ] } diff --git a/docs_src/sql_databases/sql_app_py310/__init__.py b/tests/test_tutorial/test_query_param_models/__init__.py similarity index 100% rename from docs_src/sql_databases/sql_app_py310/__init__.py rename to tests/test_tutorial/test_query_param_models/__init__.py diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial001.py b/tests/test_tutorial/test_query_param_models/test_tutorial001.py new file mode 100644 index 000000000..5b7bc7b42 --- /dev/null +++ b/tests/test_tutorial/test_query_param_models/test_tutorial001.py @@ -0,0 +1,260 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py39", marks=needs_py39), + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.query_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_query_param_model(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + }, + ) + assert response.status_code == 200 + assert response.json() == { + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + } + + +def test_query_param_model_defaults(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "limit": 100, + "offset": 0, + "order_by": "created_at", + "tags": [], + } + + +def test_query_param_model_invalid(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 150, + "offset": -1, + "order_by": "invalid", + }, + ) + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "less_than_equal", + "loc": ["query", "limit"], + "msg": "Input should be less than or equal to 100", + "input": "150", + "ctx": {"le": 100}, + }, + { + "type": "greater_than_equal", + "loc": ["query", "offset"], + "msg": "Input should be greater than or equal to 0", + "input": "-1", + "ctx": {"ge": 0}, + }, + { + "type": "literal_error", + "loc": ["query", "order_by"], + "msg": "Input should be 'created_at' or 'updated_at'", + "input": "invalid", + "ctx": {"expected": "'created_at' or 'updated_at'"}, + }, + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.number.not_le", + "loc": ["query", "limit"], + "msg": "ensure this value is less than or equal to 100", + "ctx": {"limit_value": 100}, + }, + { + "type": "value_error.number.not_ge", + "loc": ["query", "offset"], + "msg": "ensure this value is greater than or equal to 0", + "ctx": {"limit_value": 0}, + }, + { + "type": "value_error.const", + "loc": ["query", "order_by"], + "msg": "unexpected value; permitted: 'created_at', 'updated_at'", + "ctx": { + "given": "invalid", + "permitted": ["created_at", "updated_at"], + }, + }, + ] + } + ) + ) + + +def test_query_param_model_extra(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + "tool": "plumbus", + }, + ) + assert response.status_code == 200 + assert response.json() == { + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + } + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "exclusiveMinimum": 0, + "default": 100, + "title": "Limit", + }, + }, + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "minimum": 0, + "default": 0, + "title": "Offset", + }, + }, + { + "name": "order_by", + "in": "query", + "required": False, + "schema": { + "enum": ["created_at", "updated_at"], + "type": "string", + "default": "created_at", + "title": "Order By", + }, + }, + { + "name": "tags", + "in": "query", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "Tags", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial002.py b/tests/test_tutorial/test_query_param_models/test_tutorial002.py new file mode 100644 index 000000000..4432c9d8a --- /dev/null +++ b/tests/test_tutorial/test_query_param_models/test_tutorial002.py @@ -0,0 +1,282 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial002", marks=needs_pydanticv2), + pytest.param("tutorial002_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_an", marks=needs_pydanticv2), + pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.query_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_query_param_model(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + }, + ) + assert response.status_code == 200 + assert response.json() == { + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + } + + +def test_query_param_model_defaults(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "limit": 100, + "offset": 0, + "order_by": "created_at", + "tags": [], + } + + +def test_query_param_model_invalid(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 150, + "offset": -1, + "order_by": "invalid", + }, + ) + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "less_than_equal", + "loc": ["query", "limit"], + "msg": "Input should be less than or equal to 100", + "input": "150", + "ctx": {"le": 100}, + }, + { + "type": "greater_than_equal", + "loc": ["query", "offset"], + "msg": "Input should be greater than or equal to 0", + "input": "-1", + "ctx": {"ge": 0}, + }, + { + "type": "literal_error", + "loc": ["query", "order_by"], + "msg": "Input should be 'created_at' or 'updated_at'", + "input": "invalid", + "ctx": {"expected": "'created_at' or 'updated_at'"}, + }, + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.number.not_le", + "loc": ["query", "limit"], + "msg": "ensure this value is less than or equal to 100", + "ctx": {"limit_value": 100}, + }, + { + "type": "value_error.number.not_ge", + "loc": ["query", "offset"], + "msg": "ensure this value is greater than or equal to 0", + "ctx": {"limit_value": 0}, + }, + { + "type": "value_error.const", + "loc": ["query", "order_by"], + "msg": "unexpected value; permitted: 'created_at', 'updated_at'", + "ctx": { + "given": "invalid", + "permitted": ["created_at", "updated_at"], + }, + }, + ] + } + ) + ) + + +def test_query_param_model_extra(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + "tool": "plumbus", + }, + ) + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.extra", + "loc": ["query", "tool"], + "msg": "extra fields not permitted", + } + ) + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "exclusiveMinimum": 0, + "default": 100, + "title": "Limit", + }, + }, + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "minimum": 0, + "default": 0, + "title": "Offset", + }, + }, + { + "name": "order_by", + "in": "query", + "required": False, + "schema": { + "enum": ["created_at", "updated_at"], + "type": "string", + "default": "created_at", + "title": "Order By", + }, + }, + { + "name": "tags", + "in": "query", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "Tags", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_query_params/test_tutorial005.py b/tests/test_tutorial/test_query_params/test_tutorial005.py index 921586357..05ae85b45 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial005.py +++ b/tests/test_tutorial/test_query_params/test_tutorial005.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.query_params.tutorial005 import app @@ -24,7 +23,6 @@ def test_foo_no_needy(): "loc": ["query", "needy"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_query_params/test_tutorial006.py b/tests/test_tutorial/test_query_params/test_tutorial006.py index e07803d6c..dbd63da16 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial006.py +++ b/tests/test_tutorial/test_query_params/test_tutorial006.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -34,21 +33,18 @@ def test_foo_no_needy(client: TestClient): "loc": ["query", "needy"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "int_parsing", "loc": ["query", "skip"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "a", - "url": match_pydantic_error_url("int_parsing"), }, { "type": "int_parsing", "loc": ["query", "limit"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "b", - "url": match_pydantic_error_url("int_parsing"), }, ] } diff --git a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py b/tests/test_tutorial/test_query_params/test_tutorial006_py310.py index 6c4c0b4dc..5055e3805 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py +++ b/tests/test_tutorial/test_query_params/test_tutorial006_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -38,21 +37,18 @@ def test_foo_no_needy(client: TestClient): "loc": ["query", "needy"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "int_parsing", "loc": ["query", "skip"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "a", - "url": match_pydantic_error_url("int_parsing"), }, { "type": "int_parsing", "loc": ["query", "limit"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "b", - "url": match_pydantic_error_url("int_parsing"), }, ] } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py index 287c2e8f8..945cee3d2 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -45,7 +44,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py index 5b0515070..23951a9aa 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -45,7 +44,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py index d22b1ce20..2968af563 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -51,7 +50,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py index 3e7d5d3ad..534ba8759 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -51,7 +50,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py index 1c3a09d39..886bceca2 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py310 @@ -51,7 +50,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001.py b/tests/test_tutorial/test_request_files/test_tutorial001.py index 91cc2b636..f5817593b 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial001 import app @@ -29,7 +28,6 @@ def test_post_form_no_body(): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -58,7 +56,6 @@ def test_post_body_json(): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_an.py index 3021eb3c3..1c78e3679 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_an.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_an.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial001_an import app @@ -18,7 +17,6 @@ def test_post_form_no_body(): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -47,7 +45,6 @@ def test_post_body_json(): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py index 04f3a4693..843fcec28 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -26,7 +25,6 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -56,7 +54,6 @@ def test_post_body_json(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial002.py b/tests/test_tutorial/test_request_files/test_tutorial002.py index ed9680b62..db1552e5c 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial002 import app @@ -18,7 +17,6 @@ def test_post_form_no_body(): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -47,7 +45,6 @@ def test_post_body_json(): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_an.py b/tests/test_tutorial/test_request_files/test_tutorial002_an.py index ea8c1216c..b16da1669 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002_an.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002_an.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.request_files.tutorial002_an import app @@ -18,7 +17,6 @@ def test_post_form_no_body(): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -47,7 +45,6 @@ def test_post_body_json(): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py index 6d5877836..e092a516d 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -32,7 +31,6 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -62,7 +60,6 @@ def test_post_body_json(client: TestClient): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_request_files/test_tutorial002_py39.py b/tests/test_tutorial/test_request_files/test_tutorial002_py39.py index 2d0445421..341a9ac8e 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002_py39.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002_py39.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -43,7 +42,6 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -73,7 +71,6 @@ def test_post_body_json(client: TestClient): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/docs_src/sql_databases/sql_app_py310/tests/__init__.py b/tests/test_tutorial/test_request_form_models/__init__.py similarity index 100% rename from docs_src/sql_databases/sql_app_py310/tests/__init__.py rename to tests/test_tutorial/test_request_form_models/__init__.py diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001.py b/tests/test_tutorial/test_request_form_models/test_tutorial001.py new file mode 100644 index 000000000..46c130ee8 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001.py @@ -0,0 +1,232 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial001 import app + + client = TestClient(app) + return client + + +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py new file mode 100644 index 000000000..4e14d89c8 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py @@ -0,0 +1,232 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial001_an import app + + client = TestClient(app) + return client + + +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py new file mode 100644 index 000000000..2e6426aa7 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py @@ -0,0 +1,240 @@ +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient + +from tests.utils import needs_py39 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial001_an_py39 import app + + client = TestClient(app) + return client + + +@needs_py39 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_py39 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +@needs_py39 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + } + ] + } + ) + + +@needs_py39 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "password"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) + + +@needs_py39 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002.py b/tests/test_tutorial/test_request_form_models/test_tutorial002.py new file mode 100644 index 000000000..76f480001 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002.py @@ -0,0 +1,196 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002 import app + + client = TestClient(app) + return client + + +@needs_pydanticv2 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_pydanticv2 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "extra", + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py new file mode 100644 index 000000000..179b2977d --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py @@ -0,0 +1,196 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002_an import app + + client = TestClient(app) + return client + + +@needs_pydanticv2 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_pydanticv2 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "extra", + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + + +@needs_pydanticv2 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py new file mode 100644 index 000000000..510ad9d7c --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py @@ -0,0 +1,203 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_py39, needs_pydanticv2 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002_an_py39 import app + + client = TestClient(app) + return client + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "extra", + } + ] + } + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {"username": "Foo"}, + } + ] + } + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"password": "secret"}, + } + ] + } + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +@needs_py39 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {}, + }, + { + "type": "missing", + "loc": ["body", "password"], + "msg": "Field required", + "input": {}, + }, + ] + } + + +@needs_pydanticv2 +@needs_py39 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py new file mode 100644 index 000000000..249b9379d --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py @@ -0,0 +1,189 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_pydanticv1 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002_pv1 import app + + client = TestClient(app) + return client + + +@needs_pydanticv1 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +@needs_pydanticv1 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.extra", + "loc": ["body", "extra"], + "msg": "extra fields not permitted", + } + ] + } + + +@needs_pydanticv1 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + } + ] + } + + +@needs_pydanticv1 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + } + ] + } + + +@needs_pydanticv1 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +@needs_pydanticv1 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py new file mode 100644 index 000000000..44cb3c32b --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py @@ -0,0 +1,196 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_pydanticv1 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002_pv1_an import app + + client = TestClient(app) + return client + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.extra", + "loc": ["body", "extra"], + "msg": "extra fields not permitted", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py new file mode 100644 index 000000000..899549e40 --- /dev/null +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py @@ -0,0 +1,203 @@ +import pytest +from fastapi.testclient import TestClient + +from tests.utils import needs_py39, needs_pydanticv1 + + +@pytest.fixture(name="client") +def get_client(): + from docs_src.request_form_models.tutorial002_pv1_an_py39 import app + + client = TestClient(app) + return client + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_form(client: TestClient): + response = client.post("/login/", data={"username": "Foo", "password": "secret"}) + assert response.status_code == 200 + assert response.json() == {"username": "Foo", "password": "secret"} + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_extra_form(client: TestClient): + response = client.post( + "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} + ) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.extra", + "loc": ["body", "extra"], + "msg": "extra fields not permitted", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_form_no_password(client: TestClient): + response = client.post("/login/", data={"username": "Foo"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_form_no_username(client: TestClient): + response = client.post("/login/", data={"password": "secret"}) + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + } + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_form_no_data(client: TestClient): + response = client.post("/login/") + assert response.status_code == 422 + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_post_body_json(client: TestClient): + response = client.post("/login/", json={"username": "Foo", "password": "secret"}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": [ + { + "type": "value_error.missing", + "loc": ["body", "username"], + "msg": "field required", + }, + { + "type": "value_error.missing", + "loc": ["body", "password"], + "msg": "field required", + }, + ] + } + + +# TODO: remove when deprecating Pydantic v1 +@needs_pydanticv1 +@needs_py39 +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/login/": { + "post": { + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + "summary": "Login", + "operationId": "login_login__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": {"$ref": "#/components/schemas/FormData"} + } + }, + "required": True, + }, + } + } + }, + "components": { + "schemas": { + "FormData": { + "properties": { + "username": {"type": "string", "title": "Username"}, + "password": {"type": "string", "title": "Password"}, + }, + "additionalProperties": False, + "type": "object", + "required": ["username", "password"], + "title": "FormData", + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + } + }, + } diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001.py b/tests/test_tutorial/test_request_forms/test_tutorial001.py index 805daeb10..cbef9d30f 100644 --- a/tests/test_tutorial/test_request_forms/test_tutorial001.py +++ b/tests/test_tutorial/test_request_forms/test_tutorial001.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -29,7 +28,6 @@ def test_post_body_form_no_password(client: TestClient): "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -58,7 +56,6 @@ def test_post_body_form_no_username(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -87,14 +84,12 @@ def test_post_body_form_no_data(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -128,14 +123,12 @@ def test_post_body_json(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001_an.py b/tests/test_tutorial/test_request_forms/test_tutorial001_an.py index c43a0b695..88b8452bc 100644 --- a/tests/test_tutorial/test_request_forms/test_tutorial001_an.py +++ b/tests/test_tutorial/test_request_forms/test_tutorial001_an.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="client") @@ -29,7 +28,6 @@ def test_post_body_form_no_password(client: TestClient): "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -58,7 +56,6 @@ def test_post_body_form_no_username(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -87,14 +84,12 @@ def test_post_body_form_no_data(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -128,14 +123,12 @@ def test_post_body_json(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py index 078b812aa..3229897c9 100644 --- a/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py @@ -1,7 +1,6 @@ import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -33,7 +32,6 @@ def test_post_body_form_no_password(client: TestClient): "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -63,7 +61,6 @@ def test_post_body_form_no_username(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -93,14 +90,12 @@ def test_post_body_form_no_data(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -135,14 +130,12 @@ def test_post_body_json(client: TestClient): "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py index cac58639f..1e1ad2a87 100644 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py +++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="app") @@ -29,21 +28,18 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -82,14 +78,12 @@ def test_post_form_no_file(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -123,21 +117,18 @@ def test_post_body_json(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -181,14 +172,12 @@ def test_post_file_no_token(tmp_path, app: FastAPI): "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py index 009568048..5daf4dbf4 100644 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py +++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url @pytest.fixture(name="app") @@ -29,21 +28,18 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -82,14 +78,12 @@ def test_post_form_no_file(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -123,21 +117,18 @@ def test_post_body_json(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -181,14 +172,12 @@ def test_post_file_no_token(tmp_path, app: FastAPI): "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py index 3d007e90b..3f1204efa 100644 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py +++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_py39 @@ -32,21 +31,18 @@ def test_post_form_no_body(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -86,14 +82,12 @@ def test_post_form_no_file(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -128,21 +122,18 @@ def test_post_body_json(client: TestClient): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -187,14 +178,12 @@ def test_post_file_no_token(tmp_path, app: FastAPI): "loc": ["body", "fileb"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py similarity index 98% rename from tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py rename to tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py index e036d6b68..b2a4d15b1 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py @@ -6,7 +6,7 @@ from ...utils import needs_py310, needs_pydanticv1 @pytest.fixture(name="client") def get_client(): - from docs_src.schema_extra_example.tutorial001_py310_pv1 import app + from docs_src.schema_extra_example.tutorial001_pv1_py310 import app client = TestClient(app) return client diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases.py b/tests/test_tutorial/test_sql_databases/test_sql_databases.py deleted file mode 100644 index e3e2b36a8..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases.py +++ /dev/null @@ -1,419 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py deleted file mode 100644 index 73b97e09d..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py +++ /dev/null @@ -1,421 +0,0 @@ -import importlib -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(): - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py deleted file mode 100644 index a078f012a..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py +++ /dev/null @@ -1,433 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310 import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py deleted file mode 100644 index a5da07ac6..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py +++ /dev/null @@ -1,433 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39 import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py deleted file mode 100644 index 5a9106598..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py +++ /dev/null @@ -1,432 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(scope="module", name="client") -def get_client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310 import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py deleted file mode 100644 index a354ba905..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py +++ /dev/null @@ -1,432 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1 - - -@pytest.fixture(scope="module", name="client") -def get_client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39 import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py39 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py39 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases.py b/tests/test_tutorial/test_sql_databases/test_testing_databases.py deleted file mode 100644 index ce6ce230c..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases.py +++ /dev/null @@ -1,27 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_pydanticv1 - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py deleted file mode 100644 index 545d63c2a..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py +++ /dev/null @@ -1,28 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_py310, needs_pydanticv1 - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py deleted file mode 100644 index 99bfd3fa8..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py +++ /dev/null @@ -1,28 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_py39, needs_pydanticv1 - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_sql_databases/test_tutorial001.py new file mode 100644 index 000000000..cc7e590df --- /dev/null +++ b/tests/test_tutorial/test_sql_databases/test_tutorial001.py @@ -0,0 +1,373 @@ +import importlib +import warnings + +import pytest +from dirty_equals import IsDict, IsInt +from fastapi.testclient import TestClient +from inline_snapshot import snapshot +from sqlalchemy import StaticPool +from sqlmodel import SQLModel, create_engine +from sqlmodel.main import default_registry + +from tests.utils import needs_py39, needs_py310 + + +def clear_sqlmodel(): + # Clear the tables in the metadata for the default base model + SQLModel.metadata.clear() + # Clear the Models associated with the registry, to avoid warnings + default_registry.dispose() + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py39", marks=needs_py39), + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + clear_sqlmodel() + # TODO: remove when updating SQL tutorial to use new lifespan API + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + mod = importlib.import_module(f"docs_src.sql_databases.{request.param}") + clear_sqlmodel() + importlib.reload(mod) + mod.sqlite_url = "sqlite://" + mod.engine = create_engine( + mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool + ) + + with TestClient(mod.app) as c: + yield c + + +def test_crud_app(client: TestClient): + # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor + # this if using obj.model_validate becomes independent of Pydantic v2 + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + # No heroes before creating + response = client.get("heroes/") + assert response.status_code == 200, response.text + assert response.json() == [] + + # Create a hero + response = client.post( + "/heroes/", + json={ + "id": 999, + "name": "Dead Pond", + "age": 30, + "secret_name": "Dive Wilson", + }, + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"age": 30, "secret_name": "Dive Wilson", "id": 999, "name": "Dead Pond"} + ) + + # Read a hero + hero_id = response.json()["id"] + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dead Pond", "age": 30, "id": 999, "secret_name": "Dive Wilson"} + ) + + # Read all heroes + # Create more heroes first + response = client.post( + "/heroes/", + json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"}, + ) + assert response.status_code == 200, response.text + response = client.post( + "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"} + ) + assert response.status_code == 200, response.text + + response = client.get("/heroes/") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + { + "name": "Dead Pond", + "age": 30, + "id": IsInt(), + "secret_name": "Dive Wilson", + }, + { + "name": "Spider-Boy", + "age": 18, + "id": IsInt(), + "secret_name": "Pedro Parqueador", + }, + { + "name": "Rusty-Man", + "age": None, + "id": IsInt(), + "secret_name": "Tommy Sharp", + }, + ] + ) + + response = client.get("/heroes/?offset=1&limit=1") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + { + "name": "Spider-Boy", + "age": 18, + "id": IsInt(), + "secret_name": "Pedro Parqueador", + } + ] + ) + + # Delete a hero + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot({"ok": True}) + + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/heroes/": { + "post": { + "summary": "Create Hero", + "operationId": "create_hero_heroes__post", + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "get": { + "summary": "Read Heroes", + "operationId": "read_heroes_heroes__get", + "parameters": [ + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "default": 0, + "title": "Offset", + }, + }, + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "default": 100, + "title": "Limit", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hero" + }, + "title": "Response Read Heroes Heroes Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + "/heroes/{hero_id}": { + "get": { + "summary": "Read Hero", + "operationId": "read_hero_heroes__hero_id__get", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "delete": { + "summary": "Delete Hero", + "operationId": "delete_hero_heroes__hero_id__delete", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Hero": { + "properties": { + "id": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Id", + } + ), + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": {"type": "string", "title": "Secret Name"}, + }, + "type": "object", + "required": ["name", "secret_name"], + "title": "Hero", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial002.py b/tests/test_tutorial/test_sql_databases/test_tutorial002.py new file mode 100644 index 000000000..68c1966f5 --- /dev/null +++ b/tests/test_tutorial/test_sql_databases/test_tutorial002.py @@ -0,0 +1,481 @@ +import importlib +import warnings + +import pytest +from dirty_equals import IsDict, IsInt +from fastapi.testclient import TestClient +from inline_snapshot import snapshot +from sqlalchemy import StaticPool +from sqlmodel import SQLModel, create_engine +from sqlmodel.main import default_registry + +from tests.utils import needs_py39, needs_py310 + + +def clear_sqlmodel(): + # Clear the tables in the metadata for the default base model + SQLModel.metadata.clear() + # Clear the Models associated with the registry, to avoid warnings + default_registry.dispose() + + +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py39", marks=needs_py39), + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + clear_sqlmodel() + # TODO: remove when updating SQL tutorial to use new lifespan API + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + mod = importlib.import_module(f"docs_src.sql_databases.{request.param}") + clear_sqlmodel() + importlib.reload(mod) + mod.sqlite_url = "sqlite://" + mod.engine = create_engine( + mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool + ) + + with TestClient(mod.app) as c: + yield c + + +def test_crud_app(client: TestClient): + # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor + # this if using obj.model_validate becomes independent of Pydantic v2 + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + # No heroes before creating + response = client.get("heroes/") + assert response.status_code == 200, response.text + assert response.json() == [] + + # Create a hero + response = client.post( + "/heroes/", + json={ + "id": 9000, + "name": "Dead Pond", + "age": 30, + "secret_name": "Dive Wilson", + }, + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"age": 30, "id": IsInt(), "name": "Dead Pond"} + ) + assert ( + response.json()["id"] != 9000 + ), "The ID should be generated by the database" + + # Read a hero + hero_id = response.json()["id"] + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dead Pond", "age": 30, "id": IsInt()} + ) + + # Read all heroes + # Create more heroes first + response = client.post( + "/heroes/", + json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"}, + ) + assert response.status_code == 200, response.text + response = client.post( + "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"} + ) + assert response.status_code == 200, response.text + + response = client.get("/heroes/") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + {"name": "Dead Pond", "age": 30, "id": IsInt()}, + {"name": "Spider-Boy", "age": 18, "id": IsInt()}, + {"name": "Rusty-Man", "age": None, "id": IsInt()}, + ] + ) + + response = client.get("/heroes/?offset=1&limit=1") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [{"name": "Spider-Boy", "age": 18, "id": IsInt()}] + ) + + # Update a hero + response = client.patch( + f"/heroes/{hero_id}", json={"name": "Dog Pond", "age": None} + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dog Pond", "age": None, "id": hero_id} + ) + + # Get updated hero + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dog Pond", "age": None, "id": hero_id} + ) + + # Delete a hero + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot({"ok": True}) + + # The hero is no longer found + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + + # Delete a hero that does not exist + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + # Update a hero that does not exist + response = client.patch(f"/heroes/{hero_id}", json={"name": "Dog Pond"}) + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/heroes/": { + "post": { + "summary": "Create Hero", + "operationId": "create_hero_heroes__post", + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroCreate" + } + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "get": { + "summary": "Read Heroes", + "operationId": "read_heroes_heroes__get", + "parameters": [ + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "default": 0, + "title": "Offset", + }, + }, + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "default": 100, + "title": "Limit", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HeroPublic" + }, + "title": "Response Read Heroes Heroes Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + "/heroes/{hero_id}": { + "get": { + "summary": "Read Hero", + "operationId": "read_hero_heroes__hero_id__get", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "patch": { + "summary": "Update Hero", + "operationId": "update_hero_heroes__hero_id__patch", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroUpdate" + } + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "delete": { + "summary": "Delete Hero", + "operationId": "delete_hero_heroes__hero_id__delete", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "HeroCreate": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": {"type": "string", "title": "Secret Name"}, + }, + "type": "object", + "required": ["name", "secret_name"], + "title": "HeroCreate", + }, + "HeroPublic": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "id": {"type": "integer", "title": "Id"}, + }, + "type": "object", + "required": ["name", "id"], + "title": "HeroPublic", + }, + "HeroUpdate": { + "properties": { + "name": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Name", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Name", + } + ), + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Secret Name", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Secret Name", + } + ), + }, + "type": "object", + "title": "HeroUpdate", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + )