diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index 0ffc101a3..000000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1 +0,0 @@ -github: [tiangolo] diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 918a98f51..2e0061f5e 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,26 +4,30 @@ updates: - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "daily" + interval: "monthly" cooldown: default-days: 7 commit-message: prefix: ⬆ + labels: + - "internal" + - "dependencies" + - "github_actions" + groups: + github-actions: + patterns: + - "*" # Python - package-ecosystem: "uv" directory: "/" schedule: - interval: "daily" - cooldown: - default-days: 7 - commit-message: - prefix: ⬆ - # pre-commit - - package-ecosystem: "pre-commit" - directory: "/" - schedule: - interval: "daily" + interval: "monthly" cooldown: default-days: 7 commit-message: prefix: ⬆ + groups: + python-packages: + dependency-type: "development" + patterns: + - "*" diff --git a/.github/workflows/add-to-project.yml b/.github/workflows/add-to-project.yml index 01a082444..35d089860 100644 --- a/.github/workflows/add-to-project.yml +++ b/.github/workflows/add-to-project.yml @@ -13,8 +13,9 @@ jobs: add-to-project: name: Add to project runs-on: ubuntu-latest + timeout-minutes: 5 steps: - - uses: actions/add-to-project@244f685bbc3b7adfa8466e08b698b5577571133e # v1.0.2 + - uses: actions/add-to-project@5afcf98fcd03f1c2f92c3c83f58ae24323cc57fd # v2.0.0 with: project-url: https://github.com/orgs/fastapi/projects/2 github-token: ${{ secrets.PROJECTS_TOKEN }} # zizmor: ignore[secrets-outside-env] diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 288a6237a..030132a17 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -4,10 +4,6 @@ on: branches: - master pull_request: - types: - - opened - - synchronize - permissions: {} jobs: @@ -16,15 +12,16 @@ jobs: # Required permissions permissions: pull-requests: read + timeout-minutes: 5 # Set job outputs to values from filter step outputs: docs: ${{ steps.filter.outputs.docs }} steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # For pull requests it's not necessary to checkout the code but for the main branch it is - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 + - uses: dorny/paths-filter@7b450fff21473bca461d4b92ce414b9d0420d706 # v4.0.2 id: filter with: filters: | @@ -34,29 +31,31 @@ jobs: - docs_src/** - pyproject.toml - uv.lock - - mkdocs.yml - - mkdocs.env.yml - .github/workflows/build-docs.yml - .github/workflows/deploy-docs.yml - - scripts/mkdocs_hooks.py + - scripts/docs.py langs: needs: - changes + if: ${{ needs.changes.outputs.docs == 'true' }} runs-on: ubuntu-latest + timeout-minutes: 5 outputs: langs: ${{ steps.show-langs.outputs.langs }} steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" enable-cache: true cache-dependency-glob: | pyproject.toml @@ -74,6 +73,7 @@ jobs: - langs if: ${{ needs.changes.outputs.docs == 'true' }} runs-on: ubuntu-latest + timeout-minutes: 7 strategy: matrix: lang: ${{ fromJson(needs.langs.outputs.langs) }} @@ -82,17 +82,19 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" enable-cache: true cache-dependency-glob: | pyproject.toml @@ -101,23 +103,30 @@ jobs: run: uv sync --locked --no-dev --group docs - name: Update Languages run: uv run ./scripts/docs.py update-languages - - uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: - key: mkdocs-cards-${{ matrix.lang }}-${{ github.ref }} - path: docs/${{ matrix.lang }}/.cache + key: zensical-${{ matrix.lang }}-${{ github.ref }} + path: site_zensical_src/${{ matrix.lang }}/.cache - name: Build Docs run: | # zizmor: ignore[template-injection] - comes from trusted source uv run ./scripts/docs.py build-lang ${{ matrix.lang }} - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: docs-site-${{ matrix.lang }} - path: ./site/** + # English owns root static assets. Translated pages reference /img, /css, + # and /js, so omit duplicated language-local copies from artifacts. + path: | + ./site/** + !./site/${{ matrix.lang }}/img/** + !./site/${{ matrix.lang }}/css/** + !./site/${{ matrix.lang }}/js/** 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 if: always() needs: + - langs - build-docs runs-on: ubuntu-latest steps: @@ -125,4 +134,4 @@ jobs: uses: re-actors/alls-green@05ac9388f0aebcb5727afa17fcccfecd6f8ec5fe # v1.2.2 with: jobs: ${{ toJSON(needs) }} - allowed-skips: build-docs + allowed-skips: langs, build-docs diff --git a/.github/workflows/bump-pre-commit-hooks.yml b/.github/workflows/bump-pre-commit-hooks.yml new file mode 100644 index 000000000..b64341a45 --- /dev/null +++ b/.github/workflows/bump-pre-commit-hooks.yml @@ -0,0 +1,67 @@ +name: Bump pre-commit hooks + +on: + schedule: + - cron: "0 12 1 * *" + workflow_dispatch: + +permissions: {} + +jobs: + bump-pre-commit-hooks: + if: github.repository_owner == 'fastapi' + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + token: ${{ secrets.FASTAPI_LATEST_CHANGES }} + persist-credentials: true + - name: Set up Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version-file: ".python-version" + - name: Setup uv + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 + with: + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" + cache-dependency-glob: | + pyproject.toml + uv.lock + - name: Bump pre-commit hooks + run: uv run prek auto-update --freeze --cooldown-days 7 + - name: Create pull request + env: + GH_TOKEN: ${{ secrets.FASTAPI_LATEST_CHANGES }} + BASE_BRANCH: ${{ github.event.repository.default_branch }} + run: | + set -euo pipefail + if git diff --quiet; then + echo "No pre-commit hook updates available" + exit 0 + fi + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + branch="bump-pre-commit-hooks" + git switch -C "$branch" + git add .pre-commit-config.yaml + git commit -m "⬆ Bump pre-commit hooks" + git push --force origin "$branch" + if [ -z "$(gh pr list --head "$branch" --state open --json number --jq '.[].number')" ]; then + gh pr create \ + --base "$BASE_BRANCH" \ + --head "$branch" \ + --title "⬆ Bump pre-commit hooks" \ + --body "Bump pre-commit hook versions via \`prek auto-update --freeze --cooldown-days 7\`." \ + --label internal \ + --label dependencies \ + --label pre-commit + else + echo "PR for \"$branch\" already open; branch updated in place." + fi diff --git a/.github/workflows/contributors.yml b/.github/workflows/contributors.yml deleted file mode 100644 index 785ecea93..000000000 --- a/.github/workflows/contributors.yml +++ /dev/null @@ -1,54 +0,0 @@ -name: FastAPI People Contributors - -on: - schedule: - - cron: "0 3 1 * *" - workflow_dispatch: - inputs: - debug_enabled: - description: "Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)" - required: false - default: "false" - -permissions: {} - -jobs: - job: - if: github.repository_owner == 'fastapi' - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: true # Required for `git push` in `contributors.py` - - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 - with: - python-version-file: ".python-version" - - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - with: - version: "0.11.4" - enable-cache: true - cache-dependency-glob: | - pyproject.toml - uv.lock - - name: Install Dependencies - run: uv sync --locked --no-dev --group github-actions - # Allow debugging with tmate - - name: Setup tmate session - uses: mxschmitt/action-tmate@c0afd6f790e3a5564914980036ebf83216678101 # v3.23 - if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} - with: - limit-access-to-actor: true - env: - GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} # zizmor: ignore[secrets-outside-env] - - name: FastAPI People Contributors - run: uv run ./scripts/contributors.py - env: - GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} # zizmor: ignore[secrets-outside-env] diff --git a/.github/workflows/create-draft-release.yml b/.github/workflows/create-draft-release.yml new file mode 100644 index 000000000..8f9e6fc73 --- /dev/null +++ b/.github/workflows/create-draft-release.yml @@ -0,0 +1,56 @@ +name: Create Draft Release + +on: + pull_request: + types: + - closed + +permissions: {} + +jobs: + create-draft-release: + if: github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'release') + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: write + env: + PREPARE_RELEASE_VERSION_FILE: fastapi/__init__.py + PREPARE_RELEASE_RELEASE_NOTES_FILE: docs/en/docs/release-notes.md + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: true + - name: Set up Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version-file: ".python-version" + - name: Install uv + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 + with: + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" + - name: Extract release details + id: release-details + run: | + set -euo pipefail + version="$(uv run python scripts/prepare_release.py current-version)" + uv run python scripts/prepare_release.py release-notes > draft-release-notes.md + echo "version=$version" >> "$GITHUB_OUTPUT" + - name: Create draft release + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.release-details.outputs.version }} + run: | + set -euo pipefail + gh release create "$VERSION" \ + --draft \ + --title "$VERSION" \ + --notes-file draft-release-notes.md \ + --target "$(git rev-parse HEAD)" diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index ead5ed4bc..6e40b5b83 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -16,22 +16,25 @@ jobs: issues: write pull-requests: write statuses: write + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" enable-cache: false - name: Install GitHub Actions dependencies run: uv sync --locked --no-dev --group github-actions @@ -60,7 +63,7 @@ jobs: env: PROJECT_NAME: fastapitiangolo BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} - uses: cloudflare/wrangler-action@da0e0dfe58b7a431659754fdf3f186c529afbe65 # v3.14.1 + uses: cloudflare/wrangler-action@ebbaa1584979971c8614a24965b4405ff95890e0 # v4.0.0 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} # zizmor: ignore[secrets-outside-env] accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} # zizmor: ignore[secrets-outside-env] diff --git a/.github/workflows/detect-conflicts.yml b/.github/workflows/detect-conflicts.yml index 38d526bd9..ecd288ba1 100644 --- a/.github/workflows/detect-conflicts.yml +++ b/.github/workflows/detect-conflicts.yml @@ -12,9 +12,10 @@ jobs: contents: read pull-requests: write runs-on: ubuntu-latest + timeout-minutes: 5 steps: - name: Check if PRs have merge conflicts - uses: eps1lon/actions-label-merge-conflict@1df065ebe6e3310545d4f4c4e862e43bdca146f0 # v3.0.3 + uses: eps1lon/actions-label-merge-conflict@0273be72a0bbd58fcd71d0d6c02c209b50d1e5e1 # v3.1.0 with: dirtyLabel: "conflicts" repoToken: "${{ secrets.GITHUB_TOKEN }}" diff --git a/.github/workflows/guard-dependencies.yml b/.github/workflows/guard-dependencies.yml new file mode 100644 index 000000000..142c7e50e --- /dev/null +++ b/.github/workflows/guard-dependencies.yml @@ -0,0 +1,53 @@ +name: Guard Dependencies + +on: + pull_request_target: # zizmor: ignore[dangerous-triggers] -- This workflow only reads context.payload metadata, never checks out PR code + branches: [master] + paths: + - pyproject.toml + - uv.lock + +permissions: + contents: read + issues: write + pull-requests: write + +jobs: + check-author: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Check if author is org member or allowed bot + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const pr = context.payload.pull_request; + const author = pr.user.login; + const assoc = pr.author_association; + + const botAllowlist = new Set(['dependabot[bot]']); + const orgAuthorAssociations = new Set(['MEMBER', 'OWNER']); + + const allowed = + botAllowlist.has(author) || + (assoc != null && orgAuthorAssociations.has(assoc)); + + if (!allowed) { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + body: `This PR modifies dependency files (\`pyproject.toml\` or \`uv.lock\`), which is restricted to members of the **${context.repo.owner}** organization on GitHub.\n\nIf you need a dependency change, please [open a discussion](https://github.com/${context.repo.owner}/${context.repo.repo}/discussions/new) describing what you need and why.\n\nClosing this PR automatically.` + }); + + await github.rest.pulls.update({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number, + state: 'closed' + }); + + core.setFailed('Dependency changes are restricted to organization members.'); + } else { + console.log(`Author ${author} (author_association=${assoc}) is allowed to make dependency changes.`); + } diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index c0ffd7ac7..e7f3a5f53 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -23,34 +23,12 @@ jobs: permissions: issues: write pull-requests: write + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: tiangolo/issue-manager@2fb3484ec9279485df8659e8ec73de262431737d # 0.6.0 + - uses: tiangolo/issue-manager@dc846170c36eb62fb434b3d943b36399fe240fb5 # 0.8.1 with: 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." - }, - "waiting": { - "delay": 2628000, - "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.", - "reminder": { - "before": "P3D", - "message": "Heads-up: this will be closed in 3 days unless there's new activity." - } - }, - "invalid": { - "delay": 0, - "message": "This was marked as invalid and will be closed now. If this is an error, please provide additional details." - }, - "maybe-ai": { - "delay": 0, - "message": "This was marked as potentially AI generated and will be closed now. If this is an error, please provide additional details, make sure to read the docs about contributing and AI." - } - } diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 1f2780936..f5f036ec7 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -13,22 +13,25 @@ jobs: runs-on: ubuntu-latest permissions: pull-requests: write + timeout-minutes: 7 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" enable-cache: true cache-dependency-glob: | pyproject.toml diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index 58c689237..2cbfe8cca 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -17,8 +17,9 @@ jobs: contents: read pull-requests: write runs-on: ubuntu-latest + timeout-minutes: 5 steps: - - uses: actions/labeler@634933edcd8ababfe52f92936142cc22ac488b1b # v6.0.1 + - uses: actions/labeler@b8dd2d9be0f68b860e7dae5dae7d772984eacd6d # v6.2.0 if: ${{ github.event.action != 'labeled' && github.event.action != 'unlabeled' }} - run: echo "Done adding labels" # Run this after labeler applied labels @@ -28,8 +29,9 @@ jobs: permissions: pull-requests: read runs-on: ubuntu-latest + timeout-minutes: 5 steps: - uses: agilepathway/label-checker@c3d16ad512e7cea5961df85ff2486bb774caf3c5 # v1.6.65 with: - one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal + one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal,release repo_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index aaa12c17d..be20c98ae 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -22,23 +22,25 @@ jobs: latest-changes: runs-on: ubuntu-latest if: github.event_name == 'workflow_dispatch' || github.event.pull_request.merged == true + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: + ref: ${{ github.event.repository.default_branch }} # To allow latest-changes to commit to the main branch token: ${{ secrets.FASTAPI_LATEST_CHANGES }} # zizmor: ignore[secrets-outside-env] persist-credentials: true # required by tiangolo/latest-changes # Allow debugging with tmate - name: Setup tmate session - uses: mxschmitt/action-tmate@c0afd6f790e3a5564914980036ebf83216678101 # v3.23 + uses: mxschmitt/action-tmate@35b54afac29c97fb54faba5b513f8fbd1882f113 # v3.24 if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: tiangolo/latest-changes@c9d329cb147f0ddf4fb631214e3f838ff17ccbbd # 0.4.1 + - uses: tiangolo/latest-changes@c9b73efbc8992ef1a401e4235ea307a8ca8a724b # 0.6.1 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 07d4e0bdf..7e72488ef 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -24,22 +24,26 @@ jobs: runs-on: ubuntu-latest permissions: discussions: write + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: + ref: ${{ github.event.repository.default_branch }} persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" enable-cache: true cache-dependency-glob: | pyproject.toml @@ -48,7 +52,7 @@ jobs: run: uv sync --locked --no-dev --group github-actions # Allow debugging with tmate - name: Setup tmate session - uses: mxschmitt/action-tmate@c0afd6f790e3a5564914980036ebf83216678101 # v3.23 + uses: mxschmitt/action-tmate@35b54afac29c97fb54faba5b513f8fbd1882f113 # v3.24 if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml deleted file mode 100644 index 51e2188cc..000000000 --- a/.github/workflows/people.yml +++ /dev/null @@ -1,55 +0,0 @@ -name: FastAPI People - -on: - schedule: - - cron: "0 14 1 * *" - workflow_dispatch: - inputs: - debug_enabled: - description: Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate) - required: false - default: "false" - -permissions: {} - -jobs: - job: - if: github.repository_owner == 'fastapi' - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: true # Required for `git push` in `people.py` - - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 - with: - python-version-file: ".python-version" - - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 - with: - version: "0.11.4" - enable-cache: true - cache-dependency-glob: | - pyproject.toml - uv.lock - - name: Install Dependencies - run: uv sync --locked --no-dev --group github-actions - # Allow debugging with tmate - - name: Setup tmate session - uses: mxschmitt/action-tmate@c0afd6f790e3a5564914980036ebf83216678101 # v3.23 - if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} - with: - limit-access-to-actor: true - env: - GITHUB_TOKEN: ${{ secrets.FASTAPI_PEOPLE }} # zizmor: ignore[secrets-outside-env] - - name: FastAPI People Experts - run: uv run ./scripts/people.py - env: - GITHUB_TOKEN: ${{ secrets.FASTAPI_PEOPLE }} # zizmor: ignore[secrets-outside-env] - SLEEP_INTERVAL: ${{ vars.PEOPLE_SLEEP_INTERVAL }} diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 5b0be3801..06a706928 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -2,10 +2,6 @@ name: pre-commit on: pull_request: - types: - - opened - - synchronize - permissions: {} env: @@ -15,12 +11,13 @@ env: jobs: pre-commit: runs-on: ubuntu-latest + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 name: Checkout PR for own repo if: env.HAS_SECRETS == 'true' with: @@ -33,7 +30,7 @@ jobs: token: ${{ secrets.PRE_COMMIT }} # zizmor: ignore[secrets-outside-env] persist-credentials: true # Required for `git push` command # pre-commit lite ci needs the default checkout configs to work - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 name: Checkout PR for fork if: env.HAS_SECRETS == 'false' with: @@ -42,13 +39,15 @@ jobs: fetch-depth: 0 persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" cache-dependency-glob: | pyproject.toml uv.lock @@ -84,6 +83,7 @@ jobs: needs: - pre-commit runs-on: ubuntu-latest + timeout-minutes: 5 steps: - name: Dump GitHub context env: diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml new file mode 100644 index 000000000..6b84ade70 --- /dev/null +++ b/.github/workflows/prepare-release.yml @@ -0,0 +1,80 @@ +name: Prepare Release + +on: + workflow_dispatch: + inputs: + bump: + description: Release bump + required: true + type: choice + options: + - patch + - minor + - major + date: + description: Release date in YYYY-MM-DD format. Defaults to today. + required: false + type: string + +permissions: {} + +jobs: + prepare-release: + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: write + issues: write + pull-requests: write + env: + PREPARE_RELEASE_VERSION_FILE: fastapi/__init__.py + PREPARE_RELEASE_RELEASE_NOTES_FILE: docs/en/docs/release-notes.md + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + token: ${{ secrets.FASTAPI_LATEST_CHANGES }} # zizmor: ignore[secrets-outside-env] + persist-credentials: true + - name: Set up Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version-file: ".python-version" + - name: Install uv + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 + with: + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" + - name: Prepare release + env: + PREPARE_RELEASE_BUMP: ${{ inputs.bump }} + PREPARE_RELEASE_DATE: ${{ inputs.date }} + run: uv run python scripts/prepare_release.py prepare + - name: Get release version + id: release-version + run: | + version="$(uv run python scripts/prepare_release.py current-version)" + echo "$version" + echo "version=$version" >> "$GITHUB_OUTPUT" + - name: Create release pull request + env: + GH_TOKEN: ${{ secrets.FASTAPI_LATEST_CHANGES }} + VERSION: ${{ steps.release-version.outputs.version }} + run: | + set -euo pipefail + branch="release-${VERSION}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git switch -c "$branch" + git add $PREPARE_RELEASE_VERSION_FILE $PREPARE_RELEASE_RELEASE_NOTES_FILE + git commit -m "🔖 Release version ${VERSION}" + git push --set-upstream origin "$branch" + gh pr create \ + --base master \ + --head "$branch" \ + --title "🔖 Release version ${VERSION}" \ + --body "Prepare release ${VERSION}." \ + --label release diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 2695854dc..bb601611b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -3,7 +3,7 @@ name: Publish on: release: types: - - created + - published permissions: {} @@ -13,22 +13,26 @@ jobs: permissions: id-token: write contents: read + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Install uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" + enable-cache: "false" - name: Build distribution run: uv build - name: Publish diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index 46f261018..f7e4323c3 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -12,22 +12,25 @@ jobs: runs-on: ubuntu-latest permissions: statuses: write + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" cache-dependency-glob: | pyproject.toml uv.lock diff --git a/.github/workflows/sponsors.yml b/.github/workflows/sponsors.yml index ef72a6824..c880f578e 100644 --- a/.github/workflows/sponsors.yml +++ b/.github/workflows/sponsors.yml @@ -18,22 +18,25 @@ jobs: runs-on: ubuntu-latest permissions: contents: write + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: true # Required for `git push` in `sponsors.py` - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" enable-cache: true cache-dependency-glob: | pyproject.toml @@ -42,7 +45,7 @@ jobs: run: uv sync --locked --no-dev --group github-actions # Allow debugging with tmate - name: Setup tmate session - uses: mxschmitt/action-tmate@c0afd6f790e3a5564914980036ebf83216678101 # v3.23 + uses: mxschmitt/action-tmate@35b54afac29c97fb54faba5b513f8fbd1882f113 # v3.24 if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml index fad16fb2c..cffb9d8c8 100644 --- a/.github/workflows/test-redistribute.yml +++ b/.github/workflows/test-redistribute.yml @@ -5,25 +5,22 @@ on: branches: - master pull_request: - types: - - opened - - synchronize - permissions: {} jobs: test-redistribute: runs-on: ubuntu-latest + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Install build dependencies @@ -57,6 +54,7 @@ jobs: needs: - test-redistribute runs-on: ubuntu-latest + timeout-minutes: 5 steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@05ac9388f0aebcb5727afa17fcccfecd6f8ec5fe # v1.2.2 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 36cf5a287..6855f0d48 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -5,9 +5,6 @@ on: branches: - master pull_request: - types: - - opened - - synchronize schedule: # cron every week on monday - cron: "0 0 * * 1" @@ -25,14 +22,15 @@ jobs: permissions: pull-requests: read # Set job outputs to values from filter step + timeout-minutes: 5 outputs: src: ${{ steps.filter.outputs.src }} steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false # For pull requests it's not necessary to checkout the code but for the main branch it is - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 + - uses: dorny/paths-filter@7b450fff21473bca461d4b92ce414b9d0420d706 # v4.0.2 id: filter with: filters: | @@ -50,6 +48,7 @@ jobs: needs: - changes if: needs.changes.outputs.src == 'true' || github.ref == 'refs/heads/master' + timeout-minutes: 10 strategy: matrix: os: [ windows-latest, macos-latest ] @@ -81,6 +80,11 @@ jobs: uv-resolution: highest codspeed: codspeed deprecated-tests: "no-deprecation" + - os: ubuntu-latest + python-version: "3.13" + uv-resolution: highest + deprecated-tests: "no-deprecation" + without-httpx2: true - os: ubuntu-latest python-version: "3.14" coverage: coverage @@ -103,17 +107,19 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version: ${{ matrix.python-version }} - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" enable-cache: true cache-dependency-glob: | pyproject.toml @@ -129,15 +135,19 @@ jobs: - name: Install deprecated libraries just for testing if: matrix.deprecated-tests == 'test-deprecation' run: uv pip install orjson ujson + - name: Uninstall httpx2 to run tests with httpx + if: matrix.without-httpx2 == 'true' + run: uv pip uninstall httpx2 - name: Reinstall SQLAlchemy without Cython extensions if: matrix.python-version == '3.14t' && matrix.os == 'ubuntu-latest' run: "DISABLE_SQLALCHEMY_CEXT=1 uv pip install --force-reinstall --no-binary :all: sqlalchemy" - run: mkdir coverage - name: Test - run: uv run --no-sync bash scripts/test-cov.sh + run: uv run --no-sync bash scripts/test-cov.sh $PYTEST_OPTIONS env: COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }}-${{ matrix.deprecated-tests}} CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }}-${{ matrix.deprecated-tests}} + PYTEST_OPTIONS: ${{ (matrix.without-httpx2 == 'true') && '-W ignore::UserWarning' || '' }} # Do not store coverage for all possible combinations to avoid file size max errors in Smokeshow - name: Store coverage files if: matrix.coverage == 'coverage' @@ -152,6 +162,7 @@ jobs: - changes if: needs.changes.outputs.src == 'true' || github.ref == 'refs/heads/master' runs-on: ubuntu-latest + timeout-minutes: 5 env: UV_PYTHON: "3.13" UV_RESOLUTION: highest @@ -160,17 +171,19 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version: "3.13" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" enable-cache: true cache-dependency-glob: | pyproject.toml @@ -178,7 +191,7 @@ jobs: - name: Install Dependencies run: uv sync --no-dev --group tests --extra all - name: CodSpeed benchmarks - uses: CodSpeedHQ/action@1c8ae4843586d3ba879736b7f6b7b0c990757fab # v4.12.1 + uses: CodSpeedHQ/action@a4a36bb07c0638b0b4ca52bf1f3dad1b4289e52f # v4.18.1 with: mode: simulation run: uv run --no-sync pytest tests/benchmarks --codspeed @@ -187,21 +200,24 @@ jobs: needs: - test runs-on: ubuntu-latest + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" enable-cache: true cache-dependency-glob: | pyproject.toml @@ -226,12 +242,14 @@ jobs: - run: uv run coverage report --fail-under=100 # https://github.com/marketplace/actions/alls-green#why - check: # This job does nothing and is only used for the branch protection + test-alls-green: # This job does nothing and is only used for the branch protection if: always() needs: + - test - coverage-combine - benchmark runs-on: ubuntu-latest + timeout-minutes: 5 steps: - name: Dump GitHub context env: diff --git a/.github/workflows/topic-repos.yml b/.github/workflows/topic-repos.yml index 0f40b7b3d..762422813 100644 --- a/.github/workflows/topic-repos.yml +++ b/.github/workflows/topic-repos.yml @@ -13,22 +13,25 @@ jobs: runs-on: ubuntu-latest permissions: contents: write + timeout-minutes: 5 steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: true # Required for `git push` in `topic_repos.py` - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" enable-cache: true cache-dependency-glob: | pyproject.toml diff --git a/.github/workflows/translate.yml b/.github/workflows/translate.yml index ed21881cd..abe77537b 100644 --- a/.github/workflows/translate.yml +++ b/.github/workflows/translate.yml @@ -50,17 +50,19 @@ jobs: langs: ${{ steps.show-langs.outputs.langs }} commands: ${{ steps.show-langs.outputs.commands }} steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" cache-dependency-glob: | pyproject.toml uv.lock @@ -79,6 +81,8 @@ jobs: if: github.repository_owner == 'fastapi' needs: langs runs-on: ubuntu-latest + permissions: + contents: write strategy: matrix: lang: ${{ fromJson(needs.langs.outputs.langs) }} @@ -88,18 +92,20 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: fetch-depth: 0 - persist-credentials: false + persist-credentials: true # Required for `git push` in `translate.py` - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version-file: ".python-version" - name: Setup uv - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0 + uses: astral-sh/setup-uv@d31148d669074a8d0a63714ba94f3201e7020bc3 # v8.3.0 with: - version: "0.11.4" + # Before upgrading uv version, make sure astral-sh/setup-uv knows its checksum. + # See: https://github.com/astral-sh/setup-uv/issues/851#issuecomment-4282017837 + version: "0.11.18" cache-dependency-glob: | pyproject.toml uv.lock @@ -107,7 +113,7 @@ jobs: run: uv sync --locked --no-dev --group github-actions --group translations # Allow debugging with tmate - name: Setup tmate session - uses: mxschmitt/action-tmate@c0afd6f790e3a5564914980036ebf83216678101 # v3.23 + uses: mxschmitt/action-tmate@35b54afac29c97fb54faba5b513f8fbd1882f113 # v3.24 if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml new file mode 100644 index 000000000..11ecb8272 --- /dev/null +++ b/.github/workflows/zizmor.yml @@ -0,0 +1,25 @@ +name: Zizmor + +on: + push: + branches: + - main + pull_request: + workflow_dispatch: + +permissions: {} + +jobs: + zizmor: + name: Run zizmor + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + security-events: write # Required for upload-sarif (used by zizmor-action) to upload SARIF files. + steps: + - name: Checkout repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + - name: Run zizmor + uses: zizmorcore/zizmor-action@192e21d79ab29983730a13d1382995c2307fbcaa # v0.5.7 diff --git a/.gitignore b/.gitignore index 243cdb93a..2c0d859ad 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ __pycache__ htmlcov dist site +site_zensical_src .coverage* coverage.xml .netlify diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7913c813a..967d5e6d3 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,6 +14,12 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace + - repo: https://github.com/crate-ci/typos + rev: bee27e3a4fd1ea2111cf90ab89cd076c870fce14 # frozen: v1.48.0 + hooks: + - id: typos + args: [--force-exclude] + - repo: local hooks: - id: local-ruff-check @@ -39,7 +45,7 @@ repos: - id: local-ty name: ty check - entry: uv run ty check fastapi + entry: uv run ty check require_serial: true language: unsupported pass_filenames: false @@ -59,6 +65,13 @@ repos: files: ^docs/en/docs/index\.md|docs/en/data/sponsors\.yml|scripts/docs\.py$ pass_filenames: false + - id: render-banner-sponsors + language: unsupported + name: render sponsor banner partial + entry: uv run ./scripts/docs.py render-banner-sponsors + files: ^docs/en/data/sponsors\.yml|^docs/en/overrides/partials/banner-sponsors\.html|^scripts/docs\.py$ + pass_filenames: false + - id: update-languages language: unsupported name: update languages @@ -90,6 +103,6 @@ repos: name: zizmor language: python entry: uv run zizmor . - files: ^\.github\/workflows\/ + files: ^\.github/workflows/|^uv\.lock$ require_serial: true pass_filenames: false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 7b9452725..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1 +0,0 @@ -Please read the [Development - Contributing](https://fastapi.tiangolo.com/contributing/) guidelines in the documentation site. diff --git a/README.md b/README.md index 9ed338a1b..36d262983 100644 --- a/README.md +++ b/README.md @@ -49,24 +49,25 @@ The key features are: -### Gold and Silver Sponsors +### Gold Sponsors - - + +### Silver Sponsors + - - + + @@ -74,6 +75,10 @@ The key features are: ## Opinions + + +
+ "_[...] 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)
@@ -92,37 +97,25 @@ The key features are: --- -"_I’m over the moon excited about **FastAPI**. It’s so fun!_" - -
Brian Okken - [Python Bytes](https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855) podcast host (ref)
- ---- - -"_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._" +"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._" -
Timothy Crosley - [Hug](https://github.com/hugapi/hug) creator (ref)
+
Deon Pillsbury - Cisco (ref)
--- -"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" - -"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" - -
Ines Montani - Matthew Honnibal - [Explosion AI](https://explosion.ai) founders - [spaCy](https://spacy.io) creators (ref) - (ref)
- ---- +
-"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._" +## FastAPI Conf -
Deon Pillsbury - Cisco (ref)
+[**FastAPI Conf '26**](https://fastapiconf.com) is happening on **October 28, 2026** in **Amsterdam, NL**. All about FastAPI, right from the source. 🎤 ---- +FastAPI Conf '26 - October 28, 2026 - Amsterdam, NL ## FastAPI mini documentary There's a [FastAPI mini documentary](https://www.youtube.com/watch?v=mpR8ngthqiE) released at the end of 2025, you can watch it online: -FastAPI Mini Documentary +FastAPI Mini Documentary ## **Typer**, the FastAPI of CLIs @@ -438,13 +431,13 @@ For a more complete example including more features, see the Dependency Injection** system. * Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth. * More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic). * **GraphQL** integration with [Strawberry](https://strawberry.rocks) and other libraries. -* Many extra features (thanks to Starlette) as: +* Many extra features (thanks to Starlette) such as: * **WebSockets** * extremely easy tests based on HTTPX and `pytest` * **CORS** @@ -453,9 +446,7 @@ For a more complete example including more features, see the @@ -471,6 +462,8 @@ Deploying to FastAPI Cloud... +The CLI will automatically detect your FastAPI application and deploy it to the cloud. If you are not logged in, your browser will open to complete the authentication process. + That's it! Now you can access your app at that URL. ✨ #### About FastAPI Cloud diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index 87e87e0ca..000000000 --- a/SECURITY.md +++ /dev/null @@ -1,31 +0,0 @@ -# Security Policy - -Security is very important for FastAPI and its community. 🔒 - -Learn more about it below. 👇 - -## Versions - -The latest version of FastAPI is supported. - -You are encouraged to [write tests](https://fastapi.tiangolo.com/tutorial/testing/) for your application and update your FastAPI version frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**. - -You can learn more about [FastAPI versions and how to pin and upgrade them](https://fastapi.tiangolo.com/deployment/versions/) for your project in the docs. - -## Reporting a Vulnerability - -If you think you found a vulnerability, and even if you are not sure about it, please report it right away by sending an email to: security@tiangolo.com. Please try to be as explicit as possible, describing all the steps and example code to reproduce the security issue. - -I (the author, [@tiangolo](https://x.com/tiangolo)) will review it thoroughly and get back to you. - -## Public Discussions - -Please restrain from publicly discussing a potential security vulnerability. 🙊 - -It's better to discuss privately and try to find a solution first, to limit the potential impact as much as possible. - ---- - -Thanks for your help! - -The FastAPI community and I thank you for that. 🙇 diff --git a/docs/de/docs/_llm-test.md b/docs/de/docs/_llm-test.md index de1aa1e9f..3fec41817 100644 --- a/docs/de/docs/_llm-test.md +++ b/docs/de/docs/_llm-test.md @@ -1,17 +1,17 @@ # LLM-Testdatei { #llm-test-file } -Dieses Dokument testet, ob das LLM, das die Dokumentation übersetzt, den `general_prompt` in `scripts/translate.py` und den sprachspezifischen Prompt in `docs/{language code}/llm-prompt.md` versteht. Der sprachsspezifische Prompt wird an `general_prompt` angehängt. +Dieses Dokument testet, ob das LLM, das die Dokumentation übersetzt, den `general_prompt` in `scripts/translate.py` und den sprachspezifischen Prompt in `docs/{language code}/llm-prompt.md` versteht. Der sprachspezifische Prompt wird an `general_prompt` angehängt. -Hier hinzugefügte Tests werden von allen Erstellern sprachsspezifischer Prompts gesehen. +Hier hinzugefügte Tests werden von allen Erstellern sprachspezifischer Prompts gesehen. So verwenden: -* Einen sprachsspezifischen Prompt haben – `docs/{language code}/llm-prompt.md`. +* Einen sprachspezifischen Prompt haben – `docs/{language code}/llm-prompt.md`. * Eine frische Übersetzung dieses Dokuments in die gewünschte Zielsprache durchführen (siehe z. B. das Kommando `translate-page` der `translate.py`). Dadurch wird die Übersetzung unter `docs/{language code}/docs/_llm-test.md` erstellt. * Prüfen Sie, ob in der Übersetzung alles in Ordnung ist. -* Verbessern Sie bei Bedarf Ihren sprachsspezifischen Prompt, den allgemeinen Prompt oder das englische Dokument. +* Verbessern Sie bei Bedarf Ihren sprachspezifischen Prompt, den allgemeinen Prompt oder das englische Dokument. * Beheben Sie anschließend manuell die verbleibenden Probleme in der Übersetzung, sodass es eine gute Übersetzung ist. -* Übersetzen Sie erneut, nachdem die gute Übersetzung vorliegt. Das ideale Ergebnis wäre, dass das LLM an der Übersetzung keine Änderungen mehr vornimmt. Das bedeutet, dass der allgemeine Prompt und Ihr sprachsspezifischer Prompt so gut sind, wie sie sein können (Es wird manchmal ein paar scheinbar zufällige Änderungen machen, der Grund ist, dass [LLMs keine deterministischen Algorithmen sind](https://doublespeak.chat/#/handbook#deterministic-output)). +* Übersetzen Sie erneut, nachdem die gute Übersetzung vorliegt. Das ideale Ergebnis wäre, dass das LLM an der Übersetzung keine Änderungen mehr vornimmt. Das bedeutet, dass der allgemeine Prompt und Ihr sprachspezifischer Prompt so gut sind, wie sie sein können (Es wird manchmal ein paar scheinbar zufällige Änderungen machen, der Grund ist, dass [LLMs keine deterministischen Algorithmen sind](https://doublespeak.chat/#/handbook#deterministic-output)). Die Tests: @@ -95,7 +95,7 @@ $ fastapi run GTD -* lt +* GTD +* lt * XWT * PSGI ### Das abbr gibt eine vollständige Phrase und eine Erklärung { #the-abbr-gives-a-full-phrase-and-an-explanation } -* MDN -* I/O. +* MDN +* I/O. //// @@ -219,7 +211,7 @@ Siehe Abschnitt `### HTML abbr elements` im allgemeinen Prompt in `scripts/trans //// -## HTML „dfn“-Elemente { #html-dfn-elements } +## HTML-„dfn“-Elemente { #html-dfn-elements } * Cluster * Deep Learning @@ -248,7 +240,7 @@ Die einzige strenge Regel für Überschriften ist, dass das LLM den Hash-Teil in Siehe Abschnitt `### Headings` im allgemeinen Prompt in `scripts/translate.py`. -Für einige sprachsspezifische Anweisungen, siehe z. B. den Abschnitt `### Headings` in `docs/de/llm-prompt.md`. +Für einige sprachspezifische Anweisungen, siehe z. B. den Abschnitt `### Headings` in `docs/de/llm-prompt.md`. //// @@ -371,12 +363,12 @@ Für einige sprachsspezifische Anweisungen, siehe z. B. den Abschnitt `### Headi * die Umgebungsvariable * die Umgebungsvariable * der `PATH` -* die `PATH`-Umgebungsvariable +* die `PATH`-Variable * die Authentifizierung * der Authentifizierungsanbieter * die Autorisierung -* das Anmeldeformular +* das Autorisierungsformular * der Autorisierungsanbieter * der Benutzer authentisiert sich * das System authentifiziert den Benutzer diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md index bc7c477c8..f2214713b 100644 --- a/docs/de/docs/advanced/additional-responses.md +++ b/docs/de/docs/advanced/additional-responses.md @@ -34,7 +34,7 @@ Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. /// -/// info | Info +/// note | Hinweis Der `model`-Schlüssel ist nicht Teil von OpenAPI. @@ -183,7 +183,7 @@ Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben mü /// -/// info | Info +/// note | Hinweis 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`). diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md index f1a74a32c..6f0114cc1 100644 --- a/docs/de/docs/advanced/additional-status-codes.md +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -1,5 +1,6 @@ # Zusätzliche Statuscodes { #additional-status-codes } + Standardmäßig liefert **FastAPI** die Responses als `JSONResponse` zurück und fügt den Inhalt, den Sie aus Ihrer *Pfadoperation* zurückgeben, in diese `JSONResponse` ein. Es wird der Default-Statuscode oder derjenige verwendet, den Sie in Ihrer *Pfadoperation* festgelegt haben. diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md index ab2cab071..da06794a9 100644 --- a/docs/de/docs/advanced/advanced-dependencies.md +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -1,5 +1,6 @@ # Fortgeschrittene Abhängigkeiten { #advanced-dependencies } + ## Parametrisierte Abhängigkeiten { #parameterized-dependencies } Alle Abhängigkeiten, die wir bisher gesehen haben, waren festgelegte Funktionen oder Klassen. @@ -98,7 +99,7 @@ Wenn Sie beispielsweise eine Datenbanksession in einer Abhängigkeit mit `yield` Dieses Verhalten wurde in 0.118.0 zurückgenommen, sodass der Exit-Code nach `yield` ausgeführt wird, nachdem die Response gesendet wurde. -/// info | Info +/// note | Hinweis Wie Sie unten sehen werden, ähnelt dies sehr dem Verhalten vor Version 0.106.0, jedoch mit mehreren Verbesserungen und Bugfixes für Sonderfälle. diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md index 9a11089ad..377c7f569 100644 --- a/docs/de/docs/advanced/custom-response.md +++ b/docs/de/docs/advanced/custom-response.md @@ -41,7 +41,7 @@ Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie ` {* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *} -/// info | Info +/// note | Hinweis Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. @@ -65,7 +65,7 @@ Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wi /// -/// info | Info +/// note | Hinweis Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben. @@ -158,6 +158,7 @@ Sie können eine `RedirectResponse` direkt zurückgeben: Oder Sie können sie im Parameter `response_class` verwenden: + {* ../../docs_src/custom_response/tutorial006b_py310.py hl[2,7,9] *} Wenn Sie das tun, können Sie die URL direkt von Ihrer *Pfadoperation*-Funktion zurückgeben. diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md index 743aea699..bacf9d162 100644 --- a/docs/de/docs/advanced/dataclasses.md +++ b/docs/de/docs/advanced/dataclasses.md @@ -1,5 +1,6 @@ # Datenklassen verwenden { #using-dataclasses } + FastAPI basiert auf **Pydantic**, und ich habe Ihnen gezeigt, wie Sie Pydantic-Modelle verwenden können, um Requests und Responses zu deklarieren. Aber FastAPI unterstützt auf die gleiche Weise auch die Verwendung von [`dataclasses`](https://docs.python.org/3/library/dataclasses.html): @@ -18,7 +19,7 @@ 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 | Info +/// note | Hinweis Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können. diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md index ea04e3ebd..6efe96809 100644 --- a/docs/de/docs/advanced/events.md +++ b/docs/de/docs/advanced/events.md @@ -102,7 +102,7 @@ Diese Funktionen können mit `async def` oder normalem `def` deklariert werden. ### `startup`-Event { #startup-event } -Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `startup`: +Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `"startup"`: {* ../../docs_src/events/tutorial001_py310.py hl[8] *} @@ -114,13 +114,13 @@ Und Ihre Anwendung empfängt erst dann Requests, wenn alle `startup`-Eventhandle ### `shutdown`-Event { #shutdown-event } -Um eine Funktion hinzuzufügen, die beim Shutdown der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `shutdown`: +Um eine Funktion hinzuzufügen, die beim Shutdown der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `"shutdown"`: {* ../../docs_src/events/tutorial002_py310.py hl[6] *} Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`. -/// info | Info +/// note | Hinweis 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. @@ -150,9 +150,9 @@ Aus diesem Grund wird jetzt empfohlen, stattdessen `lifespan` wie oben erläuter Nur ein technisches Detail für die neugierigen Nerds. 🤓 -In der technischen ASGI-Spezifikation ist dies Teil des [Lifespan Protokolls](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) und definiert Events namens `startup` und `shutdown`. +In der technischen ASGI-Spezifikation ist dies Teil des [Lifespan-Protokolls](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) und definiert Events namens `startup` und `shutdown`. -/// info | Info +/// note | Hinweis Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in [Starlettes Lifespan-Dokumentation](https://www.starlette.dev/lifespan/). diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md index 12ba4072c..d93641bd3 100644 --- a/docs/de/docs/advanced/generate-clients.md +++ b/docs/de/docs/advanced/generate-clients.md @@ -20,22 +20,6 @@ FastAPI generiert automatisch **OpenAPI 3.1**-Spezifikationen, daher muss jedes /// -## SDK-Generatoren von FastAPI-Sponsoren { #sdk-generators-from-fastapi-sponsors } - -Dieser Abschnitt hebt **venture-unterstützte** und **firmengestützte** Lösungen hervor, die von Unternehmen entwickelt werden, welche FastAPI sponsern. Diese Produkte bieten **zusätzliche Funktionen** und **Integrationen** zusätzlich zu hochwertig generierten SDKs. - -Durch das ✨ [**Sponsoring von FastAPI**](../help-fastapi.md#sponsor-the-author) ✨ helfen diese Unternehmen sicherzustellen, dass das Framework und sein **Ökosystem** gesund und **nachhaltig** bleiben. - -Ihr Sponsoring zeigt auch ein starkes Engagement für die FastAPI-**Community** (Sie), was bedeutet, dass sie nicht nur einen **großartigen Service** bieten möchten, sondern auch ein **robustes und florierendes Framework**, FastAPI, unterstützen möchten. 🙇 - -Zum Beispiel könnten Sie ausprobieren: - -* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship) -* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral) -* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi) - -Einige dieser Lösungen sind möglicherweise auch Open Source oder bieten kostenlose Tarife an, sodass Sie diese ohne finanzielle Verpflichtung ausprobieren können. Andere kommerzielle SDK-Generatoren sind online verfügbar und können dort gefunden werden. 🤓 - ## Ein TypeScript-SDK erstellen { #create-a-typescript-sdk } Beginnen wir mit einer einfachen FastAPI-Anwendung: diff --git a/docs/de/docs/advanced/json-base64-bytes.md b/docs/de/docs/advanced/json-base64-bytes.md index 26c7e7089..618bbd1a9 100644 --- a/docs/de/docs/advanced/json-base64-bytes.md +++ b/docs/de/docs/advanced/json-base64-bytes.md @@ -4,7 +4,7 @@ Wenn Ihre App JSON-Daten empfangen und senden muss, Sie darin aber Binärdaten e ## Base64 vs Dateien { #base64-vs-files } -Prüfen Sie zunächst, ob Sie [Request Files](../tutorial/request-files.md) zum Hochladen von Binärdaten und [Benutzerdefinierte Response – FileResponse](./custom-response.md#fileresponse--fileresponse-) zum Senden von Binärdaten verwenden können, anstatt sie in JSON zu kodieren. +Prüfen Sie zunächst, ob Sie [Requestdateien](../tutorial/request-files.md) zum Hochladen von Binärdaten und [Benutzerdefinierte Response – FileResponse](./custom-response.md#fileresponse) zum Senden von Binärdaten verwenden können, anstatt sie in JSON zu kodieren. JSON kann nur UTF-8-kodierte Strings enthalten, es kann daher keine rohen Bytes enthalten. diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md index 0d2471489..b5d49c7e8 100644 --- a/docs/de/docs/advanced/openapi-callbacks.md +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -12,7 +12,7 @@ Sehen wir uns das alles anhand eines Beispiels an. Stellen Sie sich vor, Sie entwickeln eine Anwendung, mit der Sie Rechnungen erstellen können. -Diese Rechnungen haben eine `id`, einen optionalen `title`, einen `customer` (Kunde) und ein `total` (Gesamtsumme). +Diese Rechnungen haben eine `id`, einen `title` (optional), einen `customer` und ein `total`. Der Benutzer Ihrer API (ein externer Entwickler) erstellt mit einem POST-Request eine Rechnung in Ihrer API. @@ -118,13 +118,13 @@ In diesem Fall ist es der `str`: "{$callback_url}/invoices/{$request.body.id}" ``` -Wenn Ihr API-Benutzer (der externe Entwickler) also einen Request an *Ihre API* sendet, via: +Wenn Ihr API-Benutzer (der externe Entwickler) also einen Request an *Ihre API* sendet, an: ``` https://yourapi.com/invoices/?callback_url=https://www.external.org/events ``` -mit einem JSON-Körper: +mit einem JSON-Body: ```JSON { @@ -167,13 +167,13 @@ Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-P An diesem Punkt haben Sie die benötigte(n) *Callback-Pfadoperation(en)* (diejenige(n), die der *externe Entwickler* in der *externen API* implementieren sollte) im Callback-Router, den Sie oben erstellt haben. -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: +Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer API*, um das Attribut `.routes` dieses Callback-Routers zu übergeben: {* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *} /// 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`. +Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callbacks=` übergeben, sondern dessen `.routes`, wie in `invoices_callback_router.routes`. FastAPI wird diese Routen verwenden, um die Callback-OpenAPI-Dokumentation zu generieren. /// diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md index e6984de74..fbec6996a 100644 --- a/docs/de/docs/advanced/openapi-webhooks.md +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -22,7 +22,7 @@ Mit **FastAPI**, mithilfe von OpenAPI, können Sie die Namen dieser Webhooks, di 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 ihres eigenen API-Codes automatisch generieren. -/// info | Info +/// note | Hinweis Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt. @@ -36,7 +36,7 @@ Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. -/// info | Info +/// note | Hinweis Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre App mit mehreren Dateien strukturieren. diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md index e6ff498eb..6899a582a 100644 --- a/docs/de/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -16,17 +16,11 @@ Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist. ### Verwendung des Namens der *Pfadoperation-Funktion* als operationId { #using-the-path-operation-function-name-as-the-operationid } -Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, können Sie über alle iterieren und die `operation_id` jeder *Pfadoperation* mit deren `APIRoute.name` überschreiben. +Wenn Sie die Funktionsnamen Ihrer APIs als `operationId`s verwenden möchten, können Sie `FastAPI` eine eigene `generate_unique_id_function` übergeben. -Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben. +Diese Funktion erhält jeweils die `APIRoute` und gibt die `operationId` zurück, die für diese Pfadoperation verwendet werden soll. -{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *} - -/// tip | Tipp - -Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. - -/// +{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2,5:6,9] *} /// warning | Achtung diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md index a0d90fe80..a334cc0bb 100644 --- a/docs/de/docs/advanced/response-change-status-code.md +++ b/docs/de/docs/advanced/response-change-status-code.md @@ -1,5 +1,6 @@ # Response – Statuscode ändern { #response-change-status-code } + Sie haben wahrscheinlich schon vorher gelesen, dass Sie einen Default-[Response-Statuscode](../tutorial/response-status-code.md) festlegen können. In manchen Fällen müssen Sie jedoch einen anderen als den Default-Statuscode zurückgeben. diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md index 672bbbe78..34eb6cfe9 100644 --- a/docs/de/docs/advanced/response-cookies.md +++ b/docs/de/docs/advanced/response-cookies.md @@ -1,5 +1,6 @@ # Response-Cookies { #response-cookies } + ## Einen `Response`-Parameter verwenden { #use-a-response-parameter } Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren. diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md index 4235e8db0..fb5db473c 100644 --- a/docs/de/docs/advanced/response-directly.md +++ b/docs/de/docs/advanced/response-directly.md @@ -16,9 +16,9 @@ Normalerweise erzielen Sie eine deutlich bessere Leistung, wenn Sie ein [Respons ## Eine `Response` zurückgeben { #return-a-response } -Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben. +Sie können eine `Response` oder jede Unterklasse davon zurückgeben. -/// info | Info +/// note | Hinweis `JSONResponse` selbst ist eine Unterklasse von `Response`. diff --git a/docs/de/docs/advanced/response-headers.md b/docs/de/docs/advanced/response-headers.md index bcec04be8..baf5715a3 100644 --- a/docs/de/docs/advanced/response-headers.md +++ b/docs/de/docs/advanced/response-headers.md @@ -38,4 +38,4 @@ Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, Beachten Sie, dass benutzerdefinierte proprietäre Header [mit dem Präfix `X-`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) hinzugefügt werden können. -Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen können soll, müssen Sie diese zu Ihrer CORS-Konfiguration hinzufügen (weitere Informationen finden Sie unter [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), unter Verwendung des Parameters `expose_headers`, dokumentiert in [Starlettes CORS-Dokumentation](https://www.starlette.dev/middleware/#corsmiddleware). +Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen können soll, müssen Sie diese zu Ihren CORS-Konfigurationen hinzufügen (weitere Informationen finden Sie unter [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md)), unter Verwendung des Parameters `expose_headers`, dokumentiert in [Starlettes CORS-Dokumentation](https://www.starlette.dev/middleware/#corsmiddleware). diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md index a903fbeb9..74457b40d 100644 --- a/docs/de/docs/advanced/security/oauth2-scopes.md +++ b/docs/de/docs/advanced/security/oauth2-scopes.md @@ -18,7 +18,7 @@ Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizier Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden. -Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten. +Dennoch erzwingen Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so, wie Sie es benötigen. In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein. @@ -46,7 +46,7 @@ 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 | Info +/// note | Hinweis In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. @@ -126,7 +126,7 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen {* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *} -/// info | Technische Details +/// note | Technische Details `Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. @@ -247,7 +247,7 @@ Das würde einer Drittanbieteranwendung passieren, die versucht, auf eine dieser ## Über Integrationen von Drittanbietern { #about-third-party-integrations } -In diesem Beispiel verwenden wir den OAuth2-Flow „Password“. +In diesem Beispiel verwenden wir den OAuth2-Flow „password“. Das ist angemessen, wenn wir uns bei unserer eigenen Anwendung anmelden, wahrscheinlich mit unserem eigenen Frontend. @@ -255,9 +255,9 @@ Weil wir darauf vertrauen können, dass es den `username` und das `password` erh Wenn Sie jedoch eine OAuth2-Anwendung erstellen, mit der andere eine Verbindung herstellen würden (d.h. wenn Sie einen Authentifizierungsanbieter erstellen, der Facebook, Google, GitHub usw. entspricht), sollten Sie einen der anderen Flows verwenden. -Am häufigsten ist der „Implicit“-Flow. +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. +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 diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md index 1df74802b..993e5ae71 100644 --- a/docs/de/docs/advanced/settings.md +++ b/docs/de/docs/advanced/settings.md @@ -14,13 +14,13 @@ Um Umgebungsvariablen zu verstehen, können Sie [Umgebungsvariablen](../environm ## Typen und Validierung { #types-and-validation } -Diese Umgebungsvariablen können nur Text-Zeichenketten verarbeiten, da sie außerhalb von Python liegen und mit anderen Programmen und dem Rest des Systems (und sogar mit verschiedenen Betriebssystemen wie Linux, Windows, macOS) kompatibel sein müssen. +Diese Umgebungsvariablen können nur Text-Strings verarbeiten, da sie außerhalb von Python liegen und mit anderen Programmen und dem Rest des Systems (und sogar mit verschiedenen Betriebssystemen wie Linux, Windows, macOS) kompatibel sein müssen. Das bedeutet, dass jeder in Python aus einer Umgebungsvariablen gelesene Wert ein `str` ist und jede Konvertierung in einen anderen Typ oder jede Validierung im Code erfolgen muss. ## Pydantic `Settings` { #pydantic-settings } -Glücklicherweise bietet Pydantic ein großartiges Werkzeug zur Verarbeitung dieser Einstellungen, die von Umgebungsvariablen stammen, mit [Pydantic: Settings Management](https://docs.pydantic.dev/latest/concepts/pydantic_settings/). +Glücklicherweise bietet Pydantic ein großartiges Werkzeug zur Verarbeitung dieser Einstellungen, die von Umgebungsvariablen stammen, mit [Pydantic: Settings-Verwaltung](https://docs.pydantic.dev/latest/concepts/pydantic_settings/). ### `pydantic-settings` installieren { #install-pydantic-settings } @@ -92,9 +92,9 @@ Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen S /// -Und dann würde die Einstellung `admin_email` auf „deadpool@example.com“ gesetzt. +Und dann würde die Einstellung `admin_email` auf `"deadpool@example.com"` gesetzt. -Der `app_name` wäre „ChimichangApp“. +Der `app_name` wäre `"ChimichangApp"`. Und `items_per_user` würde seinen Defaultwert von `50` behalten. @@ -128,7 +128,7 @@ Ausgehend vom vorherigen Beispiel könnte Ihre Datei `config.py` so aussehen: {* ../../docs_src/settings/app02_an_py310/config.py hl[10] *} -Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erstellen. +Beachten Sie, dass wir jetzt keine Defaultinstanz `settings = Settings()` erstellen. ### Die Haupt-Anwendungsdatei { #the-main-app-file } @@ -158,7 +158,7 @@ Bei der Abhängigkeitsüberschreibung legen wir einen neuen Wert für `admin_ema Dann können wir testen, ob das verwendet wird. -## Lesen einer `.env`-Datei { #reading-a-env-file } +## Eine `.env`-Datei lesen { #reading-a-env-file } Wenn Sie viele Einstellungen haben, die sich möglicherweise oft ändern, vielleicht in verschiedenen Umgebungen, kann es nützlich sein, diese in eine Datei zu schreiben und sie dann daraus zu lesen, als wären sie Umgebungsvariablen. @@ -172,7 +172,7 @@ Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. /// -Pydantic unterstützt das Lesen dieser Dateitypen mithilfe einer externen Bibliothek. Weitere Informationen finden Sie unter [Pydantic Settings: Dotenv (.env) support](https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support). +Pydantic unterstützt das Lesen dieser Dateitypen mithilfe einer externen Bibliothek. Weitere Informationen finden Sie unter [Pydantic Settings: Dotenv (.env)-Unterstützung](https://docs.pydantic.dev/latest/concepts/pydantic_settings/#dotenv-env-support). /// tip | Tipp @@ -197,13 +197,13 @@ Und dann aktualisieren Sie Ihre `config.py` mit: /// tip | Tipp -Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter [Pydantic: Concepts: Configuration](https://docs.pydantic.dev/latest/concepts/config/). +Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter [Pydantic: Konzepte: Konfiguration](https://docs.pydantic.dev/latest/concepts/config/). /// 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. -### Die `Settings` nur einmal laden mittels `lru_cache` { #creating-the-settings-only-once-with-lru-cache } +### Die `Settings` nur einmal mittels `lru_cache` erstellen { #creating-the-settings-only-once-with-lru-cache } Das Lesen einer Datei von der Festplatte ist normalerweise ein kostspieliger (langsamer) Vorgang, daher möchten Sie ihn wahrscheinlich nur einmal ausführen und dann dasselbe Einstellungsobjekt erneut verwenden, anstatt es für jeden Request zu lesen. @@ -291,7 +291,7 @@ Im Fall unserer Abhängigkeit `get_settings()` akzeptiert die Funktion nicht ein Auf diese Weise verhält es sich fast so, als wäre es nur eine globale Variable. Da es jedoch eine Abhängigkeitsfunktion verwendet, können wir diese zu Testzwecken problemlos überschreiben. -`@lru_cache` ist Teil von `functools`, welches Teil von Pythons Standardbibliothek ist. Weitere Informationen dazu finden Sie in der [Python Dokumentation für `@lru_cache`](https://docs.python.org/3/library/functools.html#functools.lru_cache). +`@lru_cache` ist Teil von `functools`, welches Teil von Pythons Standardbibliothek ist. Weitere Informationen dazu finden Sie in der [Python-Dokumentation für `@lru_cache`](https://docs.python.org/3/library/functools.html#functools.lru_cache). ## Zusammenfassung { #recap } diff --git a/docs/de/docs/advanced/stream-data.md b/docs/de/docs/advanced/stream-data.md index 7cff1d47e..16ff73e78 100644 --- a/docs/de/docs/advanced/stream-data.md +++ b/docs/de/docs/advanced/stream-data.md @@ -4,7 +4,7 @@ Wenn Sie Daten streamen möchten, die als JSON strukturiert werden können, soll Wenn Sie jedoch **reine Binärdaten** oder Strings streamen möchten, so können Sie es machen. -/// info | Info +/// note | Hinweis Hinzugefügt in FastAPI 0.134.0. @@ -20,13 +20,13 @@ Sie könnten auf diese Weise auch **Video** oder **Audio** streamen, es könnte ## Eine `StreamingResponse` mit `yield` { #a-streamingresponse-with-yield } -Wenn Sie in Ihrer Pfadoperation-Funktion ein `response_class=StreamingResponse` deklarieren, können Sie `yield` verwenden, um nacheinander jeden Datenchunk zu senden. +Wenn Sie in Ihrer *Pfadoperation-Funktion* ein `response_class=StreamingResponse` deklarieren, können Sie `yield` verwenden, um nacheinander jeden Datenchunk zu senden. {* ../../docs_src/stream_data/tutorial001_py310.py ln[1:23] hl[20,23] *} FastAPI übergibt jeden Datenchunk unverändert an die `StreamingResponse`, es wird nicht versucht, ihn in JSON oder etwas Ähnliches zu konvertieren. -### Nicht-async-Pfadoperation-Funktionen { #non-async-path-operation-functions } +### Nicht-async-*Pfadoperation-Funktionen* { #non-async-path-operation-functions } Sie können auch reguläre `def`-Funktionen (ohne `async`) verwenden und `yield` auf die gleiche Weise einsetzen. @@ -58,7 +58,7 @@ Zum Beispiel können Sie eine `PNGStreamingResponse` erstellen, die den `Content {* ../../docs_src/stream_data/tutorial002_py310.py ln[6,19:20] hl[20] *} -Dann können Sie diese neue Klasse mit `response_class=PNGStreamingResponse` in Ihrer Pfadoperation-Funktion verwenden: +Dann können Sie diese neue Klasse mit `response_class=PNGStreamingResponse` in Ihrer *Pfadoperation-Funktion* verwenden: {* ../../docs_src/stream_data/tutorial002_py310.py ln[23:27] hl[23] *} @@ -90,7 +90,7 @@ Beispielsweise haben sie kein `await file.read()` oder `async for chunk in file` Und in vielen Fällen wäre das Lesen eine blockierende Operation (die die Event-Loop blockieren könnte), weil von der Festplatte oder aus dem Netzwerk gelesen wird. -/// info | Info +/// note | Hinweis Das obige Beispiel ist tatsächlich eine Ausnahme, weil sich das `io.BytesIO`-Objekt bereits im Speicher befindet, daher blockiert sein Lesen nichts. @@ -98,7 +98,7 @@ Aber in vielen Fällen würde das Lesen einer Datei oder eines dateiähnlichen O /// -Um die Event-Loop nicht zu blockieren, können Sie die Pfadoperation-Funktion einfach mit normalem `def` statt `async def` deklarieren, dadurch führt FastAPI sie in einem Threadpool-Worker aus, um die Haupt-Event-Loop nicht zu blockieren. +Um die Event-Loop nicht zu blockieren, können Sie die *Pfadoperation-Funktion* einfach mit normalem `def` statt `async def` deklarieren, dadurch führt FastAPI sie in einem Threadpool-Worker aus, um die Haupt-Event-Loop nicht zu blockieren. {* ../../docs_src/stream_data/tutorial002_py310.py ln[30:34] hl[31] *} diff --git a/docs/de/docs/advanced/strict-content-type.md b/docs/de/docs/advanced/strict-content-type.md index 2fcfa3e09..db9ab9f24 100644 --- a/docs/de/docs/advanced/strict-content-type.md +++ b/docs/de/docs/advanced/strict-content-type.md @@ -81,7 +81,7 @@ Wenn Sie Clients unterstützen müssen, die keinen `Content-Type`-Header senden, Mit dieser Einstellung werden Requests ohne `Content-Type`-Header im Body als JSON geparst. Das entspricht dem Verhalten älterer FastAPI-Versionen. -/// info | Info +/// note | Hinweis Dieses Verhalten und diese Konfiguration wurden in FastAPI 0.132.0 hinzugefügt. diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md index c96cfb28b..a0f3a1f33 100644 --- a/docs/de/docs/advanced/websockets.md +++ b/docs/de/docs/advanced/websockets.md @@ -111,7 +111,7 @@ Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfa {* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *} -/// info | Info +/// note | Hinweis Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus. diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md index 89e513dc0..353734a3a 100644 --- a/docs/de/docs/advanced/wsgi.md +++ b/docs/de/docs/advanced/wsgi.md @@ -1,12 +1,13 @@ # WSGI inkludieren – Flask, Django und andere { #including-wsgi-flask-django-others } + Sie können WSGI-Anwendungen mounten, wie Sie es in [Unteranwendungen – Mounts](sub-applications.md), [Hinter einem Proxy](behind-a-proxy.md) gesehen haben. Dazu können Sie die `WSGIMiddleware` verwenden und damit Ihre WSGI-Anwendung wrappen, zum Beispiel Flask, Django usw. ## `WSGIMiddleware` verwenden { #using-wsgimiddleware } -/// info | Info +/// note | Hinweis Dafür muss `a2wsgi` installiert sein, z. B. mit `pip install a2wsgi`. diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md index 910f3b972..5a814cb55 100644 --- a/docs/de/docs/alternatives.md +++ b/docs/de/docs/alternatives.md @@ -36,7 +36,7 @@ Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer vo /// -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu Eine automatische API-Dokumentationsoberfläche zu haben. @@ -56,7 +56,7 @@ Diese Entkopplung der Teile und die Tatsache, dass es sich um ein „Mikroframew Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden. -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. @@ -98,7 +98,7 @@ def read_url(): Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an. -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu * Über eine einfache und intuitive API zu verfügen. * HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. @@ -118,7 +118,7 @@ Irgendwann wurde Swagger an die Linux Foundation übergeben und in OpenAPI umben Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“. -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. @@ -147,7 +147,7 @@ Für diese Funktionen wurde Marshmallow entwickelt. Es ist eine großartige Bibl Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein Schema zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden. -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. @@ -163,13 +163,13 @@ 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 | Info +/// note | Hinweis Webargs wurde von denselben Marshmallow-Entwicklern erstellt. /// -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu Eingehende Requestdaten automatisch zu validieren. @@ -193,13 +193,13 @@ 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 | Info +/// note | Hinweis APISpec wurde von denselben Marshmallow-Entwicklern erstellt. /// -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu Den offenen Standard für APIs, OpenAPI, zu unterstützen. @@ -225,13 +225,13 @@ 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). -/// info | Info +/// note | Hinweis Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. /// -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. @@ -251,7 +251,7 @@ Da TypeScript-Daten jedoch nach der Kompilierung nach JavaScript nicht erhalten Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body im Request 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** +/// tip | Inspirierte **FastAPI** dazu Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. @@ -271,7 +271,7 @@ Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchm /// -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu Einen Weg zu finden, eine hervorragende Performanz zu haben. @@ -283,11 +283,11 @@ Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste ver Falcon ist ein weiteres leistungsstarkes Python-Framework. Es ist minimalistisch konzipiert und dient als Grundlage für andere Frameworks wie Hug. -Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter empfangen, einen „Request“ und eine „Response“. Dann „lesen“ Sie Teile des Requests und „schreiben“ Teile der Response. Aufgrund dieses Designs ist es nicht möglich, Request-Parameter und -Bodys mit Standard-Python-Typhinweisen als Funktionsparameter zu deklarieren. +Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter empfangen, einen „Request“ und eine „Response“. Dann „lesen“ Sie Teile des Requests und „schreiben“ Teile der Response. Aufgrund dieses Designs ist es nicht möglich, Request-Parameter und Requestbodys mit Standard-Python-Typhinweisen als Funktionsparameter zu deklarieren. 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** +/// tip | Inspirierte **FastAPI** dazu Wege zu finden, eine großartige Performanz zu erzielen. @@ -313,7 +313,7 @@ Das Dependency Injection System erfordert eine Vorab-Registrierung der Abhängig Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind. -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu 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. @@ -335,13 +335,13 @@ 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 | Info +/// note | Hinweis Hug wurde von Timothy Crosley erstellt, demselben Schöpfer von [`isort`](https://github.com/timothycrosley/isort), einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien. /// -/// check | Ideen, die **FastAPI** inspiriert haben +/// tip | Ideen, die **FastAPI** inspiriert haben Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar. @@ -351,11 +351,11 @@ Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu de /// -### [APIStar](https://github.com/encode/apistar) (≦ 0.5) { #apistar-0-5 } +### [APIStar](https://github.com/encode/apistar) (<= 0.5) { #apistar-0-5 } Kurz bevor ich mich entschied, **FastAPI** zu erstellen, fand ich den **APIStar**-Server. Er hatte fast alles, was ich suchte, und ein tolles Design. -Er war eine der ersten Implementierungen eines Frameworks, die ich je gesehen hatte (vor NestJS und Molten), welches Python-Typhinweise zur Deklaration von Parametern und Requests verwendeten. Ich habe ihn mehr oder weniger zeitgleich mit Hug gefunden. Aber APIStar nutzte den OpenAPI-Standard. +Er war eine der ersten Implementierungen eines Frameworks, die ich je gesehen hatte (vor NestJS und Molten), das Python-Typhinweise zur Deklaration von Parametern und Requests verwendete. Ich habe ihn mehr oder weniger zeitgleich mit Hug gefunden. Aber APIStar nutzte den OpenAPI-Standard. Er verfügte an mehreren Stellen über automatische Datenvalidierung, Datenserialisierung und OpenAPI-Schemagenerierung, basierend auf denselben Typhinweisen. @@ -375,7 +375,7 @@ 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 | Info +/// note | Hinweis APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat: @@ -385,7 +385,7 @@ APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt ha /// -/// check | Inspirierte **FastAPI** +/// tip | Inspirierte **FastAPI** dazu Zu existieren. @@ -409,7 +409,7 @@ 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 +/// tip | **FastAPI** verwendet es, um Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen. @@ -433,7 +433,7 @@ Es bietet: * CORS, GZip, statische Dateien, Responses streamen. * Session- und Cookie-Unterstützung. * 100 % Testabdeckung. -* 100 % Typannotierte Codebasis. +* 100 % typannotierte Codebasis. * Wenige starke Abhängigkeiten. Starlette ist derzeit das schnellste getestete Python-Framework. Nur übertroffen von Uvicorn, welches kein Framework, sondern ein Server ist. @@ -448,11 +448,11 @@ Das ist eines der wichtigsten Dinge, welche **FastAPI** hinzufügt, alles basier 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 jedem anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können. /// -/// check | **FastAPI** verwendet es, um +/// tip | **FastAPI** verwendet es, um Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf. @@ -470,7 +470,7 @@ 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 +/// tip | **FastAPI** empfiehlt es als Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen. diff --git a/docs/de/docs/async.md b/docs/de/docs/async.md index 066a9d9f6..060e39bf9 100644 --- a/docs/de/docs/async.md +++ b/docs/de/docs/async.md @@ -44,7 +44,7 @@ Wenn Ihre Anwendung (irgendwie) nicht mit etwas anderem kommunizieren und auf de --- -Wenn Sie sich unsicher sind, verwenden Sie einfach `def`. +Wenn Sie sich unsicher sind, verwenden Sie normales `def`. --- @@ -70,7 +70,7 @@ Asynchroner Code bedeutet lediglich, dass die Sprache 💬 eine Möglichkeit hat Während der Zeit, die „Langsam-Datei“ 📝 benötigt, kann das System also andere Aufgaben erledigen. -Dann kommt der Computer / das Programm 🤖 bei jeder Gelegenheit zurück, weil es entweder wieder wartet oder wann immer es 🤖 die ganze Arbeit erledigt hat, die zu diesem Zeitpunkt zu tun war. Und es 🤖 wird nachschauen, ob eine der Aufgaben, auf die es gewartet hat, fertig ist. +Dann kommt der Computer / das Programm 🤖 bei jeder Gelegenheit zurück, weil es entweder wieder wartet oder wann immer es 🤖 die ganze Arbeit erledigt hat, die zu diesem Zeitpunkt zu tun war. Und es 🤖 wird nachschauen, ob eine der Aufgaben, auf die es gewartet hat, bereits fertig ist, und tun, was es zu tun hatte. Dann nimmt es 🤖 die erste erledigte Aufgabe (sagen wir, unsere „Langsam-Datei“ 📝) und bearbeitet sie weiter. @@ -139,7 +139,7 @@ Sie und Ihr Schwarm essen die Burger und haben eine schöne Zeit. ✨ -/// info | Info +/// note | Hinweis Die wunderschönen Illustrationen stammen von [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨 @@ -205,7 +205,7 @@ 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 | Info +/// note | Hinweis Die wunderschönen Illustrationen stammen von [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨 @@ -361,7 +361,7 @@ Wenn Sie mit **FastAPI** arbeiten, müssen Sie sich darüber keine Sorgen machen Wenn Sie jedoch `async` / `await` ohne FastAPI verwenden möchten, können Sie dies auch tun. -### Schreiben Sie Ihren eigenen asynchronen Code { #write-your-own-async-code } +### Ihren eigenen asynchronen Code schreiben { #write-your-own-async-code } Starlette (und **FastAPI**) basieren auf [AnyIO](https://anyio.readthedocs.io/en/stable/), was bedeutet, dass es sowohl kompatibel mit der Python-Standardbibliothek [asyncio](https://docs.python.org/3/library/asyncio-task.html) als auch mit [Trio](https://trio.readthedocs.io/en/stable/) ist. diff --git a/docs/de/docs/deployment/cloud.md b/docs/de/docs/deployment/cloud.md index 2c8fe85c4..75f7ef881 100644 --- a/docs/de/docs/deployment/cloud.md +++ b/docs/de/docs/deployment/cloud.md @@ -16,7 +16,7 @@ FastAPI Cloud ist der Hauptsponsor und Finanzierungsgeber für die *FastAPI and ## Cloudanbieter – Sponsoren { #cloud-providers-sponsors } -Einige andere Cloudanbieter ✨ [**sponsern FastAPI**](../help-fastapi.md#sponsor-the-author) ✨ ebenfalls. 🙇 +Einige andere Cloudanbieter ✨ [**sponsern FastAPI**](https://github.com/sponsors/tiangolo) ✨ ebenfalls. 🙇 Sie könnten diese ebenfalls in Betracht ziehen, deren Anleitungen folgen und ihre Dienste ausprobieren: diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md index be00b2260..487ad6392 100644 --- a/docs/de/docs/deployment/concepts.md +++ b/docs/de/docs/deployment/concepts.md @@ -1,6 +1,6 @@ # Deployment-Konzepte { #deployments-concepts } -Bei dem Deployment – der Bereitstellung – einer **FastAPI**-Anwendung, oder eigentlich jeder Art von Web-API, gibt es mehrere Konzepte, die Sie wahrscheinlich interessieren, und mithilfe der Sie die **am besten geeignete** Methode zum **Deployment Ihrer Anwendung** finden können. +Beim Deployment einer **FastAPI**-Anwendung, oder eigentlich jeder Art von Web-API, gibt es mehrere Konzepte, die Sie wahrscheinlich interessieren, und mithilfe derer Sie die **am besten geeignete** Methode zum **Deployment Ihrer Anwendung** finden können. Einige wichtige Konzepte sind: @@ -59,7 +59,7 @@ Die nächsten zu berücksichtigenden Konzepte drehen sich dann um das Programm, Wir werden viel über den laufenden „**Prozess**“ sprechen, daher ist es nützlich, Klarheit darüber zu haben, was das bedeutet und was der Unterschied zum Wort „**Programm**“ ist. -### Was ist ein Programm { #what-is-a-program } +### Was ein Programm ist { #what-is-a-program } Das Wort **Programm** wird häufig zur Beschreibung vieler Dinge verwendet: @@ -67,14 +67,14 @@ Das Wort **Programm** wird häufig zur Beschreibung vieler Dinge verwendet: * Die **Datei**, die vom Betriebssystem **ausgeführt** werden kann, zum Beispiel: `python`, `python.exe` oder `uvicorn`. * Ein bestimmtes Programm, während es auf dem Betriebssystem **läuft**, die CPU nutzt und Dinge im Arbeitsspeicher ablegt. Dies wird auch als **Prozess** bezeichnet. -### Was ist ein Prozess { #what-is-a-process } +### Was ein Prozess ist { #what-is-a-process } Das Wort **Prozess** wird normalerweise spezifischer verwendet und bezieht sich nur auf das, was im Betriebssystem ausgeführt wird (wie im letzten Punkt oben): * Ein bestimmtes Programm, während es auf dem Betriebssystem **ausgeführt** wird. * Dies bezieht sich weder auf die Datei noch auf den Code, sondern **speziell** auf das, was vom Betriebssystem **ausgeführt** und verwaltet wird. -* Jedes Programm, jeder Code **kann nur dann Dinge tun**, wenn er **ausgeführt** wird, wenn also ein **Prozess läuft**. -* Der Prozess kann von Ihnen oder vom Betriebssystem **terminiert** („beendet“, „gekillt“) werden. An diesem Punkt hört es auf zu laufen/ausgeführt zu werden und kann **keine Dinge mehr tun**. +* Jedes Programm, jeder Code **kann nur dann Dinge tun**, wenn er **ausgeführt** wird. Also dann, wenn ein **Prozess läuft**. +* Der Prozess kann von Ihnen oder vom Betriebssystem **terminiert** („beendet“, „gekillt“) werden. An diesem Punkt hört er auf zu laufen/ausgeführt zu werden und kann **keine Dinge mehr tun**. * Hinter jeder Anwendung, die Sie auf Ihrem Computer ausführen, steckt ein Prozess, jedes laufende Programm, jedes Fenster usw. Und normalerweise laufen viele Prozesse **gleichzeitig**, während ein Computer eingeschaltet ist. * Es können **mehrere Prozesse** desselben **Programms** gleichzeitig ausgeführt werden. @@ -117,7 +117,7 @@ Einige Beispiele für Tools, die diese Aufgabe übernehmen können, sind: * Docker * Kubernetes * Docker Compose -* Docker im Schwarm-Modus +* Docker im Swarm-Modus * Systemd * Supervisor * Es wird intern von einem Cloudanbieter im Rahmen seiner Dienste verwaltet @@ -137,7 +137,7 @@ Und wir als Entwickler verbessern den Code ständig, wenn wir diese Bugs finden ### Kleine Fehler automatisch handhaben { #small-errors-automatically-handled } -Wenn beim Erstellen von Web-APIs mit FastAPI ein Fehler in unserem Code auftritt, wird FastAPI ihn normalerweise dem einzelnen Request zurückgeben, der den Fehler ausgelöst hat. 🛡 +Wenn beim Erstellen von Web-APIs mit FastAPI ein Fehler in unserem Code auftritt, wird FastAPI ihn normalerweise auf den einzelnen Request beschränken, der den Fehler ausgelöst hat. 🛡 Der Client erhält für diesen Request einen **500 Internal Server Error**, aber die Anwendung arbeitet bei den nächsten Requests weiter, anstatt einfach komplett abzustürzen. @@ -170,7 +170,7 @@ Dies könnte zum Beispiel erledigt werden durch: * Docker * Kubernetes * Docker Compose -* Docker im Schwarm-Modus +* Docker im Swarm-Modus * Systemd * Supervisor * Intern von einem Cloudanbieter im Rahmen seiner Dienste @@ -178,7 +178,7 @@ Dies könnte zum Beispiel erledigt werden durch: ## Replikation – Prozesse und Arbeitsspeicher { #replication-processes-and-memory } -Wenn Sie eine FastAPI-Anwendung verwenden und ein Serverprogramm wie den `fastapi`-Befehl, der Uvicorn ausführt, kann **ein einzelner Prozess** an mehrere Clients gleichzeitig ausliefern. +Wenn Sie eine FastAPI-Anwendung verwenden und ein Serverprogramm wie den `fastapi`-Befehl, der Uvicorn ausführt, kann die Ausführung in **einem Prozess** mehrere Clients gleichzeitig versorgen. In vielen Fällen möchten Sie jedoch mehrere Workerprozesse gleichzeitig ausführen. @@ -200,7 +200,7 @@ Um also **mehrere Prozesse** gleichzeitig zu haben, muss es einen **einzelnen Pr Wenn das Programm nun Dinge in den Arbeitsspeicher lädt, zum Beispiel ein Modell für maschinelles Lernen in einer Variablen oder den Inhalt einer großen Datei in einer Variablen, verbraucht das alles **einen Teil des Arbeitsspeichers (RAM – Random Access Memory)** des Servers. -Und mehrere Prozesse teilen sich normalerweise keinen Speicher. Das bedeutet, dass jeder laufende Prozess seine eigenen Dinge, eigenen Variablen und eigenen Speicher hat. Und wenn Sie in Ihrem Code viel Speicher verbrauchen, verbraucht **jeder Prozess** die gleiche Menge Speicher. +Und mehrere Prozesse **teilen sich normalerweise keinen Speicher**. Das bedeutet, dass jeder laufende Prozess seine eigenen Dinge, eigenen Variablen und eigenen Speicher hat. Und wenn Sie in Ihrem Code viel Speicher verbrauchen, verbraucht **jeder Prozess** die gleiche Menge Speicher. ### Serverspeicher { #server-memory } diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md index ee230d5d1..0ab886c46 100644 --- a/docs/de/docs/deployment/docker.md +++ b/docs/de/docs/deployment/docker.md @@ -36,7 +36,7 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"] Container (hauptsächlich Linux-Container) sind eine sehr **leichtgewichtige** Möglichkeit, Anwendungen einschließlich aller ihrer Abhängigkeiten und erforderlichen Dateien zu verpacken und sie gleichzeitig von anderen Containern (anderen Anwendungen oder Komponenten) im selben System isoliert zu halten. -Linux-Container werden mit demselben Linux-Kernel des Hosts (Maschine, virtuellen Maschine, Cloud-Servers, usw.) ausgeführt. Das bedeutet einfach, dass sie sehr leichtgewichtig sind (im Vergleich zu vollständigen virtuellen Maschinen, die ein gesamtes Betriebssystem emulieren). +Linux-Container werden mit demselben Linux-Kernel des Hosts (Maschine, virtueller Maschine, Cloud-Server usw.) ausgeführt. Das bedeutet einfach, dass sie sehr leichtgewichtig sind (im Vergleich zu vollständigen virtuellen Maschinen, die ein gesamtes Betriebssystem emulieren). Auf diese Weise verbrauchen Container **wenig Ressourcen**, eine Menge vergleichbar mit der direkten Ausführung der Prozesse (eine virtuelle Maschine würde viel mehr verbrauchen). @@ -46,7 +46,7 @@ Container verfügen außerdem über ihre eigenen **isoliert** laufenden Prozesse Ein **Container** wird von einem **Containerimage** ausgeführt. -Ein Containerimage ist eine **statische** Version aller Dateien, Umgebungsvariablen und des Standardbefehls/-programms, welche in einem Container vorhanden sein sollten. **Statisch** bedeutet hier, dass das Container-**Image** nicht läuft, nicht ausgeführt wird, sondern nur die gepackten Dateien und Metadaten enthält. +Ein Containerimage ist eine **statische** Version aller Dateien, Umgebungsvariablen und des Standardbefehls/-programms, die in einem Container vorhanden sein sollten. **Statisch** bedeutet hier, dass das Container-**Image** nicht läuft, nicht ausgeführt wird, sondern nur die gepackten Dateien und Metadaten enthält. Im Gegensatz zu einem „**Containerimage**“, bei dem es sich um den gespeicherten statischen Inhalt handelt, bezieht sich ein „**Container**“ normalerweise auf die laufende Instanz, das Ding, das **ausgeführt** wird. @@ -89,7 +89,7 @@ Ein Container läuft, solange der **Hauptprozess** (Befehl oder Programm) läuft Ein Container hat normalerweise einen **einzelnen Prozess**, aber es ist auch möglich, Unterprozesse vom Hauptprozess aus zu starten, und auf diese Weise haben Sie **mehrere Prozesse** im selben Container. -Es ist jedoch nicht möglich, einen laufenden Container, ohne **mindestens einen laufenden Prozess** zu haben. Wenn der Hauptprozess stoppt, stoppt der Container. +Es ist jedoch nicht möglich, einen laufenden Container ohne **mindestens einen laufenden Prozess** zu haben. Wenn der Hauptprozess stoppt, stoppt der Container. ## Ein Docker-Image für FastAPI erstellen { #build-a-docker-image-for-fastapi } @@ -132,7 +132,7 @@ Successfully installed fastapi pydantic -/// info | Info +/// note | Hinweis Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten. @@ -184,19 +184,19 @@ COPY ./app /code/app CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` -1. Beginne mit dem offiziellen Python-Basisimage. +1. Beginnen Sie mit dem offiziellen Python-Basisimage. -2. Setze das aktuelle Arbeitsverzeichnis auf `/code`. +2. Setzen Sie das aktuelle Arbeitsverzeichnis auf `/code`. Hier platzieren wir die Datei `requirements.txt` und das Verzeichnis `app`. -3. Kopiere die Datei mit den Paketanforderungen in das Verzeichnis `/code`. +3. Kopieren Sie die Datei mit den Paketanforderungen in das Verzeichnis `/code`. Kopieren Sie zuerst **nur** die Datei mit den Anforderungen, nicht den Rest des Codes. Da sich diese Datei **nicht oft ändert**, erkennt Docker das und verwendet den **Cache** für diesen Schritt, wodurch der Cache auch für den nächsten Schritt aktiviert wird. -4. Installiere die Paketabhängigkeiten aus der Anforderungsdatei. +4. Installieren Sie die Paketabhängigkeiten aus der Anforderungsdatei. 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. @@ -212,13 +212,13 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"] Durch die Verwendung des Caches in diesem Schritt **sparen** Sie viel **Zeit**, wenn Sie das Image während der Entwicklung immer wieder erstellen, anstatt **jedes Mal** alle Abhängigkeiten **herunterzuladen und zu installieren**. -5. Kopiere das Verzeichnis `./app` in das Verzeichnis `/code`. +5. Kopieren Sie das Verzeichnis `./app` in das Verzeichnis `/code`. Da hier der gesamte Code enthalten ist, der sich **am häufigsten ändert**, wird der Docker-**Cache** nicht ohne weiteres für diesen oder andere **folgende Schritte** verwendet. Daher ist es wichtig, dies **nahe dem Ende** des `Dockerfile`s zu platzieren, um die Erstellungszeiten des Containerimages zu optimieren. -6. Lege den **Befehl** fest, um `fastapi run` zu nutzen, welches Uvicorn darunter verwendet. +6. Legen Sie den **Befehl** fest, um `fastapi run` zu nutzen, welches Uvicorn darunter verwendet. `CMD` nimmt eine Liste von Zeichenfolgen entgegen. Jede dieser Zeichenfolgen entspricht dem, was Sie durch Leerzeichen getrennt in die Befehlszeile eingeben würden. @@ -334,7 +334,7 @@ $ docker build -t myimage . 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 Case handelt es sich um dasselbe aktuelle Verzeichnis (`.`). /// @@ -405,7 +405,7 @@ COPY ./main.py /code/ CMD ["fastapi", "run", "main.py", "--port", "80"] ``` -1. Kopiere die Datei `main.py` direkt in das Verzeichnis `/code` (ohne ein Verzeichnis `./app`). +1. Kopieren Sie die Datei `main.py` direkt in das Verzeichnis `/code` (ohne ein Verzeichnis `./app`). 2. Verwenden Sie `fastapi run`, um Ihre Anwendung in der einzelnen Datei `main.py` bereitzustellen. @@ -440,7 +440,7 @@ Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass /// -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). +Alternativ könnte HTTPS von einem Cloudanbieter als einer seiner Dienste gehandhabt werden (während die Anwendung weiterhin in einem Container ausgeführt wird). ## Beim Hochfahren ausführen und Neustarts { #running-on-startup-and-restarts } @@ -488,7 +488,7 @@ Und normalerweise wäre dieser **Load Balancer** in der Lage, Requests zu verarb In einem solchen Szenario möchten Sie wahrscheinlich **einen einzelnen (Uvicorn-)Prozess pro Container** haben, da Sie die Replikation bereits auf Cluster-Ebene durchführen würden. -In diesem Fall möchten Sie also **nicht** mehrere Worker im Container haben, z. B. mit der `--workers` Befehlszeilenoption. Sie möchten nur einen **einzelnen Uvicorn-Prozess** pro Container haben (wahrscheinlich aber mehrere Container). +In diesem Fall möchten Sie also **nicht** mehrere Worker im Container haben, z. B. mit der `--workers`-Befehlszeilenoption. Sie möchten nur einen **einzelnen Uvicorn-Prozess** pro Container haben (wahrscheinlich aber mehrere Container). Ein weiterer Prozessmanager im Container (wie es bei mehreren Workern der Fall wäre) würde nur **unnötige Komplexität** hinzufügen, um welche Sie sich höchstwahrscheinlich bereits mit Ihrem Clustersystem kümmern. @@ -496,7 +496,7 @@ Ein weiterer Prozessmanager im Container (wie es bei mehreren Workern der Fall w Natürlich gibt es **Sonderfälle**, in denen Sie **einen Container** mit mehreren **Uvicorn-Workerprozessen** haben möchten. -In diesen Fällen können Sie die `--workers` Befehlszeilenoption verwenden, um die Anzahl der zu startenden Worker festzulegen: +In diesen Fällen können Sie die `--workers`-Befehlszeilenoption verwenden, um die Anzahl der zu startenden Worker festzulegen: ```{ .dockerfile .annotate } FROM python:3.14 @@ -513,7 +513,7 @@ COPY ./app /code/app CMD ["fastapi", "run", "app/main.py", "--port", "80", "--workers", "4"] ``` -1. Hier verwenden wir die `--workers` Befehlszeilenoption, um die Anzahl der Worker auf 4 festzulegen. +1. Hier verwenden wir die `--workers`-Befehlszeilenoption, um die Anzahl der Worker auf 4 festzulegen. Hier sind einige Beispiele, wann das sinnvoll sein könnte: @@ -529,7 +529,7 @@ Dann möchten Sie vielleicht **einen einzelnen Container** mit einem **Prozessma --- -Der Hauptpunkt ist, dass **keine** dieser Regeln **in Stein gemeißelt** ist, der man blind folgen muss. Sie können diese Ideen verwenden, um **Ihren eigenen Anwendungsfall zu evaluieren**, zu entscheiden, welcher Ansatz für Ihr System am besten geeignet ist und herauszufinden, wie Sie folgende Konzepte verwalten: +Der Hauptpunkt ist, dass **keine** dieser Regeln **in Stein gemeißelt** ist, der man blind folgen muss. Sie können diese Ideen verwenden, um **I Ihren eigenen Anwendungsfall zu evaluieren**, zu entscheiden, welcher Ansatz für Ihr System am besten geeignet ist und herauszufinden, wie Sie folgende Konzepte verwalten: * Sicherheit – HTTPS * Beim Hochfahren ausführen @@ -556,7 +556,7 @@ 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 einzelnen Prozess ausführt, **bevor** die replizierten Workercontainer ausgeführt werden. -/// info | Info +/// note | Hinweis Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein [Init-Container](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/). @@ -576,7 +576,7 @@ Sie sollten wahrscheinlich **nicht** dieses Basis-Docker-Image (oder ein anderes Wenn Sie **Kubernetes** (oder andere) verwenden und bereits **Replikation** auf Cluster-Ebene mit mehreren **Containern** eingerichtet haben. In diesen Fällen ist es besser, **ein Image von Grund auf neu zu erstellen**, wie oben beschrieben: [Ein Docker-Image für FastAPI erstellen](#build-a-docker-image-for-fastapi). -Und wenn Sie mehrere Worker benötigen, können Sie einfach die `--workers` Befehlszeilenoption verwenden. +Und wenn Sie mehrere Worker benötigen, können Sie einfach die `--workers`-Befehlszeilenoption verwenden. /// note | Technische Details diff --git a/docs/de/docs/deployment/fastapicloud.md b/docs/de/docs/deployment/fastapicloud.md index c77826aaf..d563fd822 100644 --- a/docs/de/docs/deployment/fastapicloud.md +++ b/docs/de/docs/deployment/fastapicloud.md @@ -1,26 +1,6 @@ # FastAPI Cloud { #fastapi-cloud } -Sie können Ihre FastAPI-App in der [FastAPI Cloud](https://fastapicloud.com) mit **einem einzigen Befehl** deployen – tragen Sie sich in die Warteliste ein, falls noch nicht geschehen. 🚀 - -## Anmelden { #login } - -Stellen Sie sicher, dass Sie bereits ein **FastAPI-Cloud-Konto** haben (wir haben Sie von der Warteliste eingeladen 😉). - -Melden Sie sich dann an: - -
- -```console -$ fastapi login - -You are logged in to FastAPI Cloud 🚀 -``` - -
- -## Deployen { #deploy } - -Stellen Sie Ihre App jetzt mit **einem einzigen Befehl** bereit: +Sie können Ihre FastAPI-App in der [FastAPI Cloud](https://fastapicloud.com) mit **einem einzigen Befehl** deployen. 🚀
@@ -36,6 +16,8 @@ Deploying to FastAPI Cloud...
+Das CLI erkennt Ihre FastAPI-App automatisch und deployt sie in die Cloud. Wenn Sie nicht angemeldet sind, öffnet sich Ihr Browser, um den Authentifizierungsprozess abzuschließen. + Das war’s! Jetzt können Sie Ihre App unter dieser URL aufrufen. ✨ ## Über FastAPI Cloud { #about-fastapi-cloud } @@ -62,4 +44,4 @@ Folgen Sie den Anleitungen Ihres Cloudanbieters, um dort FastAPI-Apps zu deploye ## Auf den eigenen Server deployen { #deploy-your-own-server } -Ich werde Ihnen später in diesem **Deployment-Leitfaden** auch alle Details zeigen, sodass Sie verstehen, was passiert, was geschehen muss und wie Sie FastAPI-Apps selbst deployen können, auch auf Ihre eigenen Server. 🤓 +Ich werde Ihnen später in diesem **Deployment**-Leitfaden auch alle Details zeigen, sodass Sie verstehen, was passiert, was geschehen muss und wie Sie FastAPI-Apps selbst deployen können, auch auf Ihre eigenen Server. 🤓 diff --git a/docs/de/docs/deployment/https.md b/docs/de/docs/deployment/https.md index 0f97909c2..b4c49ff4d 100644 --- a/docs/de/docs/deployment/https.md +++ b/docs/de/docs/deployment/https.md @@ -21,10 +21,10 @@ Aus **Sicht des Entwicklers** sollten Sie beim Nachdenken über HTTPS Folgendes * Und dann müssen sie vom Dritten **erneuert**, **erneut erworben** werden. * Die Verschlüsselung der Verbindung erfolgt auf **TCP-Ebene**. * Das ist eine Schicht **unter HTTP**. - * Die Handhabung von **Zertifikaten und Verschlüsselung** erfolgt also **vor HTTP**. + * Die **Zertifikats- und Verschlüsselungs**-Handhabung erfolgt also **vor HTTP**. * **TCP weiß nichts über „Domains“**. Nur über IP-Adressen. * Die Informationen über die angeforderte **spezifische Domain** befinden sich in den **HTTP-Daten**. -* Die **HTTPS-Zertifikate** „zertifizieren“ eine **bestimmte Domain**, aber das Protokoll und die Verschlüsselung erfolgen auf TCP-Ebene, **ohne zu wissen**, um welche Domain es sich handelt. +* Die **HTTPS-Zertifikate** „zertifizieren“ eine **bestimmte Domain**, aber das Protokoll und die Verschlüsselung erfolgen auf TCP-Ebene, **bevor bekannt ist**, um welche Domain es sich handelt. * **Standardmäßig** bedeutet das, dass Sie nur **ein HTTPS-Zertifikat pro IP-Adresse** haben können. * Ganz gleich, wie groß Ihr Server ist oder wie klein die einzelnen Anwendungen darauf sind. * Hierfür gibt es jedoch eine **Lösung**. @@ -194,7 +194,7 @@ Dieser ganze Erneuerungsprozess, während die Anwendung weiterhin bereitgestellt Wenn Sie einen Proxy zur Verarbeitung von HTTPS verwenden, weiß Ihr **Anwendungsserver** (z. B. Uvicorn über das FastAPI CLI) nichts über den HTTPS-Prozess, er kommuniziert per einfachem HTTP mit dem **TLS-Terminierungsproxy**. -Dieser **Proxy** würde normalerweise unmittelbar vor dem Übermitteln der Anfrage an den **Anwendungsserver** einige HTTP-Header dynamisch setzen, um dem Anwendungsserver mitzuteilen, dass der Request vom Proxy **weitergeleitet** wird. +Dieser **Proxy** würde normalerweise unmittelbar vor dem Übermitteln des Requests an den **Anwendungsserver** einige HTTP-Header dynamisch setzen, um dem Anwendungsserver mitzuteilen, dass der Request vom Proxy **weitergeleitet** wird. /// note | Technische Details diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md index 53fe230e5..fa8a9c963 100644 --- a/docs/de/docs/deployment/manually.md +++ b/docs/de/docs/deployment/manually.md @@ -55,8 +55,7 @@ Es gibt mehrere Alternativen, einschließlich: * [Uvicorn](https://www.uvicorn.dev/): ein hochperformanter ASGI-Server. * [Hypercorn](https://hypercorn.readthedocs.io/): ein ASGI-Server, der unter anderem kompatibel mit HTTP/2 und Trio ist. * [Daphne](https://github.com/django/daphne): der für Django Channels entwickelte ASGI-Server. -* [Granian](https://github.com/emmett-framework/granian): Ein Rust HTTP-Server für Python-Anwendungen. -* [NGINX Unit](https://unit.nginx.org/howto/fastapi/): NGINX Unit ist eine leichte und vielseitige Laufzeitumgebung für Webanwendungen. +* [Granian](https://github.com/emmett-framework/granian): Ein Rust-HTTP-Server für Python-Anwendungen. ## Servermaschine und Serverprogramm { #server-machine-and-server-program } @@ -66,11 +65,11 @@ Das Wort „**Server**“ wird häufig verwendet, um sowohl den entfernten/Cloud Denken Sie einfach daran, dass sich „Server“ im Allgemeinen auf eines dieser beiden Dinge beziehen kann. -Wenn man sich auf die entfernte Maschine bezieht, wird sie üblicherweise als **Server**, aber auch als **Maschine**, **VM** (virtuelle Maschine) oder **Knoten** bezeichnet. Diese Begriffe beziehen sich auf irgendeine Art von entfernten Rechner, normalerweise unter Linux, auf dem Sie Programme ausführen. +Wenn man sich auf die entfernte Maschine bezieht, wird sie üblicherweise als **Server**, aber auch als **Maschine**, **VM** (virtuelle Maschine) oder **Knoten** bezeichnet. Diese Begriffe beziehen sich auf irgendeine Art von entferntem Rechner, normalerweise unter Linux, auf dem Sie Programme ausführen. ## Das Serverprogramm installieren { #install-the-server-program } -Wenn Sie FastAPI installieren, wird es mit einem Produktionsserver, Uvicorn, geliefert, und Sie können ihn mit dem `fastapi run` Befehl starten. +Wenn Sie FastAPI installieren, wird es mit einem Produktionsserver, Uvicorn, geliefert, und Sie können ihn mit dem `fastapi run`-Befehl starten. Aber Sie können auch ein ASGI-Serverprogramm manuell installieren. diff --git a/docs/de/docs/deployment/server-workers.md b/docs/de/docs/deployment/server-workers.md index 27ae53f7d..6b0cc834e 100644 --- a/docs/de/docs/deployment/server-workers.md +++ b/docs/de/docs/deployment/server-workers.md @@ -17,7 +17,7 @@ Wie Sie im vorherigen Kapitel über [Deployment-Konzepte](concepts.md) gesehen h Hier zeige ich Ihnen, wie Sie **Uvicorn** mit **Workerprozessen** verwenden, indem Sie den `fastapi`-Befehl oder den `uvicorn`-Befehl direkt verwenden. -/// info | Info +/// note | Hinweis 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). diff --git a/docs/de/docs/editor-support.md b/docs/de/docs/editor-support.md index 97782f54f..f93dd5346 100644 --- a/docs/de/docs/editor-support.md +++ b/docs/de/docs/editor-support.md @@ -1,6 +1,6 @@ # Editor-Unterstützung { #editor-support } -Die offizielle [FastAPI-Erweiterung](https://marketplace.visualstudio.com/items?itemName=FastAPILabs.fastapi-vscode) verbessert Ihren FastAPI-Entwicklungsworkflow mit Pfadoperation-Erkennung und -Navigation sowie FastAPI-Cloud-Deployment und Live-Logstreaming. +Die offizielle [FastAPI-Erweiterung](https://marketplace.visualstudio.com/items?itemName=FastAPILabs.fastapi-vscode) verbessert Ihren FastAPI-Entwicklungsworkflow mit *Pfadoperation*-Erkennung und -Navigation sowie FastAPI-Cloud-Deployment und Live-Logstreaming. Weitere Details zur Erweiterung finden Sie im README im [GitHub-Repository](https://github.com/fastapi/fastapi-vscode). @@ -14,10 +14,10 @@ Standardmäßig erkennt die Erweiterung FastAPI-Anwendungen in Ihrem Workspace a ## Funktionen { #features } -- Pfadoperation-Explorer – Eine Baumansicht in der Seitenleiste aller *Pfadoperationen* in Ihrer Anwendung. Klicken Sie, um zu einer beliebigen Route- oder Router-Definition zu springen. -- Routensuche – Suchen Sie nach Pfad, Methode oder Namen mit Ctrl + Shift + E (unter macOS: Cmd + Shift + E). -- CodeLens-Navigation – Anklickbare Links oberhalb von Testclient-Aufrufen (z. B. `client.get('/items')`), die zur passenden Pfadoperation springen und so eine schnelle Navigation zwischen Tests und Implementierung ermöglichen. -- Zu FastAPI Cloud deployen – Deployment Ihrer App mit einem Klick auf [FastAPI Cloud](https://fastapicloud.com/). -- Anwendungslogs streamen – Echtzeit-Logstreaming Ihrer auf FastAPI Cloud deployten Anwendung mit Loglevel-Filterung und Textsuche. +- **Pfadoperation-Explorer** – Eine Baumansicht in der Seitenleiste aller *Pfadoperationen* in Ihrer Anwendung. Klicken Sie, um zu einer beliebigen Route- oder Router-Definition zu springen. +- **Routensuche** – Suchen Sie nach Pfad, Methode oder Namen mit Ctrl + Shift + E (unter macOS: Cmd + Shift + E). +- **CodeLens-Navigation** – Anklickbare Links oberhalb von Testclient-Aufrufen (z. B. `client.get('/items')`), die zur passenden *Pfadoperation* springen und so eine schnelle Navigation zwischen Tests und Implementierung ermöglichen. +- **Zu FastAPI Cloud deployen** – Deployment Ihrer App mit einem Klick auf [FastAPI Cloud](https://fastapicloud.com/). +- **Anwendungslogs streamen** – Echtzeit-Logstreaming Ihrer auf FastAPI Cloud deployten Anwendung mit Loglevel-Filterung und Textsuche. -Wenn Sie sich mit den Funktionen der Erweiterung vertraut machen möchten, können Sie den Erweiterungs‑Walkthrough aufrufen, indem Sie die Befehlspalette öffnen (Ctrl + Shift + P oder unter macOS: Cmd + Shift + P) und „Welcome: Open walkthrough …“ auswählen und anschließend den Walkthrough „Get started with FastAPI“ wählen. +Wenn Sie sich mit den Funktionen der Erweiterung vertraut machen möchten, können Sie den Erweiterungs‑Walkthrough aufrufen, indem Sie die Befehlspalette öffnen (Ctrl + Shift + P oder unter macOS: Cmd + Shift + P) und „Welcome: Open walkthrough ...“ auswählen und anschließend den Walkthrough „Get started with FastAPI“ wählen. diff --git a/docs/de/docs/environment-variables.md b/docs/de/docs/environment-variables.md index 7bff442cd..1678ead27 100644 --- a/docs/de/docs/environment-variables.md +++ b/docs/de/docs/environment-variables.md @@ -12,7 +12,7 @@ Umgebungsvariablen können nützlich sein, um **Einstellungen** der Anwendung zu ## Umgebungsvariablen erstellen und verwenden { #create-and-use-env-vars } -Sie können Umgebungsvariablen in der **Shell (Terminal)** erstellen und verwenden, ohne Python zu benötigen: +Sie können Umgebungsvariablen in der **Shell (Terminal)** **erstellen** und verwenden, ohne Python zu benötigen: //// tab | Linux, macOS, Windows Bash @@ -67,7 +67,7 @@ print(f"Hello {name} from Python") Das zweite Argument von [`os.getenv()`](https://docs.python.org/3.8/library/os.html#os.getenv) ist der Defaultwert, der zurückgegeben wird. -Wenn er nicht angegeben wird, ist er standardmäßig `None`. Hier geben wir „World“ als den zu verwendenden Defaultwert an. +Wenn er nicht angegeben wird, ist er standardmäßig `None`. Hier geben wir `"World"` als den zu verwendenden Defaultwert an. /// @@ -255,7 +255,7 @@ $ python //// tab | Linux, macOS -Das System wird das `python` Programm in `/opt/custompython/bin` **finden** und es ausführen. +Das System wird das `python`-Programm in `/opt/custompython/bin` **finden** und es ausführen. Es wäre ungefähr gleichbedeutend mit der Eingabe von: @@ -271,7 +271,7 @@ $ /opt/custompython/bin/python //// tab | Windows -Das System wird das `python` Programm in `C:\opt\custompython\bin\python` **finden** und es ausführen. +Das System wird das `python`-Programm in `C:\opt\custompython\bin\python` **finden** und es ausführen. Es wäre ungefähr gleichbedeutend mit der Eingabe von: diff --git a/docs/de/docs/fastapi-cli.md b/docs/de/docs/fastapi-cli.md index b34fc4b73..4202501bc 100644 --- a/docs/de/docs/fastapi-cli.md +++ b/docs/de/docs/fastapi-cli.md @@ -95,7 +95,7 @@ was gleichbedeutend wäre mit: from backend.main import app ``` -### `fastapi dev` mit Pfad { #fastapi-dev-with-path } +### `fastapi dev` mit Pfad oder mit der CLI-Option `--entrypoint` { #fastapi-dev-with-path-or-with-entrypoint-cli-option } Sie können auch den Dateipfad an den Befehl `fastapi dev` übergeben, dann wird das zu verwendende FastAPI-App-Objekt erraten: @@ -103,7 +103,13 @@ Sie können auch den Dateipfad an den Befehl `fastapi dev` übergeben, dann wird $ fastapi dev main.py ``` -Aber Sie müssten sich merken, bei jedem Aufruf des `fastapi`-Befehls den korrekten Pfad zu übergeben. +Oder Sie können auch die Option `--entrypoint` an den Befehl `fastapi dev` übergeben: + +```console +$ fastapi dev --entrypoint main:app +``` + +Aber Sie müssten sich merken, bei jedem Aufruf des `fastapi`-Befehls den korrekten Pfad\entrypoint zu übergeben. Zusätzlich könnten andere Tools sie nicht finden, z. B. die [VS Code Extension](editor-support.md) oder [FastAPI Cloud](https://fastapicloud.com), daher wird empfohlen, den `entrypoint` in `pyproject.toml` zu verwenden. diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index f9a34c40f..f24ec2426 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -1,10 +1,10 @@ # Merkmale { #features } -## FastAPI Merkmale { #fastapi-features } +## FastAPI-Merkmale { #fastapi-features } **FastAPI** ermöglicht Ihnen Folgendes: -### Basiert auf offenen Standards { #based-on-open-standards } +### Auf offenen Standards basieren { #based-on-open-standards } * [**OpenAPI**](https://github.com/OAI/OpenAPI-Specification) für die Erstellung von APIs, inklusive Deklarationen von Pfad-Operationen, Parametern, Requestbodys, Sicherheit, usw. * Automatische Dokumentation der Datenmodelle mit [**JSON Schema**](https://json-schema.org/) (da OpenAPI selbst auf JSON Schema basiert). @@ -15,7 +15,7 @@ Interaktive API-Dokumentation und erkundbare Web-Benutzeroberflächen. Da das Framework auf OpenAPI basiert, gibt es mehrere Optionen, zwei sind standardmäßig vorhanden. -* [**Swagger UI**](https://github.com/swagger-api/swagger-ui), bietet interaktive Erkundung, testen und rufen Sie Ihre API direkt im Webbrowser auf. +* [**Swagger UI**](https://github.com/swagger-api/swagger-ui), mit interaktiver Erkundung, rufen Sie Ihre API direkt vom Browser aus auf und testen Sie sie. ![Swagger UI Interaktion](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) @@ -36,7 +36,7 @@ from datetime import date from pydantic import BaseModel -# Deklarieren Sie eine Variable als ein str +# Deklarieren Sie eine Variable vom Typ str # und bekommen Sie Editor-Unterstützung innerhalb der Funktion def main(user_id: str): return user_id @@ -63,15 +63,15 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info | Info +/// note | Hinweis `**second_user_data` bedeutet: -Nimm die Schlüssel-Wert-Paare des `second_user_data` Dicts und übergebe sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")` +Übergeben Sie die Schlüssel und Werte des `second_user_data` Dicts direkt als Schlüssel-Wert-Argumente, äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")` /// -### Editor Unterstützung { #editor-support } +### Editorunterstützung { #editor-support } Das ganze Framework wurde so entworfen, dass es einfach und intuitiv zu benutzen ist; alle Entscheidungen wurden auf mehreren Editoren getestet, sogar vor der Implementierung, um die bestmögliche Entwicklererfahrung zu gewährleisten. @@ -85,31 +85,31 @@ So kann Ihr Editor Sie unterstützen: * in [Visual Studio Code](https://code.visualstudio.com/): -![Editor Unterstützung](https://fastapi.tiangolo.com/img/vscode-completion.png) +![Editorunterstützung](https://fastapi.tiangolo.com/img/vscode-completion.png) * in [PyCharm](https://www.jetbrains.com/pycharm/): -![Editor Unterstützung](https://fastapi.tiangolo.com/img/pycharm-completion.png) +![Editorunterstützung](https://fastapi.tiangolo.com/img/pycharm-completion.png) -Sie bekommen sogar Autovervollständigung an Stellen, an denen Sie dies vorher nicht für möglich gehalten hätten. Zum Beispiel der `price` Schlüssel in einem JSON Datensatz (dieser könnte auch verschachtelt sein), der aus einem Request kommt. +Sie bekommen sogar Autovervollständigung an Stellen, an denen Sie dies vorher nicht für möglich gehalten hätten. Zum Beispiel der `price`-Schlüssel innerhalb eines JSON-Bodys (dieser könnte auch verschachtelt sein), der aus einem Request kommt. Nie wieder falsche Schlüsselnamen tippen, Hin und Herhüpfen zwischen der Dokumentation, Hoch- und Runterscrollen, um herauszufinden, ob es `username` oder `user_name` war. ### Kompakt { #short } -Es gibt für alles sensible **Defaultwerte**, mit optionaler Konfiguration überall. Alle Parameter können feinjustiert werden, damit sie tun, was Sie benötigen, und die API definieren, die Sie brauchen. +Es gibt für alles sinnvolle **Defaultwerte**, mit optionaler Konfiguration überall. Alle Parameter können feinjustiert werden, damit sie tun, was Sie benötigen, und die API definieren, die Sie brauchen. Aber standardmäßig **„funktioniert einfach alles“**. ### Validierung { #validation } * Validierung für die meisten (oder alle?) Python-**Datentypen**, hierzu gehören: - * JSON Objekte (`dict`). - * JSON Listen (`list`), die den Typ ihrer Elemente definieren. - * Strings (`str`) mit definierter minimaler und maximaler Länge. + * JSON-Objekte (`dict`). + * JSON-Array (`list`), das Elementtypen definiert. + * String-Felder (`str`) mit definierter minimaler und maximaler Länge. * Zahlen (`int`, `float`) mit Mindest- und Maximalwerten, usw. -* Validierung für mehr exotische Typen, wie: +* Validierung für exotischere Typen, wie: * URL. * E-Mail. * UUID. @@ -124,42 +124,42 @@ Sicherheit und Authentifizierung sind integriert. Ohne Kompromisse bei Datenbank Alle in OpenAPI definierten Sicherheitsschemas, inklusive: * HTTP Basic. -* **OAuth2** (auch mit **JWT Tokens**). Siehe dazu das Tutorial zu [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md). -* API Schlüssel in: +* **OAuth2** (auch mit **JWT-Tokens**). Siehe dazu das Tutorial zu [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md). +* API-Schlüssel in: * Headern. * Query-Parametern. * Cookies, usw. -Zusätzlich alle Sicherheitsfunktionen von Starlette (inklusive **Session Cookies**). +Zusätzlich alle Sicherheitsfunktionen von Starlette (inklusive **Session-Cookies**). -Alles als wiederverwendbare Tools und Komponenten gebaut, die einfach in Ihre Systeme, Datenspeicher, relationale und nicht-relationale Datenbanken, usw., integriert werden können. +Alles als wiederverwendbare Tools und Komponenten gebaut, die einfach in Ihre Systeme, Datenspeicher, relationale und NoSQL-Datenbanken, usw., integriert werden können. ### Dependency Injection { #dependency-injection } -FastAPI enthält ein extrem einfach zu verwendendes, aber extrem mächtiges Dependency Injection System. +FastAPI enthält ein extrem einfach zu verwendendes, aber extrem mächtiges Dependency Injection-System. * Selbst Abhängigkeiten können Abhängigkeiten haben, woraus eine Hierarchie oder ein **„Graph“ von Abhängigkeiten** entsteht. * Alles **automatisch gehandhabt** durch das Framework. -* Alle Abhängigkeiten können Daten von Requests anfordern und das Verhalten von **Pfadoperationen** und der automatisierten Dokumentation **modifizieren**. +* Alle Abhängigkeiten können Daten von Requests anfordern und die Einschränkungen der **Pfadoperationen** sowie die automatische Dokumentation **erweitern**. * **Automatische Validierung** selbst für solche Parameter von *Pfadoperationen*, welche in Abhängigkeiten definiert sind. -* Unterstützung für komplexe Authentifizierungssysteme, **Datenbankverbindungen**, usw. +* Unterstützung für komplexe Benutzerauthentifizierungssysteme, **Datenbankverbindungen**, usw. * **Keine Kompromisse** bei Datenbanken, Frontends, usw., sondern einfache Integration mit allen. -### Unbegrenzte Erweiterungen { #unlimited-plug-ins } +### Unbegrenzte „Plug-ins“ { #unlimited-plug-ins } Oder mit anderen Worten, sie werden nicht benötigt. Importieren und nutzen Sie den Code, den Sie brauchen. -Jede Integration wurde so entworfen, dass sie so einfach zu nutzen ist (mit Abhängigkeiten), dass Sie eine Erweiterung für Ihre Anwendung mit nur zwei Zeilen Code erstellen können. Hierbei nutzen Sie die gleiche Struktur und Syntax, wie bei *Pfadoperationen*. +Jede Integration wurde so entworfen, dass sie so einfach zu nutzen ist (mit Abhängigkeiten), dass Sie ein „Plug-in“ für Ihre Anwendung mit nur 2 Zeilen Code erstellen können. Hierbei nutzen Sie die gleiche Struktur und Syntax, wie bei *Pfadoperationen*. ### Getestet { #tested } * 100 % Testabdeckung. -* 100 % Typen annotiert. +* Zu 100 % typannotierte Codebasis. * Verwendet in Produktionsanwendungen. -## Starlette Merkmale { #starlette-features } +## Starlette-Merkmale { #starlette-features } -**FastAPI** ist vollkommen kompatibel (und basiert auf) [**Starlette**](https://www.starlette.dev/). Das bedeutet, wenn Sie eigenen Starlette Quellcode haben, funktioniert der. +**FastAPI** ist vollkommen kompatibel (und basiert auf) [**Starlette**](https://www.starlette.dev/). Das bedeutet, wenn Sie eigenen Starlette-Quellcode haben, funktioniert dieser auch. `FastAPI` ist tatsächlich eine Unterklasse von `Starlette`. Wenn Sie also bereits Starlette kennen oder benutzen, das meiste funktioniert genau so. @@ -173,11 +173,11 @@ Mit **FastAPI** bekommen Sie alles von **Starlette** (da FastAPI nur Starlette a * **CORS**, GZip, statische Dateien, Responses streamen. * **Sitzungs- und Cookie**-Unterstützung. * 100 % Testabdeckung. -* 100 % Typen annotierte Codebasis. +* Zu 100 % typannotierte Codebasis. -## Pydantic Merkmale { #pydantic-features } +## Pydantic-Merkmale { #pydantic-features } -**FastAPI** ist vollkommen kompatibel (und basiert auf) [**Pydantic**](https://docs.pydantic.dev/). Das bedeutet, wenn Sie eigenen Pydantic Quellcode haben, funktioniert der. +**FastAPI** ist vollkommen kompatibel (und basiert auf) [**Pydantic**](https://docs.pydantic.dev/). Das bedeutet, wenn Sie eigenen Pydantic-Quellcode haben, funktioniert dieser auch. Inklusive externer Bibliotheken, die auf Pydantic basieren, wie ORMs, ODMs für Datenbanken. @@ -188,14 +188,14 @@ Das gleiche gilt auch für die andere Richtung: Sie können in vielen Fällen da Mit **FastAPI** bekommen Sie alle Funktionen von **Pydantic** (da FastAPI für die gesamte Datenverarbeitung Pydantic nutzt): * **Kein Kopfzerbrechen**: - * Keine neue Schemadefinition-Mikrosprache zu lernen. + * Keine neue Schemadefinitions-Mikrosprache zu lernen. * Wenn Sie Pythons Typen kennen, wissen Sie, wie man Pydantic verwendet. * Gutes Zusammenspiel mit Ihrer/Ihrem **IDE/Linter/Gehirn**: * Weil Pydantics Datenstrukturen einfach nur Instanzen ihrer definierten Klassen sind; Autovervollständigung, Linting, mypy und Ihre Intuition sollten alle einwandfrei mit Ihren validierten Daten funktionieren. * Validierung von **komplexen Strukturen**: - * Benutzung von hierarchischen Pydantic-Modellen, Python-`typing`s `List` und `Dict`, etc. - * Die Validierer erlauben es, komplexe Datenschemen klar und einfach zu definieren, überprüft und dokumentiert als JSON Schema. - * Sie können tief **verschachtelte JSON** Objekte haben, die alle validiert und annotiert sind. + * Benutzung von hierarchischen Pydantic-Modellen, Python-`typing`s `List` und `Dict`, usw. + * Die Validierer erlauben es, komplexe Datenschemas klar und einfach zu definieren, überprüft und dokumentiert als JSON Schema. + * Sie können tief **verschachtelte JSON**-Objekte haben, die alle validiert und annotiert sind. * **Erweiterbar**: - * Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator`-dekorierten Methode im Modell erweitern. + * Pydantic erlaubt die Definition von eigenen Datentypen oder Sie können die Validierung mit Methoden in einem Modell erweitern, die mit dem Validator-Dekorator dekoriert sind. * 100 % Testabdeckung. diff --git a/docs/de/docs/help-fastapi.md b/docs/de/docs/help-fastapi.md index 59dd22074..4a8687562 100644 --- a/docs/de/docs/help-fastapi.md +++ b/docs/de/docs/help-fastapi.md @@ -1,18 +1,13 @@ -# FastAPI helfen – Hilfe erhalten { #help-fastapi-get-help } +# Helfen { #help } -Mögen Sie **FastAPI**? -Möchten Sie FastAPI, anderen Benutzern und dem Autor helfen? +Möchten Sie FastAPI helfen oder Hilfe zu FastAPI erhalten? -Oder möchten Sie Hilfe zu **FastAPI** erhalten? - -Es gibt sehr einfache Möglichkeiten zu helfen (einige erfordern nur ein oder zwei Klicks). - -Und es gibt auch mehrere Möglichkeiten, Hilfe zu bekommen. +Es gibt sehr einfache Möglichkeiten, zu helfen und Hilfe zu bekommen. ## Newsletter abonnieren { #subscribe-to-the-newsletter } -Sie können den (unregelmäßigen) [**FastAPI and friends**-Newsletter](newsletter.md) abonnieren, um über folgende Themen informiert zu bleiben: +Sie können den (unregelmäßigen) [**FastAPI and friends**-Newsletter](newsletter.md) abonnieren, um über Folgendes informiert zu bleiben: * Neuigkeiten über FastAPI und Freunde 🚀 * Anleitungen 📝 @@ -20,9 +15,13 @@ Sie können den (unregelmäßigen) [**FastAPI and friends**-Newsletter](newslett * Breaking Changes 🚨 * Tipps und Tricks ✅ -## FastAPI auf X (Twitter) folgen { #follow-fastapi-on-x-twitter } +## FastAPI online folgen { #follow-fastapi-online } + +Sie können **FastAPI** an mehreren Orten online folgen: -[Folgen Sie @fastapi auf **X (Twitter)**](https://x.com/fastapi), um die neuesten Nachrichten über **FastAPI** zu erhalten. 🐦 +* [@fastapi auf **X / Twitter**](https://x.com/fastapi) +* [@fastapi.tiangolo.com auf **Bluesky**](https://bsky.app/profile/fastapi.tiangolo.com) +* [FastAPI auf **LinkedIn**](https://www.linkedin.com/company/fastapi/) ## **FastAPI** auf GitHub einen Stern geben { #star-fastapi-in-github } @@ -30,200 +29,43 @@ Sie können FastAPI auf GitHub „starren“ (klicken Sie auf den Stern-Button o 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 überwachen { #watch-the-github-repository-for-releases } +## Das GitHub-Repository auf Releases beobachten { #watch-the-github-repository-for-releases } -Sie können FastAPI auf GitHub „beobachten“ (klicken Sie auf den „watch“-Button oben rechts): [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi). 👀 +Sie können FastAPI auf GitHub „beobachten“ (klicken Sie auf den „Watch“-Button oben rechts): [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi). 👀 Dort können Sie „Releases only“ auswählen. -Auf diese Weise erhalten Sie Benachrichtigungen (per E-Mail), wenn es ein neues Release (eine neue Version) von **FastAPI** mit Bugfixes und neuen Funktionen gibt. - -## Mit dem Autor vernetzen { #connect-with-the-author } - -Sie können sich mit [mir (Sebastián Ramírez / `tiangolo`)](https://tiangolo.com), dem Autor, vernetzen. +Auf diese Weise erhalten Sie Benachrichtigungen (per E‑Mail), wenn es ein neues Release (eine neue Version) von **FastAPI** mit Bugfixes und neuen Funktionen gibt. -Sie können: +## Dem Autor folgen { #follow-the-author } -* [Mir auf **GitHub** folgen](https://github.com/tiangolo). - * Andere Open-Source-Projekte sehen, die ich erstellt habe und die Ihnen helfen könnten. - * Mir folgen, um zu sehen, wenn ich ein neues Open-Source-Projekt erstelle. -* [Mir auf **X (Twitter)** folgen](https://x.com/tiangolo) oder [Mastodon](https://fosstodon.org/@tiangolo). - * Mir mitteilen, wie Sie FastAPI verwenden (ich höre das gerne). - * Mitbekommen, wenn ich Ankündigungen mache oder neue Tools veröffentliche. - * Sie können auch [@fastapi auf X (Twitter) folgen](https://x.com/fastapi) (ein separates Konto). -* [Mir auf **LinkedIn** folgen](https://www.linkedin.com/in/tiangolo/). - * Mitbekommen, wenn ich Ankündigungen mache oder neue Tools veröffentliche (obwohl ich X (Twitter) häufiger verwende 🤷‍♂). -* Lesen, was ich schreibe (oder mir folgen) auf [**Dev.to**](https://dev.to/tiangolo) oder [**Medium**](https://medium.com/@tiangolo). - * Andere Ideen, Artikel lesen und mehr über die von mir erstellten Tools erfahren. - * Mir folgen, um zu lesen, wenn ich etwas Neues veröffentliche. +Sie können [mir (Sebastián Ramírez / `tiangolo`)](https://tiangolo.com), dem Autor, an einigen Orten folgen, um mitzubekommen, wenn ich Neuigkeiten zu FastAPI und Freunden habe: -## Über **FastAPI** tweeten { #tweet-about-fastapi } - -[Tweeten Sie über **FastAPI**](https://x.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/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. - -## Für FastAPI abstimmen { #vote-for-fastapi } - -* [Stimmen Sie für **FastAPI** auf Slant](https://www.slant.co/options/34241/~fastapi-review). -* [Stimmen Sie für **FastAPI** auf AlternativeTo](https://alternativeto.net/software/fastapi/about/). -* [Sagen Sie auf StackShare, dass Sie **FastAPI** verwenden](https://stackshare.io/pypi-fastapi). +* [@tiangolo auf **GitHub**](https://github.com/tiangolo). +* [@tiangolo auf **X (Twitter)**](https://x.com/tiangolo) +* [@tiangolo.com auf **Bluesky**](https://bsky.app/profile/tiangolo.com) +* [@tiangolo auf **LinkedIn**](https://www.linkedin.com/in/tiangolo/). ## Anderen bei Fragen auf GitHub helfen { #help-others-with-questions-in-github } -Sie können versuchen, anderen bei ihren Fragen zu helfen: - -* [GitHub-Diskussionen](https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered) -* [GitHub-Issues](https://github.com/fastapi/fastapi/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+) +Sie können versuchen, anderen bei ihren Fragen in [GitHub-Diskussionen](https://github.com/fastapi/fastapi/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered) zu helfen. In vielen Fällen kennen Sie möglicherweise bereits die Antwort auf diese Fragen. 🤓 Wenn Sie vielen Menschen bei ihren Fragen helfen, werden Sie offizieller [FastAPI-Experte](fastapi-people.md#fastapi-experts). 🎉 -Denken Sie daran, der wichtigste Punkt ist: Versuchen Sie, freundlich zu sein. Die Leute bringen ihre Frustrationen mit und fragen in vielen Fällen nicht auf die beste Art und Weise, aber versuchen Sie dennoch so gut wie möglich, freundlich zu sein. 🤗 - -Die **FastAPI**-Community soll freundlich und einladend sein. Akzeptieren Sie gleichzeitig kein Mobbing oder respektloses Verhalten gegenüber anderen. Wir müssen uns umeinander kümmern. - ---- - -So helfen Sie anderen bei Fragen (in Diskussionen oder Issues): - -### Die Frage verstehen { #understand-the-question } - -* Prüfen Sie, ob Sie verstehen können, was der **Zweck** und der Anwendungsfall der fragenden Person ist. - -* Überprüfen Sie dann, ob die Frage (die überwiegende Mehrheit sind Fragen) **klar** ist. - -* In vielen Fällen handelt es sich bei der gestellten Frage um eine Lösung, die der Benutzer sich vorstellt, aber es könnte eine **bessere** Lösung geben. Wenn Sie das Problem und den Anwendungsfall besser verstehen, können Sie eine bessere **Alternativlösung** vorschlagen. - -* Wenn Sie die Frage nicht verstehen können, fragen Sie nach weiteren **Details**. - -### Das Problem reproduzieren { #reproduce-the-problem } +Denken Sie daran, der wichtigste Punkt ist: Versuchen Sie, freundlich zu sein. 🤗 -In den meisten Fällen und bei den meisten Fragen gibt es etwas in Bezug auf den **originalen Code** der Person. +### So helfen { #how-to-help } -In vielen Fällen wird nur ein Fragment des Codes gepostet, aber das reicht nicht aus, um **das Problem zu reproduzieren**. - -* Sie können die Person bitten, ein [minimales, reproduzierbares Beispiel](https://stackoverflow.com/help/minimal-reproducible-example) bereitzustellen, welches Sie **kopieren, einfügen** und lokal ausführen können, um den gleichen Fehler oder das gleiche Verhalten zu sehen, das die Person sieht, oder um ihren Anwendungsfall besser zu verstehen. - -* Wenn Sie in Geberlaune sind, können Sie ein solches Beispiel selbst erstellen, nur basierend auf der Beschreibung des Problems. Denken Sie jedoch daran, dass dies viel Zeit in Anspruch nehmen kann und dass es besser sein kann, zunächst um eine Klärung des Problems zu bitten. - -### Lösungen vorschlagen { #suggest-solutions } - -* Nachdem Sie die Frage verstanden haben, können Sie eine mögliche **Antwort** geben. - -* In vielen Fällen ist es besser, das **zugrunde liegende Problem oder den Anwendungsfall** zu verstehen, da es möglicherweise einen besseren Weg zur Lösung gibt als das, was die Person versucht. - -### Um Schließung bitten { #ask-to-close } - -Wenn die Person antwortet, besteht eine hohe Chance, dass Sie ihr Problem gelöst haben. Herzlichen Glückwunsch, **Sie sind ein Held**! 🦸 - -* Wenn es tatsächlich das Problem gelöst hat, können Sie sie darum bitten: - - * In GitHub-Diskussionen: den Kommentar als **Antwort** zu markieren. - * In GitHub-Issues: Das Issue zu **schließen**. - -## Das GitHub-Repository beobachten { #watch-the-github-repository } - -Sie können FastAPI auf GitHub „beobachten“ (klicken Sie auf den „watch“-Button oben rechts): [https://github.com/fastapi/fastapi](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. - -Dann können Sie versuchen, bei der Lösung solcher Fragen zu helfen. +Folgen Sie der [Anleitung, wie Sie helfen können](https://tiangolo.com/open-source/help/#help-others-with-questions-in-github) hier. ## Fragen stellen { #ask-questions } -Sie können im GitHub-Repository [eine neue Frage erstellen](https://github.com/fastapi/fastapi/discussions/new?category=questions), zum Beispiel: - -* Stellen Sie eine **Frage** oder bitten Sie um Hilfe mit einem **Problem**. -* Schlagen Sie eine neue **Funktionalität** vor. - -**Hinweis**: Wenn Sie das tun, bitte ich Sie, auch anderen zu helfen. 😉 - -## Pull Requests prüfen { #review-pull-requests } - -Sie können mir helfen, Pull Requests von anderen zu überprüfen. - -Noch einmal, bitte versuchen Sie Ihr Bestes, freundlich zu sein. 🤗 - ---- +Sie können im GitHub-Repository [eine neue Frage erstellen](https://github.com/fastapi/fastapi/discussions/new?category=questions), zum Beispiel um: -Hier ist, was Sie beachten sollten und wie Sie einen Pull Request überprüfen: - -### Das Problem verstehen { #understand-the-problem } - -* Stellen Sie zunächst sicher, dass Sie **das Problem verstehen**, welches der Pull Request zu lösen versucht. Möglicherweise gibt es eine längere Diskussion dazu in einer GitHub-Diskussion oder einem GitHub-Issue. - -* Es besteht auch eine gute Chance, dass der Pull Request nicht wirklich benötigt wird, da das Problem auf **andere Weise** gelöst werden kann. Dann können Sie das vorschlagen oder danach fragen. - -### Keine Panik wegen des Stils { #dont-worry-about-style } - -* Machen Sie sich keine Sorgen über Dinge wie den Stil von Commit-Nachrichten. Ich werde den Commit zusammenführen und manuell anpassen. - -* Außerdem, keine Sorgen über Stilregeln, es gibt bereits automatisierte Tools, die das überprüfen. - -Und wenn es irgendeinen anderen Stil- oder Konsistenzbedarf gibt, werde ich direkt danach fragen oder zusätzliche Commits mit den erforderlichen Änderungen hinzufügen. - -### Den Code testen { #check-the-code } - -* Prüfen und lesen Sie den Code, fragen Sie sich, ob er Sinn macht, **führen Sie ihn lokal aus** und testen Sie, ob er das Problem tatsächlich löst. - -* Schreiben Sie dann einen **Kommentar** und berichten, dass Sie das getan haben. So weiß ich, dass Sie ihn wirklich überprüft haben. - -/// info | Info - -Leider kann ich PRs, nur weil sie von mehreren gutgeheißen wurden, nicht einfach vertrauen. - -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 wirklich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓 - -/// - -* Wenn der PR in irgendeiner Weise vereinfacht werden kann, können Sie danach fragen, aber es gibt keinen Grund, zu wählerisch zu sein. Es gibt viele subjektive Standpunkte (und ich habe auch meinen eigenen 🙈), also ist es besser, wenn man sich auf die grundlegenden Dinge konzentriert. - -### Tests { #tests } - -* Helfen Sie mir zu überprüfen, dass der PR **Tests** hat. - -* Überprüfen Sie, dass diese Tests vor dem PR **fehlschlagen**. 🚨 - -* Überprüfen Sie dann, dass diese Tests nach dem PR **bestanden** werden. ✅ - -* Viele PRs haben keine Tests. Sie können den Autor daran **erinnern**, Tests hinzuzufügen, oder Sie können sogar selbst einige Tests **vorschlagen**. Das ist eines der Dinge, die am meisten Zeit in Anspruch nehmen, und Sie können dabei viel helfen. - -* Kommentieren Sie auch hier anschließend, was Sie versucht haben, sodass ich weiß, dass Sie es überprüft haben. 🤓 - -## Einen Pull Request erstellen { #create-a-pull-request } - -Sie können [zum Quellcode mit Pull Requests beitragen](contributing.md), 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](https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml). - * 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#translations). - * Sie können auch dabei helfen, die von anderen erstellten Übersetzungen zu überprüfen. -* Um neue Dokumentationsabschnitte vorzuschlagen. -* Um ein bestehendes Problem/Bug zu beheben. - * Stellen Sie sicher, dass Sie Tests hinzufügen. -* Um eine neue Funktionalität hinzuzufügen. - * Stellen Sie sicher, dass Sie Tests hinzufügen. - * Stellen Sie sicher, dass Sie Dokumentation hinzufügen, falls das notwendig ist. - -## FastAPI pflegen { #help-maintain-fastapi } - -Helfen Sie mir, **FastAPI** zu pflegen! 🤓 - -Es gibt viel zu tun, und das meiste davon können **SIE** tun. - -Die Hauptaufgaben, die Sie jetzt erledigen können, sind: - -* [Anderen bei Fragen auf GitHub helfen](#help-others-with-questions-in-github) (siehe Abschnitt oben). -* [Pull Requests prüfen](#review-pull-requests) (siehe Abschnitt oben). - -Diese beiden Aufgaben sind die Dinge, die **am meisten Zeit verbrauchen**. Das ist die Hauptarbeit bei der Wartung von FastAPI. - -Wenn Sie mir dabei helfen können, **helfen Sie mir, FastAPI zu pflegen** und Sie stellen sicher, dass es weiterhin **schneller und besser voranschreitet**. 🚀 +* Eine **Frage** zu stellen oder nach einem **Problem** zu fragen. +* Eine neue **Funktionalität** vorzuschlagen. ## Am Chat teilnehmen { #join-the-chat } @@ -231,7 +73,7 @@ Treten Sie dem 👥 [Discord-Chatserver](https://discord.gg/VQjSZaeJmf) 👥 bei /// tip | Tipp -Bei Fragen stellen Sie sie in [GitHub-Diskussionen](https://github.com/fastapi/fastapi/discussions/new?category=questions), dort besteht eine viel größere Chance, dass Sie Hilfe von den [FastAPI-Experten](fastapi-people.md#fastapi-experts) erhalten. +Bei Fragen stellen Sie sie in GitHub-Diskussionen, dort besteht eine viel größere Chance, dass Sie Hilfe erhalten. Nutzen Sie den Chat nur für andere allgemeine Gespräche. @@ -241,16 +83,6 @@ Nutzen Sie den Chat nur für andere allgemeine Gespräche. Bedenken Sie, dass Sie in Chats, die „freie Konversation“ erlauben, leicht Fragen stellen können, die zu allgemein und schwer zu beantworten sind, sodass Sie möglicherweise keine Antworten erhalten. -Auf GitHub hilft Ihnen die Vorlage dabei, die richtige Frage zu stellen, sodass Sie leichter eine gute Antwort erhalten können, oder sogar das Problem selbst lösen, bevor Sie überhaupt fragen. Und auf GitHub kann ich sicherstellen, dass ich immer alles beantworte, auch wenn es einige Zeit dauert. Persönlich kann ich das mit den Chat-Systemen nicht machen. 😅 - -Unterhaltungen in den Chat-Systemen sind auch nicht so leicht durchsuchbar wie auf GitHub, sodass Fragen und Antworten möglicherweise im Gespräch verloren gehen. Und nur die auf GitHub machen einen [FastAPI-Experten](fastapi-people.md#fastapi-experts), Sie werden also höchstwahrscheinlich mehr Aufmerksamkeit auf GitHub erhalten. - -Auf der anderen Seite gibt es Tausende von Benutzern in den Chat-Systemen, sodass die Wahrscheinlichkeit hoch ist, dass Sie dort fast immer jemanden zum Reden finden. 😄 - -## Den Autor sponsern { #sponsor-the-author } - -Wenn Ihr **Produkt/Firma** auf **FastAPI** angewiesen ist oder in Zusammenhang steht und Sie seine Benutzer erreichen möchten, können Sie den Autor (mich) über [GitHub-Sponsoren](https://github.com/sponsors/tiangolo) unterstützen. Je nach Stufe können Sie einige zusätzliche Vorteile erhalten, wie z. B. ein Abzeichen in der Dokumentation. 🎁 - ---- +Auf GitHub hilft Ihnen die Vorlage dabei, die richtige Frage zu stellen, sodass Sie leichter eine gute Antwort erhalten können, oder sogar das Problem selbst lösen, bevor Sie überhaupt fragen. -Danke! 🚀 +Unterhaltungen in den Chat-Systemen sind auch nicht so leicht durchsuchbar wie auf GitHub, sie gehen verloren. diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md index 2f8904be7..d25062615 100644 --- a/docs/de/docs/how-to/configure-swagger-ui.md +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -67,4 +67,4 @@ presets: [ Dabei handelt es sich um **JavaScript**-Objekte, nicht um Strings, daher können Sie diese nicht direkt vom Python-Code aus übergeben. -Wenn Sie solche JavaScript-Konfigurationen verwenden müssen, können Sie einen der früher genannten Wege verwenden. Überschreiben Sie alle *Pfadoperationen* der Swagger-Oberfläche und schreiben Sie manuell jedes benötigte JavaScript. +Wenn Sie solche Nur-JavaScript-Konfigurationen verwenden müssen, können Sie einen der früher genannten Wege verwenden. Überschreiben Sie die gesamte *Pfadoperation* der Swagger-Oberfläche und schreiben Sie manuell jedes benötigte JavaScript. 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 5e2dee95d..60fe71ed3 100644 --- a/docs/de/docs/how-to/custom-request-and-route.md +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -1,5 +1,6 @@ # Benutzerdefinierte Request- und APIRoute-Klasse { #custom-request-and-apiroute-class } + In einigen Fällen möchten Sie möglicherweise die von den Klassen `Request` und `APIRoute` verwendete Logik überschreiben. Das kann insbesondere eine gute Alternative zur Logik in einer Middleware sein. diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md index 8005344c8..23824117e 100644 --- a/docs/de/docs/how-to/extending-openapi.md +++ b/docs/de/docs/how-to/extending-openapi.md @@ -25,9 +25,17 @@ Diese Funktion `get_openapi()` erhält als Parameter: * `openapi_version`: Die Version der verwendeten OpenAPI-Spezifikation. Standardmäßig die neueste Version: `3.1.0`. * `summary`: Eine kurze Zusammenfassung der API. * `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`. +* `routes`: Die Routen der Anwendung, entnommen aus `app.routes`. FastAPI nutzt sie, um die registrierten *Pfadoperationen* zu sammeln, einschließlich derer aus eingebundenen Routern. -/// info | Info +/// tip | Technische Details + +`app.routes` ist eine Routenstruktur auf niedrigerer Ebene. Sie kann Routenkandidaten enthalten, die FastAPI intern für eingebundene Router verwendet, nicht nur endgültige `APIRoute`-Objekte. + +Sie können dennoch `app.routes` an `get_openapi()` übergeben. FastAPI durchläuft diesen Routenbaum, um die tatsächlich wirksamen Pfadoperationen zu sammeln. + +/// + +/// note | Hinweis 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. diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md index bf1490f70..cb1891b63 100644 --- a/docs/de/docs/how-to/graphql.md +++ b/docs/de/docs/how-to/graphql.md @@ -1,5 +1,6 @@ # GraphQL { #graphql } + Da **FastAPI** auf dem **ASGI**-Standard basiert, ist es sehr einfach, jede **GraphQL**-Bibliothek zu integrieren, die auch mit ASGI kompatibel ist. Sie können normale FastAPI-*Pfadoperationen* mit GraphQL in derselben Anwendung kombinieren. diff --git a/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md b/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md index c252b3e0f..5ea3b9561 100644 --- a/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md +++ b/docs/de/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md @@ -8,6 +8,8 @@ FastAPI Version 0.119.0 führte eine teilweise Unterstützung für Pydantic v1 i FastAPI 0.126.0 entfernte die Unterstützung für Pydantic v1, während `pydantic.v1` noch eine Weile unterstützt wurde. +FastAPI 0.128.0 entfernte ebenfalls die Unterstützung für `pydantic.v1`, daher erfordern die neuesten Versionen von FastAPI Pydantic v2. + /// warning | Achtung Das Pydantic-Team hat die Unterstützung für Pydantic v1 in den neuesten Python-Versionen eingestellt, beginnend mit **Python 3.14**. @@ -54,6 +56,16 @@ Das bedeutet, Sie können die neueste Version von Pydantic v2 installieren und d ### FastAPI-Unterstützung für Pydantic v1 in v2 { #fastapi-support-for-pydantic-v1-in-v2 } +/// warning | Achtung + +Diese FastAPI-Unterstützung für `pydantic.v1`-Modelle wurde in **FastAPI 0.119.0** hinzugefügt und in **FastAPI 0.128.0** entfernt. Sie war als temporäre Hilfe für die Migration zu Pydantic v2 gedacht. + +In aktuellen Versionen von FastAPI löst die Verwendung eines `pydantic.v1`-Modells in Ihrer App einen Fehler aus. + +Der Rest dieses Abschnitts beschreibt die temporäre Unterstützung, die nur in diesen älteren Versionen verfügbar ist. + +/// + Seit FastAPI 0.119.0 gibt es außerdem eine teilweise Unterstützung für Pydantic v1 innerhalb von Pydantic v2, um die Migration auf v2 zu erleichtern. Sie könnten also Pydantic auf die neueste Version 2 aktualisieren und die Importe so ändern, dass das Untermodul `pydantic.v1` verwendet wird, und in vielen Fällen würde es einfach funktionieren. @@ -122,6 +134,12 @@ Wenn Sie einige der FastAPI-spezifischen Tools für Parameter wie `Body`, `Query ### In Schritten migrieren { #migrate-in-steps } +/// warning | Achtung + +Die unten beschriebene schrittweise Migration mit sowohl Pydantic‑v1‑ als auch Pydantic‑v2‑Modellen in derselben App funktioniert nur in **FastAPI 0.119.0 bis 0.127.x**. Sie wurde in **FastAPI 0.128.0** entfernt, die neuesten Versionen erfordern **Pydantic‑v2**-Modelle. + +/// + /// tip | Tipp Probieren Sie zuerst `bump-pydantic` aus. Wenn Ihre Tests erfolgreich sind und das funktioniert, sind Sie mit einem einzigen Befehl fertig. ✨ diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md index 16f9c8a14..ae1df6176 100644 --- a/docs/de/docs/how-to/separate-openapi-schemas.md +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -1,5 +1,6 @@ # Separate OpenAPI-Schemas für Eingabe und Ausgabe oder nicht { #separate-openapi-schemas-for-input-and-output-or-not } + Seit der Veröffentlichung von **Pydantic v2** ist die generierte OpenAPI etwas genauer und **korrekter** als zuvor. 😎 Tatsächlich gibt es in einigen Fällen sogar **zwei JSON-Schemas** in OpenAPI für dasselbe Pydantic-Modell, für Eingabe und Ausgabe, je nachdem, ob sie **Defaultwerte** haben. @@ -85,7 +86,7 @@ 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 | Info +/// note | Hinweis Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓 diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index d2c282959..9922e7621 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -1,3 +1,8 @@ +--- +include_yaml: + sponsors: data/sponsors.yml +--- + # FastAPI { #fastapi } + +

+ FastAPI +

+

+ FastAPI फ़्रेमवर्क, उच्च प्रदर्शन, सीखने में आसान, कोड लिखने में तेज़, प्रोडक्शन के लिए तैयार +

+

+ + टेस्ट + + + कवरेज + + + पैकेज संस्करण + + + समर्थित Python संस्करण + +

+ +--- + +**दस्तावेज़**: [https://fastapi.tiangolo.com](https://fastapi.tiangolo.com/hi) + +**स्रोत कोड**: [https://github.com/fastapi/fastapi](https://github.com/fastapi/fastapi) + +--- + +FastAPI एक आधुनिक, तेज़ (उच्च-प्रदर्शन) वेब फ़्रेमवर्क है जो मानक Python type hints के आधार पर Python से APIs बनाने के लिए है। + +मुख्य विशेषताएँ: + +* **तेज़**: बहुत उच्च प्रदर्शन, **NodeJS** और **Go** के समकक्ष (Starlette और Pydantic की बदौलत)। [उपलब्ध सबसे तेज़ Python फ़्रेमवर्क्स में से एक](#performance)। +* **कोड लिखने में तेज़**: फ़ीचर्स विकसित करने की गति लगभग 200% से 300% तक बढ़ाएँ। * +* **कम बग्स**: मानवीय (डेवलपर) त्रुटियों में लगभग 40% की कमी। * +* **सहज**: बेहतरीन एडिटर सपोर्ट। हर जगह ऑटो-कम्प्लीट। डिबगिंग में कम समय। +* **आसान**: इस्तेमाल और सीखने में आसान। दस्तावेज़ पढ़ने में कम समय। +* **संक्षिप्त**: कोड डुप्लीकेशन को न्यूनतम करें। प्रत्येक parameter declaration से कई फ़ीचर्स। कम बग्स। +* **मजबूत**: प्रोडक्शन-रेडी कोड प्राप्त करें। स्वतः इंटरैक्टिव दस्तावेज़ीकरण के साथ। +* **मानकों पर आधारित**: APIs के खुले मानकों पर आधारित (और पूर्णतः अनुकूल): [OpenAPI](https://github.com/OAI/OpenAPI-Specification) (जिसे पहले Swagger कहा जाता था) और [JSON Schema](https://json-schema.org/)। + +* आंतरिक डेवलपमेंट टीम द्वारा प्रोडक्शन ऐप्स बनाते समय किए गए परीक्षणों के आधार पर अनुमान। + +## प्रायोजक { #sponsors } + + + +### कीस्टोन प्रायोजक { #keystone-sponsor } + +
+{% for sponsor in sponsors.keystone -%} +{{ sponsor.title }} +{% endfor -%} +
+ +### गोल्ड प्रायोजक { #gold-sponsors } + +
+{% for sponsor in sponsors.gold -%} +{{ sponsor.title }} +{% endfor -%} +
+ +### सिल्वर प्रायोजक { #silver-sponsors } + +
+{% for sponsor in sponsors.silver -%} +{{ sponsor.title }} +{% endfor %} +
+ + + +[अन्य प्रायोजक](https://fastapi.tiangolo.com/hi/fastapi-people/#sponsors) + +## विचार { #opinions } + + +
+
+ + + + +
+ +
+
"मैं इन दिनों FastAPI का बहुत उपयोग कर रहा/रही हूँ। वास्तव में मैं अपनी टीम की Microsoft में ML सेवाओं के लिए इसे उपयोग करने की योजना बना रहा/रही हूँ। इनमें से कुछ को मुख्य Windows प्रोडक्ट और कुछ Office प्रोडक्ट्स में इंटीग्रेट किया जा रहा है।"
+
— कबीर खान, Microsoft (संदर्भ)
+
+ + + +
+ + +
+ +"_[...] मैं इन दिनों **FastAPI** का बहुत उपयोग कर रहा/रही हूँ। [...] वास्तव में मैं अपनी टीम की **Microsoft में ML सेवाओं** के लिए इसे उपयोग करने की योजना बना रहा/रही हूँ। इनमें से कुछ को मुख्य **Windows** प्रोडक्ट और कुछ **Office** प्रोडक्ट्स में इंटीग्रेट किया जा रहा है._" + +
कबीर खान - Microsoft (संदर्भ)
+ +--- + +"_हमने **FastAPI** लाइब्रेरी अपनाई ताकि एक **REST** सर्वर स्पॉन किया जा सके जिसे **अनुमानों** को प्राप्त करने के लिए क्वेरी किया जा सके। [Ludwig के लिए]_" + +
पिएरो मोलिनो, यारोस्लाव डुडिन, और साई सुमंत मिर्याला - Uber (संदर्भ)
+ +--- + +"_**Netflix** हमारे **संकट प्रबंधन** ऑर्केस्ट्रेशन फ़्रेमवर्क: **Dispatch** के ओपन-सोर्स रिलीज़ की घोषणा करते हुए प्रसन्न है! [**FastAPI** के साथ बनाया गया]_" + +
केविन ग्लिसन, मार्क विलानोवा, फॉरेस्ट मॉन्सेन - Netflix (संदर्भ)
+ +--- + +"_यदि कोई प्रोडक्शन Python API बनाना चाहता है, तो मैं **FastAPI** की अत्यधिक अनुशंसा करूंगा/करूंगी। यह **सुंदरता से डिज़ाइन** किया गया है, **उपयोग में सरल** है और **बेहद स्केलेबल** है, यह हमारी API-फ़र्स्ट डेवलपमेंट रणनीति का **मुख्य घटक** बन गया है और हमारे Virtual TAC Engineer जैसे कई ऑटोमेशन्स और सेवाओं को चला रहा है._" + +
डीयोन पिल्सबरी - Cisco (संदर्भ)
+ +--- + +
+ +## FastAPI कॉन्फ़ { #fastapi-conf } + +[**FastAPI Conf '26**](https://fastapiconf.com) **28 अक्टूबर, 2026** को **एम्स्टर्डम, नीदरलैंड्स** में हो रही है। सब कुछ FastAPI के बारे में, सीधे स्रोत से। 🎤 + +FastAPI Conf '26 - 28 अक्टूबर, 2026 - एम्स्टर्डम, NL + +## FastAPI मिनी डॉक्यूमेंट्री { #fastapi-mini-documentary } + +साल 2025 के अंत में एक [FastAPI मिनी डॉक्यूमेंट्री](https://www.youtube.com/watch?v=mpR8ngthqiE) रिलीज़ हुई, आप इसे ऑनलाइन देख सकते हैं: + +FastAPI मिनी डॉक्यूमेंट्री + +## **Typer**, CLIs का FastAPI { #typer-the-fastapi-of-clis } + + + +यदि आप वेब API के बजाय टर्मिनल में उपयोग होने वाला CLI ऐप बना रहे हैं, तो [**Typer**](https://typer.tiangolo.com/) देखें। + +**Typer**, FastAPI का छोटा भाई/बहन है। और इसका उद्देश्य **CLIs का FastAPI** होना है। ⌨️ 🚀 + +## आवश्यकताएँ { #requirements } + +FastAPI दिग्गजों के कंधों पर खड़ा है: + +* वेब हिस्सों के लिए [Starlette](https://www.starlette.dev/)। +* डेटा हिस्सों के लिए [Pydantic](https://docs.pydantic.dev/)। + +## स्थापना { #installation } + +एक [वर्चुअल एन्वायरनमेंट](https://fastapi.tiangolo.com/hi/virtual-environments/) बनाएँ और सक्रिय करें, और फिर FastAPI स्थापित करें: + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +**नोट**: सुनिश्चित करें कि आप सभी टर्मिनलों में काम करने के लिए `"fastapi[standard]"` को उद्धरण-चिह्नों में रखें। + +## उदाहरण { #example } + +### इसे बनाएँ { #create-it } + +`main.py` फ़ाइल बनाएँ और इसमें लिखें: + +```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 = None): + return {"item_id": item_id, "q": q} +``` + +
+या async def का उपयोग करें... + +यदि आपका कोड `async` / `await` का उपयोग करता है, तो `async def` का उपयोग करें: + +```Python hl_lines="7 12" +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: str | None = None): + return {"item_id": item_id, "q": q} +``` + +**नोट**: + +यदि आप नहीं जानते, तो _"जल्दी में?"_ सेक्शन देखें: दस्तावेज़ में [`async` और `await`](https://fastapi.tiangolo.com/hi/async/#in-a-hurry) के बारे में। + +
+ +### इसे चलाएँ { #run-it } + +सर्वर को इस कमांड से चलाएँ: + +
+ +```console +$ fastapi dev + + ╭────────── 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. +``` + +
+ +
+fastapi dev कमांड के बारे में... + +`fastapi dev` कमांड आपका `main.py` फ़ाइल स्वतः पढ़ता है, उसमें **FastAPI** ऐप का पता लगाता है, और [Uvicorn](https://www.uvicorn.dev) का उपयोग करके सर्वर शुरू करता है। + +डिफ़ॉल्ट रूप से, `fastapi dev` लोकल डेवलपमेंट के लिए auto-reload सक्षम करके शुरू होगा। + +आप इसके बारे में और पढ़ सकते हैं: [FastAPI CLI दस्तावेज़](https://fastapi.tiangolo.com/hi/fastapi-cli/) में। + +
+ +### इसे जाँचें { #check-it } + +अपने ब्राउज़र में [http://127.0.0.1:8000/items/5?q=somequery](http://127.0.0.1:8000/items/5?q=somequery) खोलें। + +आपको JSON प्रतिक्रिया इस प्रकार दिखेगी: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +आपने पहले ही एक API बना ली है जो: + +* _paths_ `/` और `/items/{item_id}` पर HTTP अनुरोध स्वीकार करती है। +* दोनों _paths_ `GET` operations लेती हैं (जिन्हें HTTP _methods_ भी कहा जाता है)। +* _path_ `/items/{item_id}` में एक _path parameter_ `item_id` है जो `int` होना चाहिए। +* _path_ `/items/{item_id}` में एक वैकल्पिक `str` _query parameter_ `q` है। + +### इंटरैक्टिव API दस्तावेज़ { #interactive-api-docs } + +अब [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) पर जाएँ। + +आपको स्वचालित इंटरैक्टिव API दस्तावेज़ीकरण दिखेगा (जो [Swagger UI](https://github.com/swagger-api/swagger-ui) द्वारा प्रदान किया जाता है): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### वैकल्पिक API दस्तावेज़ { #alternative-api-docs } + +और अब, [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) पर जाएँ। + +आपको वैकल्पिक स्वचालित दस्तावेज़ीकरण दिखेगा (जो [ReDoc](https://github.com/Rebilly/ReDoc) द्वारा प्रदान किया जाता है): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## उदाहरण उन्नयन { #example-upgrade } + +अब `PUT` अनुरोध से body प्राप्त करने के लिए `main.py` फ़ाइल संशोधित करें। + +Pydantic की बदौलत, body को मानक Python प्रकारों से घोषित करें। + +```Python hl_lines="2 7-10 23-25" +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: bool | None = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: 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} +``` + +`fastapi dev` सर्वर स्वतः रीलोड होना चाहिए। + +### इंटरैक्टिव API दस्तावेज़ उन्नयन { #interactive-api-docs-upgrade } + +अब [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) पर जाएँ। + +* इंटरैक्टिव API दस्तावेज़ स्वतः अपडेट हो जाएगा, नए body सहित: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* "Try it out" बटन पर क्लिक करें, यह आपको parameters भरने और सीधे API के साथ इंटरेक्ट करने की अनुमति देता है: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* फिर "Execute" बटन पर क्लिक करें, यूज़र इंटरफ़ेस आपकी API से संवाद करेगा, parameters भेजेगा, परिणाम प्राप्त करेगा और उन्हें स्क्रीन पर दिखाएगा: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### वैकल्पिक API दस्तावेज़ उन्नयन { #alternative-api-docs-upgrade } + +और अब, [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) पर जाएँ। + +* वैकल्पिक दस्तावेज़ भी नए query parameter और body को दर्शाएगा: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### पुनरावलोकन { #recap } + +संक्षेप में, आप parameters, body, आदि के प्रकार फ़ंक्शन parameters के रूप में **एक बार** घोषित करते हैं। + +आप यह मानक आधुनिक Python प्रकारों से करते हैं। + +आपको किसी नई सिंटैक्स, किसी विशेष लाइब्रेरी के methods या classes, आदि सीखने की आवश्यकता नहीं है। + +बस मानक **Python**। + +उदाहरण के लिए, एक `int` के लिए: + +```Python +item_id: int +``` + +या एक अधिक जटिल `Item` मॉडल के लिए: + +```Python +item: Item +``` + +...और केवल उसी एक घोषणा के साथ आपको मिलता है: + +* एडिटर सपोर्ट, जिसमें शामिल है: + * कम्प्लीशन। + * प्रकार जाँच। +* डेटा का वैधीकरण: + * जब डेटा अमान्य हो तो स्वतः और स्पष्ट त्रुटियाँ। + * गहराई से nested JSON objects के लिए भी वैधीकरण। +* इनपुट डेटा का रूपांतरण: नेटवर्क से Python डेटा और प्रकारों में। इनमें से पढ़ना: + * JSON। + * Path parameters। + * Query parameters। + * Cookies। + * Headers। + * Forms। + * Files। +* आउटपुट डेटा का रूपांतरण: Python डेटा और प्रकारों से नेटवर्क डेटा (JSON के रूप में) में: + * Python प्रकारों का रूपांतरण (`str`, `int`, `float`, `bool`, `list`, आदि)। + * `datetime` ऑब्जेक्ट्स। + * `UUID` ऑब्जेक्ट्स। + * डेटाबेस मॉडल्स। + * ...और बहुत कुछ। +* स्वचालित इंटरैक्टिव API दस्तावेज़ीकरण, जिनमें 2 वैकल्पिक यूज़र इंटरफ़ेस शामिल हैं: + * Swagger UI। + * ReDoc। + +--- + +पिछले कोड उदाहरण पर लौटते हुए, **FastAPI** यह करेगा: + +* `GET` और `PUT` अनुरोधों के लिए path में `item_id` है, यह सत्यापित करेगा। +* `GET` और `PUT` अनुरोधों के लिए `item_id` का प्रकार `int` है, यह सत्यापित करेगा। + * यदि नहीं है, तो क्लाइंट को एक उपयोगी, स्पष्ट त्रुटि दिखाई देगी। +* `GET` अनुरोधों के लिए यह जाँच करेगा कि `q` नाम का एक वैकल्पिक query parameter है (जैसे `http://127.0.0.1:8000/items/foo?q=somequery`)। + * क्योंकि `q` parameter `= None` के साथ घोषित है, यह वैकल्पिक है। + * `None` के बिना यह आवश्यक होता (जैसे `PUT` के मामले में body आवश्यक है)। +* `/items/{item_id}` पर `PUT` अनुरोधों के लिए, body को JSON के रूप में पढ़ेगा: + * यह जाँचेगा कि एक आवश्यक attribute `name` है जो `str` होना चाहिए। + * यह जाँचेगा कि एक आवश्यक attribute `price` है जो `float` होना चाहिए। + * यह जाँचेगा कि एक वैकल्पिक attribute `is_offer` है, जो यदि मौजूद है तो `bool` होना चाहिए। + * यह सब गहराई से nested JSON objects के लिए भी काम करेगा। +* JSON से और JSON में स्वतः रूपांतरण। +* हर चीज़ को OpenAPI के साथ दस्तावेज़ित करेगा, जिसे निम्न द्वारा उपयोग किया जा सकता है: + * इंटरैक्टिव दस्तावेज़ीकरण प्रणालियाँ। + * कई भाषाओं के लिए स्वचालित क्लाइंट कोड जनरेशन प्रणालियाँ। +* सीधे 2 इंटरैक्टिव दस्तावेज़ीकरण वेब इंटरफेसेज़ प्रदान करेगा। + +--- + +हमने केवल सतह को छुआ है, लेकिन आपको पहले ही समझ आ गया होगा कि यह सब कैसे काम करता है। + +इस पंक्ति को बदलकर देखें: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...यहाँ से: + +```Python + ... "item_name": item.name ... +``` + +...यहाँ तक: + +```Python + ... "item_price": item.price ... +``` + +...और देखें कि आपका एडिटर attributes को कैसे auto-complete करेगा और उनके प्रकार जानेगा: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +अधिक फ़ीचर्स सहित एक अधिक सम्पूर्ण उदाहरण के लिए, ट्यूटोरियल - यूज़र गाइड देखें। + +**स्पॉइलर अलर्ट**: ट्यूटोरियल - यूज़र गाइड में शामिल है: + +* विभिन्न स्थानों से **parameters** की घोषणा: **headers**, **cookies**, **form fields** और **files**। +* `maximum_length` या `regex` जैसी **validation constraints** कैसे सेट करें। +* एक बहुत शक्तिशाली और उपयोग में आसान **डिपेंडेंसी इंजेक्शन** सिस्टम। +* सुरक्षा और प्रमाणीकरण, जिसमें **OAuth2** के साथ **JWT tokens** और **HTTP Basic** auth का समर्थन शामिल है। +* **गहराई से nested JSON मॉडल्स** घोषित करने की अधिक उन्नत (पर समान रूप से आसान) तकनीकें (Pydantic की बदौलत)। +* [Strawberry](https://strawberry.rocks) और अन्य लाइब्रेरीज़ के साथ **GraphQL** एकीकरण। +* कई अतिरिक्त फ़ीचर्स (Starlette की बदौलत) जैसे: + * **WebSockets** + * HTTPX और `pytest` पर आधारित अत्यंत आसान टेस्ट्स + * **CORS** + * **Cookie Sessions** + * ...आदि। + +### अपनी ऐप परिनियोजित करें (वैकल्पिक) { #deploy-your-app-optional } + +आप वैकल्पिक रूप से अपनी FastAPI ऐप को [FastAPI Cloud](https://fastapicloud.com) पर एक ही कमांड से डिप्लॉय कर सकते हैं। 🚀 + +
+ +```console +$ fastapi deploy + +Deploying to FastAPI Cloud... + +✅ Deployment successful! + +🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev +``` + +
+ +CLI आपकी FastAPI एप्लिकेशन को स्वतः पहचान लेगा और उसे क्लाउड पर डिप्लॉय करेगा। यदि आप logged in नहीं हैं, तो प्रमाणीकरण प्रक्रिया पूरी करने के लिए आपका ब्राउज़र खुलेगा। + +बस इतना ही! अब आप उस URL पर अपनी ऐप एक्सेस कर सकते हैं। ✨ + +#### FastAPI Cloud के बारे में { #about-fastapi-cloud } + +**[FastAPI Cloud](https://fastapicloud.com)** को **FastAPI** के ही लेखक और टीम ने बनाया है। + +यह न्यूनतम प्रयास में किसी API को **बनाने**, **डिप्लॉय** करने और **एक्सेस** करने की प्रक्रिया को सरल बनाता है। + +यह FastAPI के साथ ऐप्स बनाने के उसी **डेवलपर अनुभव** को उन्हें क्लाउड में **डिप्लॉय** करने तक लाता है। 🎉 + +FastAPI Cloud, *FastAPI and friends* ओपन सोर्स प्रोजेक्ट्स के लिए मुख्य प्रायोजक और फंडिंग प्रदाता है। ✨ + +#### अन्य क्लाउड प्रदाताओं पर डिप्लॉय करें { #deploy-to-other-cloud-providers } + +FastAPI ओपन सोर्स है और मानकों पर आधारित है। आप FastAPI ऐप्स को किसी भी क्लाउड प्रदाता पर डिप्लॉय कर सकते हैं। + +अपने क्लाउड प्रदाता के गाइड्स का पालन करें और उनके साथ FastAPI ऐप्स डिप्लॉय करें। 🤓 + +## प्रदर्शन { #performance } + +स्वतंत्र TechEmpower बेंचमार्क दिखाते हैं कि Uvicorn के तहत चलने वाले **FastAPI** एप्लीकेशन्स [उपलब्ध सबसे तेज़ Python फ़्रेमवर्क्स में से एक](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7) हैं, केवल Starlette और Uvicorn (जो FastAPI द्वारा आंतरिक रूप से उपयोग किए जाते हैं) से नीचे। (*) + +इसके बारे में अधिक समझने के लिए, [बेंचमार्क्स](https://fastapi.tiangolo.com/hi/benchmarks/) सेक्शन देखें। + +## निर्भरताएँ { #dependencies } + +FastAPI, Pydantic और Starlette पर निर्भर करता है। + +### `standard` निर्भरताएँ { #standard-dependencies } + +जब आप `pip install "fastapi[standard]"` के साथ FastAPI स्थापित करते हैं, तो यह `standard` समूह की वैकल्पिक निर्भरताओं के साथ आता है: + +Pydantic द्वारा उपयोग किया गया: + +* [`email-validator`](https://github.com/JoshData/python-email-validator) - ईमेल वैधीकरण के लिए। + +Starlette द्वारा उपयोग किया गया: + +* [`httpx`](https://www.python-httpx.org) - यदि आप `TestClient` का उपयोग करना चाहते हैं तो आवश्यक। +* [`jinja2`](https://jinja.palletsprojects.com) - यदि आप डिफ़ॉल्ट टेम्पलेट कॉन्फ़िगरेशन का उपयोग करना चाहते हैं तो आवश्यक। +* [`python-multipart`](https://github.com/Kludex/python-multipart) - यदि आप फॉर्म "पार्सिंग" का समर्थन करना चाहते हैं, `request.form()` के साथ, तो आवश्यक। + +FastAPI द्वारा उपयोग किया गया: + +* [`uvicorn`](https://www.uvicorn.dev) - वह सर्वर जो आपकी एप्लिकेशन को लोड और सर्व करता है। इसमें `uvicorn[standard]` शामिल है, जिसमें उच्च-प्रदर्शन सर्विंग के लिए कुछ निर्भरताएँ (जैसे `uvloop`) शामिल हैं। +* `fastapi-cli[standard]` - `fastapi` कमांड प्रदान करने के लिए। + * इसमें `fastapi-cloud-cli` शामिल है, जो आपको अपनी FastAPI एप्लिकेशन को [FastAPI Cloud](https://fastapicloud.com) पर डिप्लॉय करने की अनुमति देता है। + +### `standard` निर्भरताओं के बिना { #without-standard-dependencies } + +यदि आप `standard` वैकल्पिक निर्भरताओं को शामिल नहीं करना चाहते, तो आप `pip install fastapi` के साथ स्थापित कर सकते हैं, `pip install "fastapi[standard]"` के बजाय। + +### `fastapi-cloud-cli` के बिना { #without-fastapi-cloud-cli } + +यदि आप standard निर्भरताओं के साथ लेकिन `fastapi-cloud-cli` के बिना FastAPI स्थापित करना चाहते हैं, तो `pip install "fastapi[standard-no-fastapi-cloud-cli]"` के साथ स्थापित कर सकते हैं। + +### अतिरिक्त वैकल्पिक निर्भरताएँ { #additional-optional-dependencies } + +कुछ अतिरिक्त निर्भरताएँ हैं जिन्हें आप स्थापित करना चाहेंगे। + +अतिरिक्त वैकल्पिक Pydantic निर्भरताएँ: + +* [`pydantic-settings`](https://docs.pydantic.dev/latest/usage/pydantic_settings/) - सेटिंग्स प्रबंधन के लिए। +* [`pydantic-extra-types`](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/) - Pydantic के साथ उपयोग करने के लिए अतिरिक्त प्रकारों हेतु। + +अतिरिक्त वैकल्पिक FastAPI निर्भरताएँ: + +* [`orjson`](https://github.com/ijl/orjson) - यदि आप `ORJSONResponse` उपयोग करना चाहते हैं तो आवश्यक। +* [`ujson`](https://github.com/esnme/ultrajson) - यदि आप `UJSONResponse` उपयोग करना चाहते हैं तो आवश्यक। + +## लाइसेंस { #license } + +यह प्रोजेक्ट MIT लाइसेंस की शर्तों के अंतर्गत लाइसेंस प्राप्त है। diff --git a/docs/hi/docs/learn/index.md b/docs/hi/docs/learn/index.md new file mode 100644 index 000000000..20f63c173 --- /dev/null +++ b/docs/hi/docs/learn/index.md @@ -0,0 +1,5 @@ +# सीखें { #learn } + +यहाँ **FastAPI** सीखने के लिए परिचयात्मक section और ट्यूटोरियल हैं। + +आप इसे FastAPI सीखने का एक **book**, एक **course**, **आधिकारिक** और अनुशंसित तरीका मान सकते हैं। 😎 diff --git a/docs/hi/docs/project-generation.md b/docs/hi/docs/project-generation.md new file mode 100644 index 000000000..747e4da53 --- /dev/null +++ b/docs/hi/docs/project-generation.md @@ -0,0 +1,28 @@ +# Full Stack FastAPI Template { #full-stack-fastapi-template } + +Templates आम तौर पर एक विशिष्ट setup के साथ आते हैं, लेकिन उन्हें flexible और customizable होने के लिए डिज़ाइन किया जाता है। इससे आप उन्हें अपने project की आवश्यकताओं के अनुसार modify और adapt कर सकते हैं, जिससे वे एक बेहतरीन starting point बन जाते हैं। 🏁 + +आप शुरू करने के लिए इस template का उपयोग कर सकते हैं, क्योंकि इसमें आपके लिए बहुत सा initial setup, security, database और कुछ API endpoints पहले से तैयार हैं। + +GitHub Repository: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template) + +## Full Stack FastAPI Template - Technology Stack और Features { #full-stack-fastapi-template-technology-stack-and-features } + +- ⚡ Python backend API के लिए [**FastAPI**](https://fastapi.tiangolo.com/hi)। + - 🧰 Python SQL database interactions (ORM) के लिए [SQLModel](https://sqlmodel.tiangolo.com)। + - 🔍 data validation और settings management के लिए [Pydantic](https://docs.pydantic.dev), जिसका उपयोग FastAPI करता है। + - 💾 SQL database के रूप में [PostgreSQL](https://www.postgresql.org)। +- 🚀 frontend के लिए [React](https://react.dev)। + - 💃 TypeScript, hooks, Vite, और modern frontend stack के अन्य parts का उपयोग। + - 🎨 frontend components के लिए [Tailwind CSS](https://tailwindcss.com) और [shadcn/ui](https://ui.shadcn.com)। + - 🤖 एक automatically generated frontend client। + - 🧪 End-to-End testing के लिए [Playwright](https://playwright.dev)। + - 🦇 Dark mode support। +- 🐋 development और production के लिए [Docker Compose](https://www.docker.com)। +- 🔒 default रूप से secure password hashing। +- 🔑 JWT (JSON Web Token) authentication। +- 📫 Email आधारित password recovery। +- ✅ [Pytest](https://pytest.org) के साथ tests। +- 📞 reverse proxy / load balancer के रूप में [Traefik](https://traefik.io)। +- 🚢 Docker Compose का उपयोग करके deployment instructions, जिसमें automatic HTTPS certificates handle करने के लिए frontend Traefik proxy setup करना शामिल है। +- 🏭 GitHub Actions पर आधारित CI (continuous integration) और CD (continuous deployment)। diff --git a/docs/hi/docs/python-types.md b/docs/hi/docs/python-types.md new file mode 100644 index 000000000..86522e18e --- /dev/null +++ b/docs/hi/docs/python-types.md @@ -0,0 +1,348 @@ +# Python Types परिचय { #python-types-intro } + +Python में वैकल्पिक "type hints" (जिन्हें "type annotations" भी कहा जाता है) का समर्थन है। + +ये **"type hints"** या annotations एक विशेष syntax हैं, जो किसी variable का type घोषित करने की अनुमति देते हैं। + +अपने variables के लिए types घोषित करके, editors और tools आपको बेहतर support दे सकते हैं। + +यह Python type hints के बारे में बस एक **त्वरित tutorial / refresher** है। इसमें केवल उतना ही शामिल है जितना उन्हें **FastAPI** के साथ उपयोग करने के लिए न्यूनतम रूप से आवश्यक है... जो वास्तव में बहुत कम है। + +**FastAPI** पूरी तरह से इन्हीं type hints पर आधारित है, ये इसे कई फायदे और लाभ देते हैं। + +लेकिन अगर आप कभी **FastAPI** का उपयोग नहीं भी करते, तब भी इनके बारे में थोड़ा सीखने से आपको लाभ होगा। + +/// note | नोट + +अगर आप Python expert हैं, और type hints के बारे में पहले से सब कुछ जानते हैं, तो अगले chapter पर जाएँ। + +/// + +## प्रेरणा { #motivation } + +आइए एक सरल उदाहरण से शुरू करें: + +{* ../../docs_src/python_types/tutorial001_py310.py *} + +इस program को call करने पर output आता है: + +``` +John Doe +``` + +Function निम्नलिखित करता है: + +* एक `first_name` और `last_name` लेता है। +* प्रत्येक के पहले अक्षर को `title()` के साथ upper case में बदलता है। +* उन्हें बीच में एक space के साथ Concatenate करता है। + +{* ../../docs_src/python_types/tutorial001_py310.py hl[2] *} + +### इसे edit करें { #edit-it } + +यह एक बहुत सरल program है। + +लेकिन अब कल्पना करें कि आप इसे scratch से लिख रहे थे। + +किसी point पर आप function define करना शुरू करते हैं, और आपके parameters तैयार हैं... + +लेकिन फिर आपको "वह method जो पहले अक्षर को upper case में बदलता है" call करना है। + +क्या वह `upper` था? क्या वह `uppercase` था? `first_uppercase`? `capitalize`? + +फिर, आप programmer के पुराने दोस्त, editor autocompletion के साथ कोशिश करते हैं। + +आप function का पहला parameter, `first_name`, फिर एक dot (`.`) type करते हैं और फिर completion trigger करने के लिए `Ctrl+Space` दबाते हैं। + +लेकिन, दुख की बात है, आपको कुछ भी उपयोगी नहीं मिलता: + + + +### Types जोड़ें { #add-types } + +आइए पिछले version की एक single line बदलते हैं। + +हम ठीक इस fragment को, function के parameters को, इससे बदलेंगे: + +```Python + first_name, last_name +``` + +इसमें: + +```Python + first_name: str, last_name: str +``` + +बस इतना ही। + +यही "type hints" हैं: + +{* ../../docs_src/python_types/tutorial002_py310.py hl[1] *} + +यह default values declare करने जैसा नहीं है, जैसा कि इसमें होता: + +```Python + first_name="john", last_name="doe" +``` + +यह एक अलग चीज़ है। + +हम colons (`:`) का उपयोग कर रहे हैं, equals (`=`) का नहीं। + +और type hints जोड़ने से सामान्यतः यह नहीं बदलता कि बिना उनके जो होता, वह कैसे होता। + +लेकिन अब, कल्पना करें कि आप फिर से उस function को बनाने के बीच में हैं, लेकिन type hints के साथ। + +उसी point पर, आप `Ctrl+Space` के साथ autocomplete trigger करने की कोशिश करते हैं और आप देखते हैं: + + + +इसके साथ, आप options देखते हुए scroll कर सकते हैं, जब तक आपको वह न मिल जाए जो "पहचाना हुआ लगे": + + + +## और प्रेरणा { #more-motivation } + +इस function को देखें, इसमें पहले से type hints हैं: + +{* ../../docs_src/python_types/tutorial003_py310.py hl[1] *} + +क्योंकि editor variables के types जानता है, आपको केवल completion ही नहीं मिलता, आपको error checks भी मिलते हैं: + + + +अब आप जानते हैं कि आपको इसे ठीक करना है, `age` को `str(age)` के साथ string में convert करना है: + +{* ../../docs_src/python_types/tutorial004_py310.py hl[2] *} + +## Types declare करना { #declaring-types } + +आपने अभी type hints declare करने की मुख्य जगह देखी। Function parameters के रूप में। + +यही वह मुख्य जगह भी है जहाँ आप उन्हें **FastAPI** के साथ उपयोग करेंगे। + +### Simple types { #simple-types } + +आप सभी standard Python types declare कर सकते हैं, केवल `str` ही नहीं। + +आप उदाहरण के लिए उपयोग कर सकते हैं: + +* `int` +* `float` +* `bool` +* `bytes` + +{* ../../docs_src/python_types/tutorial005_py310.py hl[1] *} + +### `typing` module { #typing-module } + +कुछ अतिरिक्त use cases के लिए, आपको standard library के `typing` module से कुछ चीज़ें import करने की आवश्यकता हो सकती है, उदाहरण के लिए जब आप declare करना चाहते हैं कि किसी चीज़ का "कोई भी type" है, तो आप `typing` से `Any` का उपयोग कर सकते हैं: + +```python +from typing import Any + + +def some_function(data: Any): + print(data) +``` + +### Generic types { #generic-types } + +कुछ types square brackets में "type parameters" ले सकते हैं, ताकि उनके internal types define किए जा सकें, उदाहरण के लिए "strings की list" को `list[str]` declare किया जाएगा। + +जो types type parameters ले सकते हैं उन्हें **Generic types** या **Generics** कहा जाता है। + +आप उन्हीं builtin types को generics के रूप में उपयोग कर सकते हैं (square brackets और अंदर types के साथ): + +* `list` +* `tuple` +* `set` +* `dict` + +#### List { #list } + +उदाहरण के लिए, आइए एक variable को `str` की `list` के रूप में define करते हैं। + +Variable को उसी colon (`:`) syntax के साथ declare करें। + +Type के रूप में, `list` रखें। + +क्योंकि list एक ऐसा type है जिसमें कुछ internal types होते हैं, आप उन्हें square brackets में रखते हैं: + +{* ../../docs_src/python_types/tutorial006_py310.py hl[1] *} + +/// note | नोट + +Square brackets में मौजूद उन internal types को "type parameters" कहा जाता है। + +इस case में, `str` वह type parameter है जो `list` को pass किया गया है। + +/// + +इसका मतलब है: "variable `items` एक `list` है, और इस list का प्रत्येक item एक `str` है"। + +ऐसा करने से, आपका editor list से items process करते समय भी support दे सकता है: + + + +Types के बिना, इसे हासिल करना लगभग असंभव है। + +ध्यान दें कि variable `item`, list `items` के elements में से एक है। + +और फिर भी, editor जानता है कि यह एक `str` है, और उसके लिए support देता है। + +#### Tuple और Set { #tuple-and-set } + +आप `tuple`s और `set`s declare करने के लिए भी ऐसा ही करेंगे: + +{* ../../docs_src/python_types/tutorial007_py310.py hl[1] *} + +इसका मतलब है: + +* Variable `items_t` 3 items वाला एक `tuple` है, एक `int`, दूसरा `int`, और एक `str`। +* Variable `items_s` एक `set` है, और इसके प्रत्येक item का type `bytes` है। + +#### Dict { #dict } + +`dict` define करने के लिए, आप 2 type parameters pass करते हैं, commas से separated। + +पहला type parameter `dict` की keys के लिए होता है। + +दूसरा type parameter `dict` की values के लिए होता है: + +{* ../../docs_src/python_types/tutorial008_py310.py hl[1] *} + +इसका मतलब है: + +* Variable `prices` एक `dict` है: + * इस `dict` की keys `str` type की हैं (मान लें, प्रत्येक item का नाम)। + * इस `dict` की values `float` type की हैं (मान लें, प्रत्येक item की price)। + +#### Union { #union } + +आप declare कर सकते हैं कि कोई variable **कई types** में से कोई भी हो सकता है, उदाहरण के लिए, एक `int` या एक `str`। + +इसे define करने के लिए आप दोनों types को separate करने के लिए vertical bar (`|`) का उपयोग करते हैं। + +इसे "union" कहा जाता है, क्योंकि variable उन दो type sets के union में कुछ भी हो सकता है। + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +इसका मतलब है कि `item` एक `int` या एक `str` हो सकता है। + +#### संभवतः `None` { #possibly-none } + +आप declare कर सकते हैं कि किसी value का type, जैसे `str`, हो सकता है, लेकिन वह `None` भी हो सकती है। + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +सिर्फ `str` के बजाय `str | None` का उपयोग करने से editor आपको उन errors को detect करने में मदद करेगा जहाँ आप यह मान रहे हो सकते हैं कि कोई value हमेशा `str` है, जबकि वास्तव में वह `None` भी हो सकती है। + +### Classes को types के रूप में { #classes-as-types } + +आप किसी class को भी variable के type के रूप में declare कर सकते हैं। + +मान लें आपके पास एक class `Person` है, जिसमें एक name है: + +{* ../../docs_src/python_types/tutorial010_py310.py hl[1:3] *} + +फिर आप किसी variable को `Person` type का declare कर सकते हैं: + +{* ../../docs_src/python_types/tutorial010_py310.py hl[6] *} + +और फिर, फिर से, आपको पूरा editor support मिलता है: + + + +ध्यान दें कि इसका मतलब है "`one_person`, class `Person` का एक **instance** है"। + +इसका मतलब यह नहीं है कि "`one_person`, `Person` नाम की **class** है"। + +## Pydantic models { #pydantic-models } + +[Pydantic](https://docs.pydantic.dev/) data validation करने के लिए एक Python library है। + +आप data की "shape" को attributes वाली classes के रूप में declare करते हैं। + +और प्रत्येक attribute का एक type होता है। + +फिर आप कुछ values के साथ उस class का एक instance create करते हैं और यह values को validate करेगा, उन्हें appropriate type में convert करेगा (अगर ऐसा case है) और आपको पूरे data वाला एक object देगा। + +और उस resulting object के साथ आपको पूरा editor support मिलता है। + +Official Pydantic docs से एक उदाहरण: + +{* ../../docs_src/python_types/tutorial011_py310.py *} + +/// note | नोट + +अधिक जानने के लिए [Pydantic, इसके docs देखें](https://docs.pydantic.dev/)। + +/// + +**FastAPI** पूरी तरह से Pydantic पर आधारित है। + +आप यह सब practice में [Tutorial - User Guide](tutorial/index.md) में बहुत अधिक देखेंगे। + +## Metadata Annotations के साथ Type Hints { #type-hints-with-metadata-annotations } + +Python में एक feature भी है जो `Annotated` का उपयोग करके इन type hints में **अतिरिक्त metadata** डालने की अनुमति देता है। + +आप `typing` से `Annotated` import कर सकते हैं। + +{* ../../docs_src/python_types/tutorial013_py310.py hl[1,4] *} + +Python खुद इस `Annotated` के साथ कुछ नहीं करता। और editors और अन्य tools के लिए, type अभी भी `str` है। + +लेकिन आप `Annotated` में इस जगह का उपयोग **FastAPI** को अतिरिक्त metadata देने के लिए कर सकते हैं कि आप अपनी application को कैसे behave कराना चाहते हैं। + +याद रखने वाली महत्वपूर्ण बात यह है कि `Annotated` को pass किया गया **पहला *type parameter*** ही **actual type** होता है। बाकी सब, अन्य tools के लिए केवल metadata है। + +अभी के लिए, आपको बस यह जानना है कि `Annotated` मौजूद है, और यह standard Python है। 😎 + +बाद में आप देखेंगे कि यह कितना **powerful** हो सकता है। + +/// tip | सुझाव + +यह तथ्य कि यह **standard Python** है, इसका मतलब है कि आपको अपने editor में, अपने code को analyze और refactor करने वाले tools के साथ, आदि, अभी भी **सबसे अच्छा possible developer experience** मिलेगा। ✨ + +और यह भी कि आपका code कई अन्य Python tools और libraries के साथ बहुत compatible होगा। 🚀 + +/// + +## **FastAPI** में Type hints { #type-hints-in-fastapi } + +**FastAPI** इन type hints का लाभ उठाकर कई चीज़ें करता है। + +**FastAPI** के साथ आप type hints के साथ parameters declare करते हैं और आपको मिलता है: + +* **Editor support**। +* **Type checks**। + +...और **FastAPI** उन्हीं declarations का उपयोग करता है: + +* **Requirements define** करने के लिए: request path parameters, query parameters, headers, bodies, dependencies, आदि से। +* **Data convert** करने के लिए: request से required type में। +* **Data validate** करने के लिए: प्रत्येक request से आने वाले data को: + * Data invalid होने पर client को लौटाए जाने वाले **automatic errors** generate करना। +* OpenAPI का उपयोग करके API को **document** करने के लिए: + * जिसका उपयोग फिर automatic interactive documentation user interfaces द्वारा किया जाता है। + +यह सब abstract लग सकता है। चिंता न करें। आप यह सब action में [Tutorial - User Guide](tutorial/index.md) में देखेंगे। + +महत्वपूर्ण बात यह है कि standard Python types का उपयोग करके, एक ही जगह पर (अधिक classes, decorators, आदि जोड़ने के बजाय), **FastAPI** आपके लिए बहुत सारा काम कर देगा। + +/// note | नोट + +अगर आप पहले ही पूरे tutorial से गुजर चुके हैं और types के बारे में और देखने के लिए वापस आए हैं, तो एक अच्छा resource [`mypy` की "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html) है। + +/// diff --git a/docs/hi/docs/resources/index.md b/docs/hi/docs/resources/index.md new file mode 100644 index 000000000..d60effdc7 --- /dev/null +++ b/docs/hi/docs/resources/index.md @@ -0,0 +1,3 @@ +# संसाधन { #resources } + +अतिरिक्त संसाधन, external links, और भी बहुत कुछ। ✈️ diff --git a/docs/hi/docs/translation-banner.md b/docs/hi/docs/translation-banner.md new file mode 100644 index 000000000..af9fedda8 --- /dev/null +++ b/docs/hi/docs/translation-banner.md @@ -0,0 +1,11 @@ +/// details | 🌐 एआई और मनुष्यों द्वारा किया गया अनुवाद + +यह अनुवाद मनुष्यों के मार्गदर्शन में एआई द्वारा किया गया है। 🤝 + +इसमें मूल अर्थ को गलत समझने या अप्राकृतिक लगने आदि जैसी गलतियाँ हो सकती हैं। 🤖 + +आप [हमें एआई LLM को बेहतर मार्गदर्शन करने में मदद करके](https://fastapi.tiangolo.com/hi/contributing/#translations) इस अनुवाद को बेहतर बना सकते हैं। + +[अंग्रेज़ी संस्करण](ENGLISH_VERSION_URL) + +/// diff --git a/docs/hi/docs/tutorial/background-tasks.md b/docs/hi/docs/tutorial/background-tasks.md new file mode 100644 index 000000000..f1c685644 --- /dev/null +++ b/docs/hi/docs/tutorial/background-tasks.md @@ -0,0 +1,86 @@ +# Background Tasks { #background-tasks } + +आप background tasks define कर सकते हैं जिन्हें response लौटाने के *बाद* चलाया जाए। + +यह उन operations के लिए उपयोगी है जिन्हें request के बाद होना होता है, लेकिन client को response पाने से पहले operation के पूरा होने का इंतज़ार करने की वास्तव में ज़रूरत नहीं होती। + +इसमें, उदाहरण के लिए, ये शामिल हैं: + +* कोई action करने के बाद भेजे गए email notifications: + * क्योंकि email server से connect करना और email भेजना आम तौर पर "slow" (कई seconds) होता है, आप response तुरंत लौटा सकते हैं और email notification को background में भेज सकते हैं। +* data process करना: + * उदाहरण के लिए, मान लीजिए आपको एक file मिलती है जिसे किसी slow process से गुजरना है, आप "Accepted" (HTTP 202) का response लौटा सकते हैं और file को background में process कर सकते हैं। + +## `BackgroundTasks` का उपयोग करना { #using-backgroundtasks } + +सबसे पहले, `BackgroundTasks` import करें और अपनी *path operation function* में `BackgroundTasks` की type declaration के साथ एक parameter define करें: + +{* ../../docs_src/background_tasks/tutorial001_py310.py hl[1,13] *} + +**FastAPI** आपके लिए `BackgroundTasks` type का object बनाएगा और उसे उस parameter के रूप में pass करेगा। + +## task function बनाएँ { #create-a-task-function } + +background task के रूप में चलाने के लिए एक function बनाएँ। + +यह बस एक standard function है जो parameters receive कर सकता है। + +यह `async def` या normal `def` function हो सकता है, **FastAPI** जानता होगा कि इसे सही तरीके से कैसे handle करना है। + +इस case में, task function एक file में लिखेगा (email भेजने का simulation करते हुए)। + +और क्योंकि write operation `async` और `await` का उपयोग नहीं करता, हम function को normal `def` के साथ define करते हैं: + +{* ../../docs_src/background_tasks/tutorial001_py310.py hl[6:9] *} + +## background task जोड़ें { #add-the-background-task } + +अपनी *path operation function* के अंदर, अपनी task function को *background tasks* object में method `.add_task()` के साथ pass करें: + +{* ../../docs_src/background_tasks/tutorial001_py310.py hl[14] *} + +`.add_task()` arguments के रूप में receive करता है: + +* background में चलाने के लिए एक task function (`write_notification`)। +* arguments की कोई भी sequence जो order में task function को pass की जानी चाहिए (`email`)। +* कोई भी keyword arguments जो task function को pass किए जाने चाहिए (`message="some notification"`)। + +## Dependency Injection { #dependency-injection } + +`BackgroundTasks` का उपयोग dependency injection system के साथ भी काम करता है, आप कई levels पर `BackgroundTasks` type का parameter declare कर सकते हैं: किसी *path operation function* में, dependency (dependable) में, sub-dependency में, आदि। + +**FastAPI** जानता है कि हर case में क्या करना है और same object को कैसे reuse करना है, ताकि सभी background tasks merge हो जाएँ और बाद में background में run हों: + + +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *} + + +इस example में, response भेजे जाने के *बाद* messages `log.txt` file में लिखे जाएँगे। + +अगर request में कोई query थी, तो उसे एक background task में log में लिखा जाएगा। + +और फिर *path operation function* पर generate हुआ एक और background task `email` path parameter का उपयोग करके एक message लिखेगा। + +## Technical Details { #technical-details } + +class `BackgroundTasks` सीधे [`starlette.background`](https://www.starlette.dev/background/) से आती है। + +इसे सीधे FastAPI में import/include किया गया है ताकि आप इसे `fastapi` से import कर सकें और गलती से `starlette.background` से alternative `BackgroundTask` (अंत में `s` के बिना) import करने से बच सकें। + +सिर्फ `BackgroundTasks` (और `BackgroundTask` नहीं) का उपयोग करने से, इसे *path operation function* parameter के रूप में use करना संभव होता है और **FastAPI** आपके लिए बाकी चीज़ें handle करता है, ठीक वैसे ही जैसे `Request` object को सीधे use करते समय होता है। + +FastAPI में अकेले `BackgroundTask` का उपयोग करना अभी भी संभव है, लेकिन आपको अपने code में object बनाना होगा और उसे शामिल करते हुए Starlette `Response` return करना होगा। + +आप [Background Tasks के लिए Starlette के official docs](https://www.starlette.dev/background/) में अधिक details देख सकते हैं। + +## सावधानी { #caveat } + +अगर आपको heavy background computation perform करनी है और यह ज़रूरी नहीं है कि वह same process द्वारा run हो (उदाहरण के लिए, आपको memory, variables, आदि share करने की ज़रूरत नहीं है), तो आपको [Celery](https://docs.celeryq.dev) जैसे दूसरे बड़े tools का उपयोग करने से लाभ हो सकता है। + +उन्हें आम तौर पर अधिक complex configurations, RabbitMQ या Redis जैसे message/job queue manager की ज़रूरत होती है, लेकिन वे आपको multiple processes में, और खासकर multiple servers में, background tasks run करने देते हैं। + +लेकिन अगर आपको उसी **FastAPI** app से variables और objects access करने हैं, या आपको छोटे background tasks perform करने हैं (जैसे email notification भेजना), तो आप आसानी से `BackgroundTasks` का उपयोग कर सकते हैं। + +## Recap { #recap } + +background tasks जोड़ने के लिए *path operation functions* और dependencies में parameters के साथ `BackgroundTasks` import और use करें। diff --git a/docs/hi/docs/tutorial/bigger-applications.md b/docs/hi/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..263a59397 --- /dev/null +++ b/docs/hi/docs/tutorial/bigger-applications.md @@ -0,0 +1,547 @@ +# बड़े Applications - Multiple Files { #bigger-applications-multiple-files } + +अगर आप कोई application या web API बना रहे हैं, तो ऐसा कम ही होता है कि आप सब कुछ एक ही file में रख सकें। + +**FastAPI** आपके application को structure करने के लिए एक सुविधाजनक tool देता है, और साथ ही पूरी flexibility भी बनाए रखता है। + +/// note | नोट + +अगर आप Flask से आए हैं, तो यह Flask के Blueprints के बराबर होगा। + +/// + +## एक उदाहरण file structure { #an-example-file-structure } + +मान लीजिए आपके पास ऐसा file structure है: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +│ ├── dependencies.py +│ └── routers +│ │ ├── __init__.py +│ │ ├── items.py +│ │ └── users.py +│ └── internal +│ ├── __init__.py +│ └── admin.py +``` + +/// tip | टिप + +कई `__init__.py` files हैं: हर directory या subdirectory में एक। + +यही एक file से दूसरी file में code import करने की अनुमति देता है। + +उदाहरण के लिए, `app/main.py` में आपके पास ऐसी line हो सकती है: + +``` +from app.routers import items +``` + +/// + +* `app` directory में सब कुछ है। और इसमें एक खाली file `app/__init__.py` है, इसलिए यह एक "Python package" है ("Python modules" का संग्रह): `app`. +* इसमें एक `app/main.py` file है। क्योंकि यह एक Python package (एक ऐसी directory जिसमें `__init__.py` file है) के अंदर है, यह उस package का एक "module" है: `app.main`. +* एक `app/dependencies.py` file भी है, `app/main.py` की तरह, यह एक "module" है: `app.dependencies`. +* एक subdirectory `app/routers/` है जिसमें एक और file `__init__.py` है, इसलिए यह एक "Python subpackage" है: `app.routers`. +* file `app/routers/items.py` एक package, `app/routers/`, के अंदर है, इसलिए यह एक submodule है: `app.routers.items`. +* `app/routers/users.py` के साथ भी वही है, यह एक और submodule है: `app.routers.users`. +* एक subdirectory `app/internal/` भी है जिसमें एक और file `__init__.py` है, इसलिए यह एक और "Python subpackage" है: `app.internal`. +* और file `app/internal/admin.py` एक और submodule है: `app.internal.admin`. + + + +वही file structure comments के साथ: + +```bash +. +├── app # "app" एक Python package है +│   ├── __init__.py # यह file "app" को "Python package" बनाती है +│   ├── main.py # "main" module, जैसे import app.main +│   ├── dependencies.py # "dependencies" module, जैसे import app.dependencies +│   └── routers # "routers" एक "Python subpackage" है +│   │ ├── __init__.py # "routers" को "Python subpackage" बनाता है +│   │ ├── items.py # "items" submodule, जैसे import app.routers.items +│   │ └── users.py # "users" submodule, जैसे import app.routers.users +│   └── internal # "internal" एक "Python subpackage" है +│   ├── __init__.py # "internal" को "Python subpackage" बनाता है +│   └── admin.py # "admin" submodule, जैसे import app.internal.admin +``` + +## `APIRouter` { #apirouter } + +मान लीजिए सिर्फ users को handle करने के लिए dedicated file `/app/routers/users.py` पर submodule है। + +आप अपने users से संबंधित *path operations* को बाकी code से अलग रखना चाहते हैं, ताकि यह व्यवस्थित रहे। + +लेकिन यह अभी भी उसी **FastAPI** application/web API का हिस्सा है (यह उसी "Python Package" का हिस्सा है)। + +आप उस module के लिए *path operations* `APIRouter` का उपयोग करके बना सकते हैं। + +### `APIRouter` import करें { #import-apirouter } + +आप इसे import करते हैं और उसी तरह एक "instance" बनाते हैं जैसे आप `FastAPI` class के साथ करते: + +{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[1,3] title["app/routers/users.py"] *} + +### `APIRouter` के साथ *Path operations* { #path-operations-with-apirouter } + +और फिर आप इसका उपयोग अपने *path operations* declare करने के लिए करते हैं। + +इसे उसी तरह उपयोग करें जैसे आप `FastAPI` class का उपयोग करते: + +{* ../../docs_src/bigger_applications/app_an_py310/routers/users.py hl[6,11,16] title["app/routers/users.py"] *} + +आप `APIRouter` को एक "mini `FastAPI`" class की तरह सोच सकते हैं। + +सभी वही options समर्थित हैं। + +सभी वही `parameters`, `responses`, `dependencies`, `tags`, आदि। + +/// tip | टिप + +इस उदाहरण में, variable को `router` कहा गया है, लेकिन आप इसे अपनी इच्छा अनुसार कोई भी नाम दे सकते हैं। + +/// + +हम इस `APIRouter` को main `FastAPI` app में शामिल करने जा रहे हैं, लेकिन पहले, dependencies और एक और `APIRouter` देखें। + +## Dependencies { #dependencies } + +हम देखते हैं कि हमें application के कई स्थानों पर उपयोग होने वाली कुछ dependencies की ज़रूरत होगी। + +इसलिए हम उन्हें उनके अपने `dependencies` module (`app/dependencies.py`) में रखते हैं। + +अब हम एक custom `X-Token` header पढ़ने के लिए एक सरल dependency का उपयोग करेंगे: + +{* ../../docs_src/bigger_applications/app_an_py310/dependencies.py hl[3,6:8] title["app/dependencies.py"] *} + +/// tip | टिप + +हम इस उदाहरण को सरल बनाने के लिए एक काल्पनिक header का उपयोग कर रहे हैं। + +लेकिन वास्तविक मामलों में आपको integrated [Security utilities](security/index.md) का उपयोग करके बेहतर परिणाम मिलेंगे। + +/// + +## `APIRouter` के साथ एक और module { #another-module-with-apirouter } + +मान लीजिए आपके application से "items" को handle करने के लिए dedicated endpoints भी `app/routers/items.py` module में हैं। + +आपके पास इनके लिए *path operations* हैं: + +* `/items/` +* `/items/{item_id}` + +यह सब `app/routers/users.py` जैसी ही structure है। + +लेकिन हम थोड़े अधिक smart होना चाहते हैं और code को थोड़ा simplify करना चाहते हैं। + +हम जानते हैं कि इस module के सभी *path operations* में वही हैं: + +* Path `prefix`: `/items`. +* `tags`: (सिर्फ एक tag: `items`). +* अतिरिक्त `responses`. +* `dependencies`: उन सभी को वह `X-Token` dependency चाहिए जो हमने बनाई है। + +इसलिए, यह सब प्रत्येक *path operation* में जोड़ने के बजाय, हम इसे `APIRouter` में जोड़ सकते हैं। + +{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[5:10,16,21] title["app/routers/items.py"] *} + +क्योंकि प्रत्येक *path operation* का path `/` से शुरू होना चाहिए, जैसे: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +...prefix में अंत में `/` शामिल नहीं होना चाहिए। + +इसलिए, इस मामले में prefix `/items` है। + +हम `tags` की list और अतिरिक्त `responses` भी जोड़ सकते हैं जो इस router में शामिल सभी *path operations* पर लागू होंगे। + +और हम `dependencies` की list जोड़ सकते हैं जो router के सभी *path operations* में जोड़ी जाएगी और उन पर किए गए हर request के लिए execute/solve की जाएगी। + +/// tip | टिप + +ध्यान दें कि, [*path operation decorators* में dependencies](dependencies/dependencies-in-path-operation-decorators.md) की तरह ही, आपके *path operation function* को कोई value pass नहीं की जाएगी। + +/// + +अंतिम परिणाम यह है कि item paths अब ये हैं: + +* `/items/` +* `/items/{item_id}` + +...जैसा हमने चाहा था। + +* उन्हें tags की list से mark किया जाएगा जिसमें एक ही string `"items"` होगी। + * ये "tags" automatic interactive documentation systems (OpenAPI का उपयोग करते हुए) के लिए विशेष रूप से उपयोगी हैं। +* उन सभी में predefined `responses` शामिल होंगे। +* इन सभी *path operations* से पहले `dependencies` की list evaluate/execute की जाएगी। + * अगर आप किसी specific *path operation* में भी dependencies declare करते हैं, **तो वे भी execute होंगी**। + * router dependencies पहले execute होती हैं, फिर decorator में [`dependencies`](dependencies/dependencies-in-path-operation-decorators.md), और फिर normal parameter dependencies। + * आप [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md) भी जोड़ सकते हैं। + +/// tip | टिप + +`APIRouter` में `dependencies` होने का उपयोग, उदाहरण के लिए, *path operations* के पूरे group के लिए authentication require करने के लिए किया जा सकता है। भले ही dependencies उनमें से हर एक में individually न जोड़ी गई हों। + +/// + +/// tip | टिप + +`prefix`, `tags`, `responses`, और `dependencies` parameters (कई अन्य मामलों की तरह) **FastAPI** की एक feature हैं जो आपको code duplication से बचने में मदद करती है। + +/// + +### dependencies import करें { #import-the-dependencies } + +यह code `app.routers.items` module, file `app/routers/items.py` में रहता है। + +और हमें dependency function `app.dependencies` module, file `app/dependencies.py` से लेनी है। + +इसलिए हम dependencies के लिए `..` के साथ relative import का उपयोग करते हैं: + +{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[3] title["app/routers/items.py"] *} + +#### Relative imports कैसे काम करते हैं { #how-relative-imports-work } + +/// tip | टिप + +अगर आप पूरी तरह जानते हैं कि imports कैसे काम करते हैं, तो नीचे वाले अगले section पर जाएँ। + +/// + +एक single dot `.`, जैसे: + +```Python +from .dependencies import get_token_header +``` + +का मतलब होगा: + +* उसी package से शुरू करना जिसमें यह module (file `app/routers/items.py`) रहता है (directory `app/routers/`)... +* module `dependencies` ढूँढना (`app/routers/dependencies.py` पर एक काल्पनिक file)... +* और उससे, function `get_token_header` import करना। + +लेकिन वह file मौजूद नहीं है, हमारी dependencies `app/dependencies.py` पर एक file में हैं। + +याद रखें कि हमारी app/file structure कैसी दिखती है: + + + +--- + +दो dots `..`, जैसे: + +```Python +from ..dependencies import get_token_header +``` + +का मतलब है: + +* उसी package से शुरू करना जिसमें यह module (file `app/routers/items.py`) रहता है (directory `app/routers/`)... +* parent package (directory `app/`) पर जाना... +* और वहाँ, module `dependencies` ढूँढना (file `app/dependencies.py` पर)... +* और उससे, function `get_token_header` import करना। + +यह सही तरीके से काम करता है! 🎉 + +--- + +उसी तरह, अगर हमने तीन dots `...` का उपयोग किया होता, जैसे: + +```Python +from ...dependencies import get_token_header +``` + +तो उसका मतलब होगा: + +* उसी package से शुरू करना जिसमें यह module (file `app/routers/items.py`) रहता है (directory `app/routers/`)... +* parent package (directory `app/`) पर जाना... +* फिर उस package के parent पर जाना (कोई parent package नहीं है, `app` top level है 😱)... +* और वहाँ, module `dependencies` ढूँढना (file `app/dependencies.py` पर)... +* और उससे, function `get_token_header` import करना। + +यह `app/` के ऊपर किसी package को refer करेगा, जिसकी अपनी file `__init__.py` आदि होगी। लेकिन हमारे पास वह नहीं है। इसलिए, हमारे उदाहरण में इससे error आएगा। 🚨 + +लेकिन अब आप जानते हैं कि यह कैसे काम करता है, इसलिए आप अपने apps में relative imports का उपयोग कर सकते हैं, चाहे वे कितने भी complex हों। 🤓 + +### कुछ custom `tags`, `responses`, और `dependencies` जोड़ें { #add-some-custom-tags-responses-and-dependencies } + +हम प्रत्येक *path operation* में prefix `/items` या `tags=["items"]` नहीं जोड़ रहे हैं क्योंकि हमने उन्हें `APIRouter` में जोड़ दिया है। + +लेकिन हम अभी भी _अधिक_ `tags` जोड़ सकते हैं जो किसी specific *path operation* पर लागू होंगे, और उस *path operation* के लिए specific कुछ अतिरिक्त `responses` भी: + +{* ../../docs_src/bigger_applications/app_an_py310/routers/items.py hl[30:31] title["app/routers/items.py"] *} + +/// tip | टिप + +इस आखिरी path operation में tags का combination होगा: `["items", "custom"]`। + +और documentation में इसके दोनों responses भी होंगे, एक `404` के लिए और एक `403` के लिए। + +/// + +## मुख्य `FastAPI` { #the-main-fastapi } + +अब, `app/main.py` पर module देखें। + +यहीं आप `FastAPI` class import और use करते हैं। + +यह आपके application की main file होगी जो सब कुछ एक साथ जोड़ती है। + +और क्योंकि आपका अधिकतर logic अब अपने-अपने specific module में रहेगा, main file काफी सरल होगी। + +### `FastAPI` import करें { #import-fastapi } + +आप सामान्य रूप से `FastAPI` class import और create करते हैं। + +और हम [global dependencies](dependencies/global-dependencies.md) भी declare कर सकते हैं जिन्हें प्रत्येक `APIRouter` के लिए dependencies के साथ combine किया जाएगा: + +{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[1,3,7] title["app/main.py"] *} + +### `APIRouter` import करें { #import-the-apirouter } + +अब हम उन अन्य submodules को import करते हैं जिनके पास `APIRouter`s हैं: + +{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[4:5] title["app/main.py"] *} + +क्योंकि files `app/routers/users.py` और `app/routers/items.py` ऐसे submodules हैं जो उसी Python package `app` का हिस्सा हैं, हम "relative imports" का उपयोग करके उन्हें import करने के लिए single dot `.` का उपयोग कर सकते हैं। + +### importing कैसे काम करता है { #how-the-importing-works } + +section: + +```Python +from .routers import items, users +``` + +का मतलब है: + +* उसी package से शुरू करना जिसमें यह module (file `app/main.py`) रहता है (directory `app/`)... +* subpackage `routers` ढूँढना (directory `app/routers/` पर)... +* और उससे, submodule `items` (file `app/routers/items.py` पर) और `users` (file `app/routers/users.py` पर) import करना... + +module `items` में एक variable `router` (`items.router`) होगा। यह वही है जो हमने file `app/routers/items.py` में बनाया था, यह एक `APIRouter` object है। + +और फिर हम module `users` के लिए भी वही करते हैं। + +हम उन्हें इस तरह भी import कर सकते थे: + +```Python +from app.routers import items, users +``` + +/// note | नोट + +पहला version एक "relative import" है: + +```Python +from .routers import items, users +``` + +दूसरा version एक "absolute import" है: + +```Python +from app.routers import items, users +``` + +Python Packages और Modules के बारे में अधिक जानने के लिए, [Modules के बारे में official Python documentation](https://docs.python.org/3/tutorial/modules.html) पढ़ें। + +/// + +### नामों के collisions से बचें { #avoid-name-collisions } + +हम submodule `items` को directly import कर रहे हैं, केवल उसके variable `router` को import करने के बजाय। + +ऐसा इसलिए है क्योंकि हमारे पास submodule `users` में भी `router` नाम का एक और variable है। + +अगर हमने एक के बाद एक import किया होता, जैसे: + +```Python +from .routers.items import router +from .routers.users import router +``` + +तो `users` का `router`, `items` वाले को overwrite कर देता और हम उन्हें एक ही समय में use नहीं कर पाते। + +इसलिए, उन्हें एक ही file में दोनों को use करने में सक्षम होने के लिए, हम submodules को directly import करते हैं: + +{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[5] title["app/main.py"] *} + +### `users` और `items` के लिए `APIRouter`s include करें { #include-the-apirouters-for-users-and-items } + +अब, submodules `users` और `items` से `router`s include करें: + +{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *} + +/// note | नोट + +`users.router` file `app/routers/users.py` के अंदर मौजूद `APIRouter` को contain करता है। + +और `items.router` file `app/routers/items.py` के अंदर मौजूद `APIRouter` को contain करता है। + +/// + +`app.include_router()` के साथ हम प्रत्येक `APIRouter` को main `FastAPI` application में जोड़ सकते हैं। + +यह उस router के सभी routes को उसका हिस्सा बनाकर include करेगा। + +/// note | तकनीकी विवरण + +FastAPI मूल `APIRouter` और उसके `APIRoute`s को active रखता है जब router main application में include किया जाता है। + +इसका मतलब है कि custom `APIRouter` और `APIRoute` subclasses router include होने के बाद भी participate कर सकते हैं। + +/// + +/// tip | टिप + +routers include करते समय आपको performance के बारे में चिंता करने की ज़रूरत नहीं है। + +इसे lightweight होने और हर request में overhead जोड़ने से बचने के लिए design किया गया है। + +इसलिए यह performance को affect नहीं करेगा। ⚡ + +/// + +### custom `prefix`, `tags`, `responses`, और `dependencies` के साथ `APIRouter` include करें { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies } + +अब, कल्पना करें कि आपकी organization ने आपको `app/internal/admin.py` file दी है। + +इसमें कुछ admin *path operations* वाला `APIRouter` है जिसे आपकी organization कई projects के बीच share करती है। + +इस उदाहरण के लिए यह बहुत सरल होगा। लेकिन मान लीजिए कि क्योंकि यह organization में अन्य projects के साथ shared है, हम इसे modify नहीं कर सकते और `prefix`, `dependencies`, `tags`, आदि directly `APIRouter` में नहीं जोड़ सकते: + +{* ../../docs_src/bigger_applications/app_an_py310/internal/admin.py hl[3] title["app/internal/admin.py"] *} + +लेकिन हम फिर भी `APIRouter` include करते समय एक custom `prefix` set करना चाहते हैं ताकि इसके सभी *path operations* `/admin` से शुरू हों, हम इसे इस project के लिए पहले से मौजूद `dependencies` के साथ secure करना चाहते हैं, और हम `tags` और `responses` include करना चाहते हैं। + +हम original `APIRouter` को modify किए बिना यह सब declare कर सकते हैं, उन parameters को `app.include_router()` में pass करके: + +{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[14:17] title["app/main.py"] *} + +इस तरह, original `APIRouter` unmodified रहेगा, इसलिए हम वही `app/internal/admin.py` file organization में अन्य projects के साथ अब भी share कर सकते हैं। + +परिणाम यह है कि हमारी app में, `admin` module से प्रत्येक *path operation* में होगा: + +* prefix `/admin`. +* tag `admin`. +* dependency `get_token_header`. +* response `418`. 🍵 + +लेकिन यह केवल हमारी app में उस `APIRouter` को affect करेगा, उसे use करने वाले किसी अन्य code को नहीं। + +इसलिए, उदाहरण के लिए, अन्य projects उसी `APIRouter` को किसी अलग authentication method के साथ use कर सकते हैं। + +### एक *path operation* include करें { #include-a-path-operation } + +हम सीधे `FastAPI` app में भी *path operations* जोड़ सकते हैं। + +यहाँ हम ऐसा करते हैं... बस यह दिखाने के लिए कि हम कर सकते हैं 🤷: + +{* ../../docs_src/bigger_applications/app_an_py310/main.py hl[21:23] title["app/main.py"] *} + +और यह `app.include_router()` के साथ जोड़े गए सभी अन्य *path operations* के साथ सही तरीके से काम करेगा। + +/// note | बहुत तकनीकी विवरण + +**नोट**: यह बहुत technical detail है जिसे आप शायद **बस skip** कर सकते हैं। + +--- + +`APIRouter`s "mounted" नहीं होते, वे बाकी application से isolated नहीं होते। + +ऐसा इसलिए है क्योंकि हम उनके *path operations* को OpenAPI schema और user interfaces में include करना चाहते हैं। + +FastAPI original routers और path operations को active रखता है, और requests handle करते समय और OpenAPI generate करते समय router prefixes, dependencies, tags, responses, और अन्य metadata को combine करता है। + +/// + +## `pyproject.toml` में `entrypoint` configure करें { #configure-the-entrypoint-in-pyproject-toml } + +क्योंकि आपका FastAPI `app` object `app/main.py` में रहता है, आप अपने `pyproject.toml` file में `entrypoint` को इस तरह configure कर सकते हैं: + +```toml +[tool.fastapi] +entrypoint = "app.main:app" +``` + +यह इस तरह import करने के बराबर है: + +```python +from app.main import app +``` + +इस तरह `fastapi` command जान जाएगा कि आपकी app कहाँ मिलेगी। + +/// Note | नोट + +आप command को path भी pass कर सकते हैं, जैसे: + +```console +$ fastapi dev app/main.py +``` + +लेकिन हर बार `fastapi` command call करते समय आपको सही path pass करना याद रखना होगा। + +इसके अलावा, अन्य tools शायद इसे ढूँढ न पाएँ, उदाहरण के लिए [VS Code Extension](../editor-support.md) या [FastAPI Cloud](https://fastapicloud.com), इसलिए `pyproject.toml` में `entrypoint` का उपयोग करने की सलाह दी जाती है। + +/// + +## automatic API docs जाँचें { #check-the-automatic-api-docs } + +अब, अपनी app चलाएँ: + +
+ +```console +$ fastapi dev + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +और docs को [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) पर खोलें। + +आप automatic API docs देखेंगे, जिसमें सभी submodules से paths शामिल होंगे, सही paths (और prefixes) और सही tags का उपयोग करते हुए: + + + +## अलग-अलग `prefix` के साथ उसी router को multiple times include करें { #include-the-same-router-multiple-times-with-different-prefix } + +आप अलग-अलग prefixes का उपयोग करके *same* router के साथ `.include_router()` को multiple times भी use कर सकते हैं। + +यह उपयोगी हो सकता है, उदाहरण के लिए, उसी API को अलग-अलग prefixes के तहत expose करने के लिए, जैसे `/api/v1` और `/api/latest`। + +यह एक advanced usage है जिसकी आपको शायद सच में ज़रूरत न हो, लेकिन अगर हो तो यह मौजूद है। + +## एक `APIRouter` को दूसरे में include करें { #include-an-apirouter-in-another } + +जिस तरह आप `FastAPI` application में `APIRouter` include कर सकते हैं, उसी तरह आप एक `APIRouter` को दूसरे `APIRouter` में include कर सकते हैं: + +```Python +router.include_router(other_router) +``` + +आप यह `FastAPI` app में `router` include करने से पहले या बाद में कर सकते हैं। FastAPI फिर भी `other_router` से *path operations* को routing और OpenAPI में include करेगा। + +बाद में routers में जोड़े गए *path operations* पर भी यही लागू होता है। वे पहले वाली inclusion के माध्यम से भी visible होंगे। + +/// warning | तकनीकी विवरण + +router include करने के बाद `router.routes` को directly mutate करने से बचें। FastAPI router inclusion को live मानता है, इसलिए original router और उसके routes routing और OpenAPI generation का हिस्सा बने रहते हैं। + +routes और routers जोड़ने के लिए documented APIs जैसे path operation decorators और `.include_router()` का उपयोग करें। + +`router.routes` को एक lower-level route tree की तरह treat करें जिसमें route definitions और included routers हो सकते हैं, और इस पर final path operations की flat list की तरह rely करने से बचें। + +/// diff --git a/docs/hi/docs/tutorial/body-fields.md b/docs/hi/docs/tutorial/body-fields.md new file mode 100644 index 000000000..22f5d38fd --- /dev/null +++ b/docs/hi/docs/tutorial/body-fields.md @@ -0,0 +1,61 @@ +# Body - Fields { #body-fields } + +जिस तरह आप *path operation function* के parameters में `Query`, `Path` और `Body` के साथ अतिरिक्त validation और metadata घोषित कर सकते हैं, उसी तरह आप Pydantic के `Field` का उपयोग करके Pydantic models के अंदर validation और metadata घोषित कर सकते हैं। + +## `Field` import करें { #import-field } + +सबसे पहले, आपको इसे import करना होगा: + +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} + + +/// warning | चेतावनी + +ध्यान दें कि `Field` को सीधे `pydantic` से import किया जाता है, `fastapi` से नहीं, जैसे बाकी सभी (`Query`, `Path`, `Body`, आदि) किए जाते हैं। + +/// + +## model attributes घोषित करें { #declare-model-attributes } + +फिर आप model attributes के साथ `Field` का उपयोग कर सकते हैं: + +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} + +`Field` उसी तरह काम करता है जैसे `Query`, `Path` और `Body`, इसमें वही सभी parameters आदि होते हैं। + +/// note | तकनीकी विवरण + +वास्तव में, `Query`, `Path` और अन्य जिन्हें आप आगे देखेंगे, एक सामान्य `Param` class के subclasses के objects बनाते हैं, जो स्वयं Pydantic की `FieldInfo` class का subclass है। + +और Pydantic का `Field` भी `FieldInfo` का एक instance लौटाता है। + +`Body` भी सीधे `FieldInfo` के subclass के objects लौटाता है। और कुछ अन्य भी हैं जिन्हें आप बाद में देखेंगे, जो `Body` class के subclasses हैं। + +याद रखें कि जब आप `fastapi` से `Query`, `Path` और अन्य import करते हैं, तो वे वास्तव में functions होते हैं जो विशेष classes लौटाते हैं। + +/// + +/// tip | सुझाव + +ध्यान दें कि type, default value और `Field` वाले हर model के attribute की संरचना *path operation function* के parameter जैसी ही होती है, बस `Path`, `Query` और `Body` की जगह `Field` होता है। + +/// + +## अतिरिक्त जानकारी जोड़ें { #add-extra-information } + +आप `Field`, `Query`, `Body` आदि में अतिरिक्त जानकारी घोषित कर सकते हैं। और यह जनरेट किए गए JSON Schema में शामिल होगी। + +आप docs में आगे examples घोषित करना सीखते समय अतिरिक्त जानकारी जोड़ने के बारे में और जानेंगे। + +/// warning | चेतावनी + +`Field` को दिए गए अतिरिक्त keys आपके application के परिणामी OpenAPI schema में भी मौजूद होंगे। +क्योंकि ये keys जरूरी नहीं कि OpenAPI specification का हिस्सा हों, इसलिए कुछ OpenAPI tools, उदाहरण के लिए [OpenAPI validator](https://validator.swagger.io/), आपके जनरेट किए गए schema के साथ काम नहीं कर सकते। + +/// + +## Recap { #recap } + +आप model attributes के लिए अतिरिक्त validations और metadata घोषित करने के लिए Pydantic के `Field` का उपयोग कर सकते हैं। + +आप अतिरिक्त JSON Schema metadata पास करने के लिए extra keyword arguments का भी उपयोग कर सकते हैं। diff --git a/docs/hi/docs/tutorial/body-multiple-params.md b/docs/hi/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..0d095ddf3 --- /dev/null +++ b/docs/hi/docs/tutorial/body-multiple-params.md @@ -0,0 +1,169 @@ +# Body - कई Parameters { #body-multiple-parameters } + +अब जबकि हमने देख लिया है कि `Path` और `Query` का उपयोग कैसे करना है, आइए request body declarations के और उन्नत उपयोग देखें। + +## `Path`, `Query` और body parameters को मिलाएँ { #mix-path-query-and-body-parameters } + +सबसे पहले, बेशक, आप `Path`, `Query` और request body parameter declarations को स्वतंत्र रूप से मिला सकते हैं और **FastAPI** जान जाएगा कि क्या करना है। + +और आप body parameters को optional भी declare कर सकते हैं, default को `None` पर सेट करके: + +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} + +/// note | नोट + +ध्यान दें कि, इस मामले में, body से लिया जाने वाला `item` optional है। क्योंकि इसका default value `None` है। + +/// + +## कई body parameters { #multiple-body-parameters } + +पिछले उदाहरण में, *path operations* एक JSON body की अपेक्षा करेंगे जिसमें `Item` के attributes हों, जैसे: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +लेकिन आप कई body parameters भी declare कर सकते हैं, उदाहरण के लिए `item` और `user`: + +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} + + +इस मामले में, **FastAPI** ध्यान देगा कि function में एक से अधिक body parameter हैं (दो parameters हैं जो Pydantic models हैं)। + +तो, फिर यह parameter names को body में keys (field names) के रूप में उपयोग करेगा, और ऐसी body की अपेक्षा करेगा: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note | नोट + +ध्यान दें कि भले ही `item` को पहले की तरह ही declare किया गया था, अब उससे अपेक्षा की जाती है कि वह body के अंदर key `item` के साथ हो। + +/// + +**FastAPI** request से automatic conversion करेगा, ताकि parameter `item` को उसकी विशिष्ट content मिले और `user` के लिए भी यही हो। + +यह compound data का validation करेगा, और इसे OpenAPI schema और automatic docs के लिए उसी तरह document करेगा। + +## body में एकल values { #singular-values-in-body } + +जिस तरह query और path parameters के लिए extra data define करने हेतु `Query` और `Path` हैं, **FastAPI** एक समान `Body` प्रदान करता है। + +उदाहरण के लिए, पिछले model को extend करते हुए, आप तय कर सकते हैं कि आप उसी body में `item` और `user` के अलावा एक और key `importance` रखना चाहते हैं। + +यदि आप इसे जैसे है वैसे declare करते हैं, क्योंकि यह एक single value है, **FastAPI** मान लेगा कि यह एक query parameter है। + +लेकिन आप **FastAPI** को `Body` का उपयोग करके इसे एक और body key के रूप में treat करने का निर्देश दे सकते हैं: + +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} + + +इस मामले में, **FastAPI** ऐसी body की अपेक्षा करेगा: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +फिर से, यह data types को convert करेगा, validate करेगा, document करेगा, आदि। + +## कई body params और query { #multiple-body-params-and-query } + +बेशक, आप जब भी ज़रूरत हो, किसी भी body parameters के अतिरिक्त, extra query parameters भी declare कर सकते हैं। + +क्योंकि default रूप से, single values को query parameters के रूप में interpret किया जाता है, आपको स्पष्ट रूप से `Query` जोड़ने की ज़रूरत नहीं है, आप बस ऐसा कर सकते हैं: + +```Python +q: str | None = None +``` + +उदाहरण के लिए: + +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *} + + +/// note | नोट + +`Body` में भी वही सभी extra validation और metadata parameters हैं जो `Query`, `Path` और अन्य में हैं जिन्हें आप बाद में देखेंगे। + +/// + +## एक single body parameter को embed करें { #embed-a-single-body-parameter } + +मान लीजिए आपके पास Pydantic model `Item` से केवल एक single `item` body parameter है। + +default रूप से, **FastAPI** फिर सीधे उसकी body की अपेक्षा करेगा। + +लेकिन यदि आप चाहते हैं कि यह key `item` के साथ JSON की अपेक्षा करे और उसके अंदर model contents हों, जैसा कि यह तब करता है जब आप extra body parameters declare करते हैं, तो आप special `Body` parameter `embed` का उपयोग कर सकते हैं: + +```Python +item: Annotated[Item, Body(embed=True)] +``` + +जैसे कि: + +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} + + +इस मामले में **FastAPI** ऐसी body की अपेक्षा करेगा: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +इसके बजाय: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Recap { #recap } + +आप अपनी *path operation function* में कई body parameters जोड़ सकते हैं, भले ही एक request में केवल एक ही body हो सकती है। + +लेकिन **FastAPI** इसे handle करेगा, आपको आपके function में सही data देगा, और *path operation* में सही schema को validate और document करेगा। + +आप single values को body के हिस्से के रूप में receive करने के लिए भी declare कर सकते हैं। + +और आप **FastAPI** को body को एक key में embed करने का निर्देश दे सकते हैं, भले ही केवल एक single parameter declare किया गया हो। diff --git a/docs/hi/docs/tutorial/body-nested-models.md b/docs/hi/docs/tutorial/body-nested-models.md new file mode 100644 index 000000000..04ac55bfd --- /dev/null +++ b/docs/hi/docs/tutorial/body-nested-models.md @@ -0,0 +1,221 @@ +# Body - Nested Models { #body-nested-models } + +**FastAPI** के साथ, आप arbitrarily deeply nested models को define, validate, document, और use कर सकते हैं (Pydantic की बदौलत)। + +## List fields { #list-fields } + +आप किसी attribute को subtype के रूप में define कर सकते हैं। उदाहरण के लिए, एक Python `list`: + +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} + +यह `tags` को एक list बना देगा, हालांकि यह list के elements का type declare नहीं करता। + +## Type parameter के साथ List fields { #list-fields-with-type-parameter } + +लेकिन Python में internal types, या "type parameters" के साथ lists declare करने का एक खास तरीका है: + +### Type parameter के साथ `list` declare करें { #declare-a-list-with-a-type-parameter } + +ऐसे types declare करने के लिए जिनमें type parameters (internal types) होते हैं, जैसे `list`, `dict`, `tuple`, +internal type(s) को square brackets: `[` और `]` का उपयोग करके "type parameters" के रूप में pass करें + +```Python +my_list: list[str] +``` + +Type declarations के लिए यह सब standard Python syntax है। + +Internal types वाले model attributes के लिए भी वही standard syntax उपयोग करें। + +तो, हमारे उदाहरण में, हम `tags` को खास तौर पर "strings की list" बना सकते हैं: + +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} + +## Set types { #set-types } + +लेकिन फिर हम इस पर सोचते हैं, और समझते हैं कि tags repeat नहीं होने चाहिए, वे शायद unique strings होंगे। + +और Python में unique items के sets के लिए एक खास data type है, `set`। + +फिर हम `tags` को strings के set के रूप में declare कर सकते हैं: + +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} + +इसके साथ, भले ही आपको duplicate data वाला request मिले, वह unique items के set में convert हो जाएगा। + +और जब भी आप उस data को output करेंगे, भले ही source में duplicates हों, वह unique items के set के रूप में output होगा। + +और इसे उसी अनुसार annotate / document भी किया जाएगा। + +## Nested Models { #nested-models } + +Pydantic model के हर attribute का एक type होता है। + +लेकिन वह type खुद भी कोई दूसरा Pydantic model हो सकता है। + +इसलिए, आप खास attribute names, types और validations के साथ deeply nested JSON "objects" declare कर सकते हैं। + +यह सब, मनचाही गहराई तक nested हो सकता है। + +### Submodel define करें { #define-a-submodel } + +उदाहरण के लिए, हम एक `Image` model define कर सकते हैं: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} + +### Submodel को type के रूप में उपयोग करें { #use-the-submodel-as-a-type } + +और फिर हम इसे किसी attribute के type के रूप में उपयोग कर सकते हैं: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} + +इसका मतलब होगा कि **FastAPI** कुछ इस तरह के body की अपेक्षा करेगा: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +फिर से, सिर्फ वह declaration करने से, **FastAPI** के साथ आपको मिलता है: + +* Editor support (completion, आदि), nested models के लिए भी +* Data conversion +* Data validation +* Automatic documentation + +## Special types और validation { #special-types-and-validation } + +`str`, `int`, `float`, आदि जैसे सामान्य singular types के अलावा, आप अधिक complex singular types उपयोग कर सकते हैं जो `str` से inherit करते हैं। + +आपके पास मौजूद सभी options देखने के लिए, [Pydantic का Type Overview](https://docs.pydantic.dev/latest/concepts/types/) देखें। अगले chapter में आपको कुछ उदाहरण दिखेंगे। + +उदाहरण के लिए, जैसा कि `Image` model में हमारे पास एक `url` field है, हम इसे `str` के बजाय Pydantic के `HttpUrl` का instance declare कर सकते हैं: + +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} + +String को valid URL होने के लिए check किया जाएगा, और JSON Schema / OpenAPI में उसी तरह document किया जाएगा। + +## Submodels की lists वाले attributes { #attributes-with-lists-of-submodels } + +आप Pydantic models को `list`, `set`, आदि के subtypes के रूप में भी उपयोग कर सकते हैं: + +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} + +यह इस तरह के JSON body की अपेक्षा करेगा (convert, validate, document, आदि): + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +/// note | नोट + +ध्यान दें कि `images` key में अब image objects की एक list है। + +/// + +## Deeply nested models { #deeply-nested-models } + +आप arbitrarily deeply nested models define कर सकते हैं: + +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} + +/// note | नोट + +ध्यान दें कि `Offer` में `Item`s की एक list है, जिनमें आगे `Image`s की एक optional list है + +/// + +## Pure lists के bodies { #bodies-of-pure-lists } + +अगर जिस JSON body की आप अपेक्षा करते हैं उसका top level value एक JSON `array` (एक Python `list`) है, तो आप function के parameter में type declare कर सकते हैं, बिल्कुल Pydantic models की तरह: + +```Python +images: list[Image] +``` + +जैसे कि: + +{* ../../docs_src/body_nested_models/tutorial008_py310.py hl[13] *} + +## हर जगह editor support { #editor-support-everywhere } + +और आपको हर जगह editor support मिलता है। + +Lists के अंदर के items के लिए भी: + + + +अगर आप Pydantic models के बजाय सीधे `dict` के साथ काम कर रहे होते, तो आपको इस तरह का editor support नहीं मिल सकता था। + +लेकिन आपको उनकी चिंता भी करने की ज़रूरत नहीं है, आने वाले dicts अपने आप convert हो जाते हैं और आपका output भी अपने आप JSON में convert हो जाता है। + +## Arbitrary `dict`s के bodies { #bodies-of-arbitrary-dicts } + +आप body को एक `dict` के रूप में भी declare कर सकते हैं, जिसकी keys किसी type की हों और values किसी दूसरे type की। + +इस तरह, आपको पहले से यह जानने की ज़रूरत नहीं होती कि valid field/attribute names क्या हैं (जैसा कि Pydantic models के साथ होता)। + +यह तब उपयोगी होगा जब आप ऐसी keys receive करना चाहते हैं जिन्हें आप पहले से नहीं जानते। + +--- + +एक और उपयोगी case वह है जब आप किसी दूसरे type (जैसे, `int`) की keys रखना चाहते हैं। + +यही हम यहाँ देखने जा रहे हैं। + +इस case में, आप कोई भी `dict` accept करेंगे, जब तक कि उसमें `float` values वाली `int` keys हों: + +{* ../../docs_src/body_nested_models/tutorial009_py310.py hl[7] *} + +/// tip | टिप + +ध्यान रखें कि JSON केवल `str` को keys के रूप में support करता है। + +लेकिन Pydantic में automatic data conversion है। + +इसका मतलब है कि, भले ही आपके API clients केवल strings को keys के रूप में भेज सकते हैं, जब तक उन strings में pure integers हैं, Pydantic उन्हें convert और validate कर देगा। + +और `weights` के रूप में आपको जो `dict` receive होगा, उसमें वास्तव में `int` keys और `float` values होंगी। + +/// + +## Recap { #recap } + +**FastAPI** के साथ आपके पास Pydantic models द्वारा दी गई अधिकतम flexibility होती है, जबकि आपका code simple, short और elegant बना रहता है। + +लेकिन सभी benefits के साथ: + +* Editor support (हर जगह completion!) +* Data conversion (a.k.a. parsing / serialization) +* Data validation +* Schema documentation +* Automatic docs diff --git a/docs/hi/docs/tutorial/body-updates.md b/docs/hi/docs/tutorial/body-updates.md new file mode 100644 index 000000000..cab762e47 --- /dev/null +++ b/docs/hi/docs/tutorial/body-updates.md @@ -0,0 +1,100 @@ +# Body - अपडेट्स { #body-updates } + +## `PUT` के साथ बदलकर अपडेट करना { #update-replacing-with-put } + +किसी item को अपडेट करने के लिए आप [HTTP `PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) operation का उपयोग कर सकते हैं। + +आप input data को ऐसे data में बदलने के लिए `jsonable_encoder` का उपयोग कर सकते हैं जिसे JSON के रूप में संग्रहीत किया जा सके (जैसे NoSQL database के साथ)। उदाहरण के लिए, `datetime` को `str` में बदलना। + +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} + +`PUT` का उपयोग ऐसा data प्राप्त करने के लिए किया जाता है जो मौजूदा data को बदल दे। + +### बदलने के बारे में चेतावनी { #warning-about-replacing } + +इसका मतलब है कि अगर आप item `bar` को `PUT` का उपयोग करके ऐसे body के साथ अपडेट करना चाहते हैं जिसमें यह हो: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +क्योंकि इसमें पहले से संग्रहीत attribute `"tax": 20.2` शामिल नहीं है, input model `"tax": 10.5` की default value लेगा। + +और data उस "नए" `tax` `10.5` के साथ सहेजा जाएगा। + +## `PATCH` के साथ आंशिक अपडेट्स { #partial-updates-with-patch } + +आप data को *आंशिक रूप से* अपडेट करने के लिए [HTTP `PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) operation का भी उपयोग कर सकते हैं। + +इसका मतलब है कि आप केवल वही data भेज सकते हैं जिसे आप अपडेट करना चाहते हैं, बाकी को वैसा ही छोड़ते हुए। + +/// note | नोट + +`PATCH`, `PUT` की तुलना में कम सामान्य रूप से उपयोग और जाना जाता है। + +और कई teams आंशिक अपडेट्स के लिए भी केवल `PUT` का उपयोग करती हैं। + +आप इन्हें जैसे चाहें वैसे उपयोग करने के लिए **स्वतंत्र** हैं, **FastAPI** कोई प्रतिबंध नहीं लगाता। + +लेकिन यह गाइड आपको मोटे तौर पर दिखाती है कि इन्हें कैसे उपयोग करने का इरादा है। + +/// + +### Pydantic के `exclude_unset` parameter का उपयोग करना { #using-pydantics-exclude-unset-parameter } + +अगर आप आंशिक अपडेट्स प्राप्त करना चाहते हैं, तो Pydantic के model के `.model_dump()` में parameter `exclude_unset` का उपयोग करना बहुत उपयोगी है। + +जैसे `item.model_dump(exclude_unset=True)`। + +इससे केवल उस data के साथ एक `dict` बनेगा जो `item` model बनाते समय सेट किया गया था, default values को छोड़कर। + +फिर आप इसका उपयोग केवल उस data के साथ एक `dict` बनाने के लिए कर सकते हैं जो सेट किया गया था (request में भेजा गया), default values को छोड़ते हुए: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} + +### Pydantic के `update` parameter का उपयोग करना { #using-pydantics-update-parameter } + +अब, आप `.model_copy()` का उपयोग करके मौजूदा model की एक copy बना सकते हैं, और अपडेट करने के लिए data वाले `dict` के साथ `update` parameter पास कर सकते हैं। + +जैसे `stored_item_model.model_copy(update=update_data)`: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} + +### आंशिक अपडेट्स Recap { #partial-updates-recap } + +संक्षेप में, आंशिक अपडेट्स लागू करने के लिए आप: + +* (वैकल्पिक रूप से) `PUT` के बजाय `PATCH` का उपयोग करें। +* संग्रहीत data प्राप्त करें। +* उस data को Pydantic model में रखें। +* input model से default values के बिना एक `dict` बनाएँ (`exclude_unset` का उपयोग करके)। + * इस तरह आप केवल उन values को अपडेट कर सकते हैं जिन्हें वास्तव में user ने सेट किया है, बजाय इसके कि आपके model में पहले से संग्रहीत values को default values से override कर दें। +* संग्रहीत model की एक copy बनाएँ, और प्राप्त आंशिक अपडेट्स के साथ उसके attributes को अपडेट करें (`update` parameter का उपयोग करके)। +* copied model को ऐसी चीज़ में बदलें जिसे आपकी DB में संग्रहीत किया जा सके (उदाहरण के लिए, `jsonable_encoder` का उपयोग करके)। + * यह model की `.model_dump()` method को फिर से उपयोग करने जैसा है, लेकिन यह सुनिश्चित करता है (और बदलता है) कि values ऐसे data types में हों जिन्हें JSON में बदला जा सके, उदाहरण के लिए, `datetime` को `str` में। +* data को अपनी DB में सहेजें। +* अपडेट किया गया model लौटाएँ। + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} + +/// tip | टिप + +आप वास्तव में इसी तकनीक का उपयोग HTTP `PUT` operation के साथ भी कर सकते हैं। + +लेकिन यहाँ का उदाहरण `PATCH` का उपयोग करता है क्योंकि इसे इन्हीं use cases के लिए बनाया गया था। + +/// + +/// note | नोट + +ध्यान दें कि input model अभी भी validate किया जाता है। + +इसलिए, अगर आप ऐसे आंशिक अपडेट्स प्राप्त करना चाहते हैं जो सभी attributes को छोड़ सकते हैं, तो आपको ऐसा model चाहिए जिसमें सभी attributes optional के रूप में चिह्नित हों (default values या `None` के साथ)। + +**अपडेट्स** के लिए सभी optional values वाले models और **creation** के लिए required values वाले models में अंतर करने के लिए, आप [Extra Models](extra-models.md) में बताए गए विचारों का उपयोग कर सकते हैं। + +/// diff --git a/docs/hi/docs/tutorial/body.md b/docs/hi/docs/tutorial/body.md new file mode 100644 index 000000000..dfccf3726 --- /dev/null +++ b/docs/hi/docs/tutorial/body.md @@ -0,0 +1,166 @@ +# Request Body { #request-body } + +जब आपको किसी client (मान लें, एक browser) से अपनी API को data भेजना होता है, तो आप उसे **request body** के रूप में भेजते हैं। + +**request** body वह data है जो client आपकी API को भेजता है। **response** body वह data है जो आपकी API client को भेजती है। + +आपकी API को लगभग हमेशा **response** body भेजनी होती है। लेकिन clients को हर समय **request bodies** भेजने की ज़रूरत नहीं होती, कभी-कभी वे केवल एक path request करते हैं, शायद कुछ query parameters के साथ, लेकिन body नहीं भेजते। + +**request** body घोषित करने के लिए, आप [Pydantic](https://docs.pydantic.dev/) models का उनकी पूरी शक्ति और लाभों के साथ उपयोग करते हैं। + +/// note | नोट + +Data भेजने के लिए, आपको इनमें से किसी एक का उपयोग करना चाहिए: `POST` (सबसे आम), `PUT`, `DELETE` या `PATCH`. + +`GET` request के साथ body भेजने का व्यवहार specifications में undefined है, फिर भी, FastAPI इसे support करता है, केवल बहुत जटिल/चरम use cases के लिए। + +क्योंकि इसे discouraged किया जाता है, Swagger UI वाले interactive docs `GET` का उपयोग करते समय body के लिए documentation नहीं दिखाएँगे, और बीच में मौजूद proxies इसे support नहीं कर सकते। + +/// + +## Pydantic के `BaseModel` को import करें { #import-pydantics-basemodel } + +सबसे पहले, आपको `pydantic` से `BaseModel` import करना होगा: + +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} + +## अपना data model बनाएँ { #create-your-data-model } + +फिर आप अपने data model को एक class के रूप में घोषित करते हैं जो `BaseModel` से inherit करती है। + +सभी attributes के लिए standard Python types का उपयोग करें: + +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} + + +Query parameters घोषित करते समय की तरह, जब किसी model attribute का default value होता है, तो वह required नहीं होता। अन्यथा, वह required होता है। उसे केवल optional बनाने के लिए `None` का उपयोग करें। + +उदाहरण के लिए, ऊपर दिया गया यह model इस तरह का JSON "`object`" (या Python `dict`) घोषित करता है: + +```JSON +{ + "name": "Foo", + "description": "An optional description", + "price": 45.2, + "tax": 3.5 +} +``` + +...क्योंकि `description` और `tax` optional हैं (`None` के default value के साथ), यह JSON "`object`" भी valid होगा: + +```JSON +{ + "name": "Foo", + "price": 45.2 +} +``` + +## इसे एक parameter के रूप में घोषित करें { #declare-it-as-a-parameter } + +इसे अपनी *path operation* में जोड़ने के लिए, इसे उसी तरह घोषित करें जैसे आपने path और query parameters घोषित किए थे: + +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} + +...और इसके type को आपके बनाए हुए model, `Item`, के रूप में घोषित करें। + +## परिणाम { #results } + +सिर्फ उस Python type declaration के साथ, **FastAPI** यह करेगा: + +* request के body को JSON के रूप में पढ़ेगा। +* संबंधित types को convert करेगा (यदि ज़रूरत हो)। +* data को validate करेगा। + * यदि data invalid है, तो यह एक अच्छा और स्पष्ट error return करेगा, जो ठीक-ठीक बताएगा कि गलत data कहाँ और क्या था। +* आपको प्राप्त data parameter `item` में देगा। + * क्योंकि आपने इसे function में `Item` type का घोषित किया है, आपको इसके सभी attributes और उनके types के लिए पूरा editor support (completion, आदि) भी मिलेगा। +* आपके model के लिए [JSON Schema](https://json-schema.org) definitions generate करेगा, यदि आपके project के लिए उचित हो तो आप उन्हें कहीं और भी उपयोग कर सकते हैं। +* वे schemas generated OpenAPI schema का हिस्सा होंगे, और automatic documentation UIs द्वारा उपयोग किए जाएँगे। + +## स्वचालित docs { #automatic-docs } + +आपके models के JSON Schemas आपके OpenAPI generated schema का हिस्सा होंगे, और interactive API docs में दिखाए जाएँगे: + + + +और वे API docs में हर उस *path operation* के अंदर भी उपयोग किए जाएँगे जिसे उनकी ज़रूरत है: + + + +## Editor support { #editor-support } + +अपने editor में, अपने function के अंदर आपको हर जगह type hints और completion मिलेंगे (यदि आपको Pydantic model के बजाय `dict` मिला होता, तो ऐसा नहीं होता): + + + +आपको incorrect type operations के लिए error checks भी मिलते हैं: + + + +यह संयोग से नहीं है, पूरा framework इसी design के इर्द-गिर्द बनाया गया था। + +और किसी भी implementation से पहले, design phase में इसे पूरी तरह test किया गया था, ताकि सुनिश्चित किया जा सके कि यह सभी editors के साथ काम करेगा। + +इसे support करने के लिए Pydantic में भी कुछ बदलाव किए गए थे। + +पिछले screenshots [Visual Studio Code](https://code.visualstudio.com) के साथ लिए गए थे। + +लेकिन आपको [PyCharm](https://www.jetbrains.com/pycharm/) और अधिकांश अन्य Python editors के साथ भी वही editor support मिलेगा: + + + +/// tip | सुझाव + +यदि आप [PyCharm](https://www.jetbrains.com/pycharm/) को अपने editor के रूप में उपयोग करते हैं, तो आप [Pydantic PyCharm Plugin](https://github.com/koxudaxi/pydantic-pycharm-plugin/) का उपयोग कर सकते हैं। + +यह Pydantic models के लिए editor support को बेहतर बनाता है, इन चीज़ों के साथ: + +* auto-completion +* type checks +* refactoring +* searching +* inspections + +/// + +## model का उपयोग करें { #use-the-model } + +Function के अंदर, आप model object के सभी attributes को सीधे access कर सकते हैं: + +{* ../../docs_src/body/tutorial002_py310.py *} + +## Request body + path parameters { #request-body-path-parameters } + +आप path parameters और request body को एक ही समय में घोषित कर सकते हैं। + +**FastAPI** पहचानेगा कि वे function parameters जो path parameters से match करते हैं, उन्हें **path से लिया जाना चाहिए**, और वे function parameters जो Pydantic models के रूप में घोषित हैं, उन्हें **request body से लिया जाना चाहिए**। + +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} + + +## Request body + path + query parameters { #request-body-path-query-parameters } + +आप **body**, **path** और **query** parameters को भी एक ही समय में घोषित कर सकते हैं। + +**FastAPI** उनमें से प्रत्येक को पहचानेगा और data को सही जगह से लेगा। + +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} + +Function parameters को इस प्रकार पहचाना जाएगा: + +* यदि parameter **path** में भी घोषित है, तो उसे path parameter के रूप में उपयोग किया जाएगा। +* यदि parameter **singular type** का है (जैसे `int`, `float`, `str`, `bool`, आदि), तो उसे **query** parameter के रूप में interpret किया जाएगा। +* यदि parameter को **Pydantic model** के type का घोषित किया गया है, तो उसे request **body** के रूप में interpret किया जाएगा। + +/// note | नोट + +FastAPI जान जाएगा कि `q` का value required नहीं है क्योंकि उसका default value `= None` है। + +`str | None` का उपयोग FastAPI यह निर्धारित करने के लिए नहीं करता कि value required नहीं है, वह जान जाएगा कि यह required नहीं है क्योंकि इसका default value `= None` है। + +लेकिन type annotations जोड़ने से आपका editor आपको बेहतर support दे सकेगा और errors detect कर सकेगा। + +/// + +## Pydantic के बिना { #without-pydantic } + +यदि आप Pydantic models का उपयोग नहीं करना चाहते, तो आप **Body** parameters का भी उपयोग कर सकते हैं। [Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body) के docs देखें। diff --git a/docs/hi/docs/tutorial/cookie-param-models.md b/docs/hi/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..38ea681b2 --- /dev/null +++ b/docs/hi/docs/tutorial/cookie-param-models.md @@ -0,0 +1,76 @@ +# Cookie Parameter Models { #cookie-parameter-models } + +अगर आपके पास संबंधित **cookies** का एक समूह है, तो आप उन्हें declare करने के लिए एक **Pydantic model** बना सकते हैं। 🍪 + +यह आपको **model को फिर से उपयोग** करने की अनुमति देगा, **कई जगहों** पर, और साथ ही सभी parameters के लिए validations और metadata एक साथ declare करने की भी। 😎 + +/// note | नोट + +यह FastAPI version `0.115.0` से supported है। 🤓 + +/// + +/// tip | सुझाव + +यही तकनीक `Query`, `Cookie`, और `Header` पर लागू होती है। 😎 + +/// + +## Pydantic Model के साथ Cookies { #cookies-with-a-pydantic-model } + +जिन **cookie** parameters की आपको ज़रूरत है, उन्हें एक **Pydantic model** में declare करें, और फिर parameter को `Cookie` के रूप में declare करें: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI** request में प्राप्त **cookies** से **हर field** के लिए data **extract** करेगा और आपको वह Pydantic model देगा जिसे आपने define किया है। + +## Docs देखें { #check-the-docs } + +आप `/docs` पर docs UI में defined cookies देख सकते हैं: + +
+ +
+ +/// note | नोट + +ध्यान रखें कि, क्योंकि **browsers cookies को** विशेष तरीकों से और पर्दे के पीछे handle करते हैं, वे **JavaScript** को आसानी से उन्हें छूने की अनुमति **नहीं** देते। + +अगर आप `/docs` पर **API docs UI** पर जाते हैं, तो आप अपने *path operations* के लिए cookies की **documentation** देख पाएँगे। + +लेकिन भले ही आप **data भरें** और "Execute" पर क्लिक करें, क्योंकि docs UI **JavaScript** के साथ काम करता है, cookies नहीं भेजे जाएँगे, और आपको एक **error** message दिखाई देगा जैसे कि आपने कोई values लिखी ही न हों। + +/// + +## Extra Cookies को forbid करें { #forbid-extra-cookies } + +कुछ विशेष use cases में (शायद बहुत आम नहीं), आप उन cookies को **restrict** करना चाह सकते हैं जिन्हें आप प्राप्त करना चाहते हैं। + +आपकी API के पास अब अपनी खुद की cookie सहमति को control करने की शक्ति है। 🤪🍪 + +आप Pydantic के model configuration का उपयोग करके किसी भी `extra` fields को `forbid` कर सकते हैं: + +{* ../../docs_src/cookie_param_models/tutorial002_an_py310.py hl[10] *} + +अगर कोई client कुछ **extra cookies** भेजने की कोशिश करता है, तो उन्हें एक **error** response मिलेगा। + +बेचारे cookie banners, जो API द्वारा उसे reject किए जाने के लिए आपकी सहमति पाने में इतनी मेहनत करते हैं। 🍪 + +उदाहरण के लिए, अगर client `good-list-please` value के साथ एक `santa_tracker` cookie भेजने की कोशिश करता है, तो client को एक **error** response मिलेगा जो बताएगा कि `santa_tracker` cookie की अनुमति नहीं है: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## सारांश { #summary } + +आप **FastAPI** में **cookies** declare करने के लिए **Pydantic models** का उपयोग कर सकते हैं। 😎 diff --git a/docs/hi/docs/tutorial/cookie-params.md b/docs/hi/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..9f6265dd6 --- /dev/null +++ b/docs/hi/docs/tutorial/cookie-params.md @@ -0,0 +1,45 @@ +# Cookie Parameters { #cookie-parameters } + +आप `Cookie` parameters को उसी तरह define कर सकते हैं जैसे आप `Query` और `Path` parameters define करते हैं। + +## `Cookie` import करें { #import-cookie } + +पहले `Cookie` import करें: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} + +## `Cookie` parameters declare करें { #declare-cookie-parameters } + +फिर cookie parameters को `Path` और `Query` जैसी ही structure का उपयोग करके declare करें। + +आप default value के साथ-साथ सभी extra validation या annotation parameters भी define कर सकते हैं: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} + +/// note | तकनीकी विवरण + +`Cookie`, `Path` और `Query` की एक "sister" class है। यह भी उसी common `Param` class से inherit करती है। + +लेकिन याद रखें कि जब आप `fastapi` से `Query`, `Path`, `Cookie` और अन्य चीज़ें import करते हैं, तो वे वास्तव में ऐसे functions होते हैं जो special classes return करते हैं। + +/// + +/// note | नोट + +Cookies declare करने के लिए, आपको `Cookie` का उपयोग करना होगा, क्योंकि अन्यथा parameters को query parameters के रूप में interpret किया जाएगा। + +/// + +/// note | नोट + +ध्यान रखें कि, क्योंकि **browsers cookies को** विशेष तरीकों से और पर्दे के पीछे handle करते हैं, वे **JavaScript** को उन्हें आसानी से access करने की अनुमति **नहीं** देते। + +यदि आप `/docs` पर **API docs UI** में जाते हैं, तो आप अपनी *path operations* के लिए cookies की **documentation** देख पाएँगे। + +लेकिन भले ही आप **data भरें** और "Execute" पर click करें, क्योंकि docs UI **JavaScript** के साथ काम करता है, cookies भेजी नहीं जाएँगी, और आपको ऐसा **error** message दिखेगा जैसे आपने कोई values लिखी ही नहीं हों। + +/// + +## Recap { #recap } + +`Query` और `Path` जैसे ही common pattern का उपयोग करके, `Cookie` के साथ cookies declare करें। diff --git a/docs/hi/docs/tutorial/cors.md b/docs/hi/docs/tutorial/cors.md new file mode 100644 index 000000000..cd707990c --- /dev/null +++ b/docs/hi/docs/tutorial/cors.md @@ -0,0 +1,89 @@ +# CORS (Cross-Origin Resource Sharing) { #cors-cross-origin-resource-sharing } + +[CORS या "Cross-Origin Resource Sharing"](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) उन स्थितियों को संदर्भित करता है जब browser में चल रहे frontend में JavaScript code होता है जो backend से communicate करता है, और backend frontend से अलग "origin" में होता है। + +## Origin { #origin } + +एक origin protocol (`http`, `https`), domain (`myapp.com`, `localhost`, `localhost.tiangolo.com`), और port (`80`, `443`, `8080`) का combination होता है। + +तो, ये सभी अलग-अलग origins हैं: + +* `http://localhost` +* `https://localhost` +* `http://localhost:8080` + +भले ही वे सभी `localhost` में हों, वे अलग-अलग protocols या ports का उपयोग करते हैं, इसलिए वे अलग-अलग "origins" हैं। + +## Steps { #steps } + +तो, मान लें कि आपके browser में `http://localhost:8080` पर एक frontend चल रहा है, और उसका JavaScript `http://localhost` पर चल रहे backend से communicate करने की कोशिश कर रहा है (क्योंकि हम port specify नहीं करते, browser default port `80` मान लेगा)। + +फिर, browser `:80`-backend को एक HTTP `OPTIONS` request भेजेगा, और अगर backend इस अलग origin (`http://localhost:8080`) से communication को authorize करने वाले उचित headers भेजता है, तो `:8080`-browser frontend में JavaScript को अपना request `:80`-backend को भेजने देगा। + +इसे हासिल करने के लिए, `:80`-backend के पास "allowed origins" की एक list होनी चाहिए। + +इस मामले में, `:8080`-frontend के सही ढंग से काम करने के लिए list में `http://localhost:8080` शामिल होना चाहिए। + +## Wildcards { #wildcards } + +यह भी possible है कि list को `"*"` (एक "wildcard") के रूप में declare किया जाए, यह बताने के लिए कि सभी allowed हैं। + +लेकिन यह केवल कुछ प्रकार के communication को allow करेगा, उन सभी चीज़ों को छोड़कर जिनमें credentials शामिल हैं: Cookies, Authorization headers जैसे कि Bearer Tokens के साथ उपयोग किए जाने वाले, आदि। + +इसलिए, सब कुछ सही ढंग से काम करे, इसके लिए allowed origins को स्पष्ट रूप से specify करना बेहतर है। + +## `CORSMiddleware` का उपयोग करें { #use-corsmiddleware } + +आप `CORSMiddleware` का उपयोग करके इसे अपनी **FastAPI** application में configure कर सकते हैं। + +* `CORSMiddleware` import करें। +* allowed origins की एक list बनाएँ (strings के रूप में)। +* इसे अपनी **FastAPI** application में "middleware" के रूप में जोड़ें। + +आप यह भी specify कर सकते हैं कि आपका backend allow करता है या नहीं: + +* Credentials (Authorization headers, Cookies, आदि)। +* Specific HTTP methods (`POST`, `PUT`) या wildcard `"*"` के साथ सभी methods। +* Specific HTTP headers या wildcard `"*"` के साथ सभी headers। + +{* ../../docs_src/cors/tutorial001_py310.py hl[2,6:11,13:19] *} + + +`CORSMiddleware` implementation द्वारा उपयोग किए जाने वाले default parameters default रूप से restrictive होते हैं, इसलिए browsers को Cross-Domain context में उनका उपयोग करने की permission देने के लिए आपको particular origins, methods, या headers को स्पष्ट रूप से enable करना होगा। + +निम्नलिखित arguments supported हैं: + +* `allow_origins` - origins की एक list जिन्हें cross-origin requests करने की permission होनी चाहिए। जैसे `['https://example.org', 'https://www.example.org']`। आप किसी भी origin को allow करने के लिए `['*']` का उपयोग कर सकते हैं। +* `allow_origin_regex` - origins के against match करने के लिए एक regex string जिन्हें cross-origin requests करने की permission होनी चाहिए। जैसे `'https://.*\.example\.org'`। +* `allow_methods` - HTTP methods की एक list जिन्हें cross-origin requests के लिए allowed होना चाहिए। Defaults to `['GET']`। आप सभी standard methods को allow करने के लिए `['*']` का उपयोग कर सकते हैं। +* `allow_headers` - HTTP request headers की एक list जिन्हें cross-origin requests के लिए supported होना चाहिए। Defaults to `[]`। आप सभी headers को allow करने के लिए `['*']` का उपयोग कर सकते हैं। `Accept`, `Accept-Language`, `Content-Language` और `Content-Type` headers हमेशा [simple CORS requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests) के लिए allowed होते हैं। +* `allow_credentials` - indicate करता है कि cookies cross-origin requests के लिए supported होनी चाहिए। Defaults to `False`. + + अगर `allow_credentials` को `True` पर set किया गया है, तो `allow_origins`, `allow_methods` और `allow_headers` में से किसी को भी `['*']` पर set नहीं किया जा सकता। उन सभी को [explicitly specified](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#credentialed_requests_and_wildcards) होना चाहिए। + +* `expose_headers` - indicate करता है कि कौन से response headers browser के लिए accessible बनाए जाने चाहिए। Defaults to `[]`। +* `max_age` - browsers के लिए CORS responses को cache करने का maximum समय seconds में set करता है। Defaults to `600`। + +middleware दो particular प्रकार के HTTP request का response देता है... + +### CORS preflight requests { #cors-preflight-requests } + +ये `Origin` और `Access-Control-Request-Method` headers वाले कोई भी `OPTIONS` request होते हैं। + +इस मामले में middleware incoming request को intercept करेगा और appropriate CORS headers के साथ respond करेगा, और informational purposes के लिए या तो `200` या `400` response देगा। + +### Simple requests { #simple-requests } + +`Origin` header वाला कोई भी request। इस मामले में middleware request को सामान्य रूप से pass through करेगा, लेकिन response पर appropriate CORS headers शामिल करेगा। + +## अधिक जानकारी { #more-info } + +CORS के बारे में अधिक जानकारी के लिए, [Mozilla CORS documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) देखें। + +/// note | तकनीकी विवरण + +आप `from starlette.middleware.cors import CORSMiddleware` का भी उपयोग कर सकते हैं। + +**FastAPI** आपकी सुविधा के लिए, developer के रूप में, `fastapi.middleware` में कई middlewares provide करता है। लेकिन available middlewares में से अधिकांश सीधे Starlette से आते हैं। + +/// diff --git a/docs/hi/docs/tutorial/debugging.md b/docs/hi/docs/tutorial/debugging.md new file mode 100644 index 000000000..0c214bb9a --- /dev/null +++ b/docs/hi/docs/tutorial/debugging.md @@ -0,0 +1,113 @@ +# Debugging { #debugging } + +आप अपने editor में debugger connect कर सकते हैं, उदाहरण के लिए Visual Studio Code या PyCharm के साथ। + +## `uvicorn` को call करें { #call-uvicorn } + +अपने FastAPI application में, `uvicorn` को सीधे import करके run करें: + +{* ../../docs_src/debugging/tutorial001_py310.py hl[1,15] *} + +### `__name__ == "__main__"` के बारे में { #about-name-main } + +`__name__ == "__main__"` का मुख्य उद्देश्य ऐसा कुछ code रखना है जो तब execute होता है जब आपकी file को इसके साथ call किया जाता है: + +
+ +```console +$ python myapp.py +``` + +
+ +लेकिन तब call नहीं होता जब कोई दूसरी file इसे import करती है, जैसे कि: + +```Python +from myapp import app +``` + +#### अधिक विवरण { #more-details } + +मान लीजिए आपकी file का नाम `myapp.py` है। + +अगर आप इसे इसके साथ run करते हैं: + +
+ +```console +$ python myapp.py +``` + +
+ +तो आपकी file में Python द्वारा अपने आप बनाई गई internal variable `__name__` का value string `"__main__"` होगा। + +तो, यह section: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +run होगा। + +--- + +अगर आप उस module (file) को import करते हैं तो ऐसा नहीं होगा। + +तो, अगर आपके पास `importer.py` नाम की कोई दूसरी file है जिसमें यह है: + +```Python +from myapp import app + +# कुछ और code +``` + +उस स्थिति में, `myapp.py` के अंदर अपने आप बनाई गई variable `__name__` का value `"__main__"` नहीं होगा। + +तो, यह line: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +execute नहीं होगी। + +/// note | नोट + +अधिक जानकारी के लिए, [आधिकारिक Python docs](https://docs.python.org/3/library/__main__.html) देखें। + +/// + +## अपने debugger के साथ अपना code run करें { #run-your-code-with-your-debugger } + +क्योंकि आप Uvicorn server को सीधे अपने code से run कर रहे हैं, आप अपने Python program (अपने FastAPI application) को सीधे debugger से call कर सकते हैं। + +--- + +उदाहरण के लिए, Visual Studio Code में, आप यह कर सकते हैं: + +* "Debug" panel पर जाएँ। +* "Add configuration..."। +* "Python" चुनें। +* "`Python: Current File (Integrated Terminal)`" option के साथ debugger run करें। + +फिर यह आपके **FastAPI** code के साथ server start करेगा, आपके breakpoints पर रुकेगा, आदि। + +यह कुछ ऐसा दिख सकता है: + + + +--- + +अगर आप PyCharm का उपयोग करते हैं, तो आप यह कर सकते हैं: + +* "Run" menu खोलें। +* "Debug..." option चुनें। +* फिर एक context menu दिखाई देता है। +* debug करने के लिए file चुनें (इस मामले में, `main.py`)। + +फिर यह आपके **FastAPI** code के साथ server start करेगा, आपके breakpoints पर रुकेगा, आदि। + +यह कुछ ऐसा दिख सकता है: + + diff --git a/docs/hi/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/hi/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..0d166e7ea --- /dev/null +++ b/docs/hi/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,288 @@ +# Dependencies के रूप में Classes { #classes-as-dependencies } + +**Dependency Injection** system में और गहराई में जाने से पहले, पिछले उदाहरण को बेहतर बनाते हैं। + +## पिछले उदाहरण से एक `dict` { #a-dict-from-the-previous-example } + +पिछले उदाहरण में, हम अपनी dependency ("dependable") से एक `dict` return कर रहे थे: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} + +लेकिन फिर हमें *path operation function* के parameter `commons` में एक `dict` मिलता है। + +और हम जानते हैं कि editors `dict`s के लिए ज़्यादा support (जैसे completion) नहीं दे सकते, क्योंकि वे उनकी keys और value types नहीं जान सकते। + +हम इससे बेहतर कर सकते हैं... + +## Dependency किससे बनती है { #what-makes-a-dependency } + +अब तक आपने dependencies को functions के रूप में declare होते देखा है। + +लेकिन dependencies declare करने का यही एकमात्र तरीका नहीं है (हालाँकि शायद यह अधिक common होगा)। + +मुख्य बात यह है कि dependency एक "callable" होनी चाहिए। + +Python में "**callable**" वह कोई भी चीज़ है जिसे Python एक function की तरह "call" कर सकता है। + +तो, अगर आपके पास कोई object `something` है (जो शायद function _न_ हो) और आप उसे इस तरह "call" (execute) कर सकते हैं: + +```Python +something() +``` + +या + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +तो वह एक "callable" है। + +## Dependencies के रूप में Classes { #classes-as-dependencies_1 } + +आप ध्यान दे सकते हैं कि Python class का instance बनाने के लिए भी आप वही syntax उपयोग करते हैं। + +उदाहरण के लिए: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +इस case में, `fluffy` class `Cat` का एक instance है। + +और `fluffy` बनाने के लिए, आप `Cat` को "call" कर रहे हैं। + +इसलिए, Python class भी एक **callable** है। + +फिर, **FastAPI** में, आप Python class को dependency के रूप में उपयोग कर सकते हैं। + +FastAPI वास्तव में यह check करता है कि वह एक "callable" (function, class या कुछ और) है और उसमें parameters defined हैं। + +अगर आप **FastAPI** में dependency के रूप में कोई "callable" pass करते हैं, तो यह उस "callable" के parameters को analyze करेगा, और उन्हें *path operation function* के parameters की तरह ही process करेगा। इसमें sub-dependencies भी शामिल हैं। + +यह उन callables पर भी लागू होता है जिनमें कोई parameters नहीं होते। ठीक वैसे ही जैसे बिना parameters वाले *path operation functions* के लिए होता। + +फिर, हम ऊपर वाली dependency "dependable" `common_parameters` को class `CommonQueryParams` में बदल सकते हैं: + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} + +Class का instance बनाने के लिए उपयोग की गई `__init__` method पर ध्यान दें: + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} + +...इसमें वही parameters हैं जो हमारे पिछले `common_parameters` में थे: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} + +यही parameters **FastAPI** dependency को "solve" करने के लिए उपयोग करेगा। + +दोनों cases में, इसमें होगा: + +* एक optional `q` query parameter जो `str` है। +* एक `skip` query parameter जो `int` है, जिसका default `0` है। +* एक `limit` query parameter जो `int` है, जिसका default `100` है। + +दोनों cases में data converted, validated, OpenAPI schema पर documented, आदि किया जाएगा। + +## इसका उपयोग करें { #use-it } + +अब आप इस class का उपयोग करके अपनी dependency declare कर सकते हैं। + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} + +**FastAPI** `CommonQueryParams` class को call करता है। यह उस class का एक "instance" बनाता है और वह instance आपके function को parameter `commons` के रूप में pass किया जाएगा। + +## Type annotation बनाम `Depends` { #type-annotation-vs-depends } + +ध्यान दें कि ऊपर के code में हम `CommonQueryParams` को दो बार कैसे लिखते हैं: + +//// tab | Python 3.10+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | सुझाव + +संभव हो तो `Annotated` version का उपयोग करना बेहतर है। + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +आखिरी `CommonQueryParams`, इसमें: + +```Python +... Depends(CommonQueryParams) +``` + +...वही है जिसे **FastAPI** वास्तव में यह जानने के लिए उपयोग करेगा कि dependency क्या है। + +FastAPI इसी से declared parameters extract करेगा और वास्तव में इसी को call करेगा। + +--- + +इस case में, पहला `CommonQueryParams`, इसमें: + +//// tab | Python 3.10+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | सुझाव + +संभव हो तो `Annotated` version का उपयोग करना बेहतर है। + +/// + +```Python +commons: CommonQueryParams ... +``` + +//// + +...का **FastAPI** के लिए कोई विशेष अर्थ नहीं है। FastAPI इसे data conversion, validation, आदि के लिए उपयोग नहीं करेगा। (क्योंकि वह इसके लिए `Depends(CommonQueryParams)` का उपयोग कर रहा है)। + +आप वास्तव में सिर्फ यह लिख सकते हैं: + +//// tab | Python 3.10+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | सुझाव + +संभव हो तो `Annotated` version का उपयोग करना बेहतर है। + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// + +...जैसे: + +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} + +लेकिन type declare करने को प्रोत्साहित किया जाता है क्योंकि इस तरह आपका editor जान पाएगा कि parameter `commons` के रूप में क्या pass होगा, और फिर यह code completion, type checks, आदि में आपकी मदद कर सकता है: + + + +## Shortcut { #shortcut } + +लेकिन आप देखते हैं कि यहाँ कुछ code repetition हो रहा है, `CommonQueryParams` को दो बार लिखते हुए: + +//// tab | Python 3.10+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | सुझाव + +संभव हो तो `Annotated` version का उपयोग करना बेहतर है। + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +**FastAPI** ऐसे cases के लिए एक shortcut प्रदान करता है, जहाँ dependency *specifically* एक class है जिसे **FastAPI** class का instance बनाने के लिए "call" करेगा। + +उन specific cases के लिए, आप यह कर सकते हैं: + +यह लिखने के बजाय: + +//// tab | Python 3.10+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | सुझाव + +संभव हो तो `Annotated` version का उपयोग करना बेहतर है। + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +...आप लिखते हैं: + +//// tab | Python 3.10+ + +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | सुझाव + +संभव हो तो `Annotated` version का उपयोग करना बेहतर है। + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// + +आप dependency को parameter के type के रूप में declare करते हैं, और `Depends(CommonQueryParams)` के अंदर पूरी class को *फिर से* लिखने के बजाय, आप बिना किसी parameter के `Depends()` का उपयोग करते हैं। + +फिर वही उदाहरण इस तरह दिखेगा: + +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} + +...और **FastAPI** जान जाएगा कि क्या करना है। + +/// tip | सुझाव + +अगर यह मददगार से ज़्यादा confusing लगता है, तो इसे अनदेखा करें, आपको इसकी *ज़रूरत* नहीं है। + +यह सिर्फ एक shortcut है। क्योंकि **FastAPI** आपको code repetition कम करने में मदद करने की परवाह करता है। + +/// diff --git a/docs/hi/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/hi/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..6e051ef5d --- /dev/null +++ b/docs/hi/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,69 @@ +# path operation decorators में Dependencies { #dependencies-in-path-operation-decorators } + +कुछ मामलों में आपको अपनी *path operation function* के अंदर किसी dependency की return value की वास्तव में ज़रूरत नहीं होती। + +या dependency कोई value return नहीं करती। + +लेकिन फिर भी आपको उसका execute/solve होना चाहिए। + +ऐसे मामलों के लिए, `Depends` के साथ *path operation function* parameter declare करने के बजाय, आप *path operation decorator* में `dependencies` की एक `list` जोड़ सकते हैं। + +## *path operation decorator* में `dependencies` जोड़ें { #add-dependencies-to-the-path-operation-decorator } + +*path operation decorator* एक optional argument `dependencies` प्राप्त करता है। + +यह `Depends()` की एक `list` होनी चाहिए: + +{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[19] *} + +ये dependencies normal dependencies की तरह ही execute/solve होंगी। लेकिन उनकी value (यदि वे कोई return करती हैं) आपकी *path operation function* को pass नहीं की जाएगी। + +/// tip | सुझाव + +कुछ editors unused function parameters की जाँच करते हैं, और उन्हें errors के रूप में दिखाते हैं। + +*path operation decorator* में इन `dependencies` का उपयोग करके आप सुनिश्चित कर सकते हैं कि वे execute हों, साथ ही editor/tooling errors से बच सकें। + +यह नए developers के लिए भ्रम से बचने में भी मदद कर सकता है, जो आपके code में unused parameter देखकर सोच सकते हैं कि यह अनावश्यक है। + +/// + +/// note | नोट + +इस example में हम बनाए गए custom headers `X-Key` और `X-Token` का उपयोग करते हैं। + +लेकिन वास्तविक मामलों में, security implement करते समय, आपको integrated [Security utilities (अगला अध्याय)](../security/index.md) का उपयोग करने से अधिक लाभ मिलेंगे। + +/// + +## Dependencies errors और return values { #dependencies-errors-and-return-values } + +आप वही dependency *functions* उपयोग कर सकते हैं जिन्हें आप सामान्य रूप से उपयोग करते हैं। + +### Dependency requirements { #dependency-requirements } + +वे request requirements (जैसे headers) या अन्य sub-dependencies declare कर सकती हैं: + +{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[8,13] *} + +### Exceptions raise करें { #raise-exceptions } + +ये dependencies normal dependencies की तरह ही exceptions `raise` कर सकती हैं: + +{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[10,15] *} + +### Return values { #return-values } + +और वे values return कर सकती हैं या नहीं भी कर सकतीं, values का उपयोग नहीं किया जाएगा। + +इसलिए, आप एक normal dependency (जो value return करती है) को फिर से उपयोग कर सकते हैं जिसे आप पहले से कहीं और उपयोग करते हैं, और भले ही value का उपयोग न हो, dependency execute होगी: + +{* ../../docs_src/dependencies/tutorial006_an_py310.py hl[11,16] *} + +## *path operations* के समूह के लिए Dependencies { #dependencies-for-a-group-of-path-operations } + +बाद में, जब आप बड़े applications को structure करने के बारे में पढ़ेंगे ([बड़े Applications - कई Files](../../tutorial/bigger-applications.md)), संभवतः कई files के साथ, तो आप सीखेंगे कि *path operations* के समूह के लिए एक ही `dependencies` parameter कैसे declare किया जाए। + +## Global Dependencies { #global-dependencies } + +आगे हम देखेंगे कि पूरे `FastAPI` application में dependencies कैसे जोड़ी जाएँ, ताकि वे हर *path operation* पर लागू हों। diff --git a/docs/hi/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/hi/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..e85d7401a --- /dev/null +++ b/docs/hi/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,289 @@ +# `yield` वाली Dependencies { #dependencies-with-yield } + +FastAPI ऐसी dependencies को support करता है जो पूरा होने के बाद अतिरिक्त steps करती हैं। + +ऐसा करने के लिए, `return` की जगह `yield` का उपयोग करें, और अतिरिक्त steps (code) उसके बाद लिखें। + +/// tip | सुझाव + +हर dependency में `yield` का उपयोग केवल एक बार करना सुनिश्चित करें। + +/// + +/// note | तकनीकी विवरण + +कोई भी function जो इनके साथ उपयोग करने के लिए valid है: + +* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) या +* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager) + +वह **FastAPI** dependency के रूप में उपयोग करने के लिए valid होगी। + +वास्तव में, FastAPI internally इन दोनों decorators का उपयोग करता है। + +/// + +## `yield` वाली database dependency { #a-database-dependency-with-yield } + +उदाहरण के लिए, आप इसका उपयोग database session बनाने और पूरा होने के बाद उसे close करने के लिए कर सकते हैं। + +`yield` statement से पहले और उसे शामिल करते हुए केवल वही code response बनाने से पहले execute होता है: + +{* ../../docs_src/dependencies/tutorial007_py310.py hl[2:4] *} + +yield किया गया value वही होता है जिसे *path operations* और अन्य dependencies में inject किया जाता है: + +{* ../../docs_src/dependencies/tutorial007_py310.py hl[4] *} + +`yield` statement के बाद वाला code response के बाद execute होता है: + +{* ../../docs_src/dependencies/tutorial007_py310.py hl[5:6] *} + +/// tip | सुझाव + +आप `async` या regular functions का उपयोग कर सकते हैं। + +**FastAPI** हर एक के साथ सही काम करेगा, ठीक normal dependencies की तरह। + +/// + +## `yield` और `try` वाली dependency { #a-dependency-with-yield-and-try } + +अगर आप `yield` वाली dependency में `try` block का उपयोग करते हैं, तो dependency का उपयोग करते समय throw की गई कोई भी exception आपको मिलेगी। + +उदाहरण के लिए, अगर बीच में किसी point पर, किसी दूसरी dependency में या किसी *path operation* में, कुछ code ने database transaction को "rollback" किया या कोई अन्य exception बनाई, तो आपको अपनी dependency में वह exception मिलेगी। + +इसलिए, आप `except SomeException` के साथ dependency के अंदर उस specific exception को देख सकते हैं। + +इसी तरह, आप `finally` का उपयोग यह सुनिश्चित करने के लिए कर सकते हैं कि exit steps execute हों, चाहे exception आई हो या नहीं। + +{* ../../docs_src/dependencies/tutorial007_py310.py hl[3,5] *} + +## `yield` वाली Sub-dependencies { #sub-dependencies-with-yield } + +आपके पास किसी भी size और shape की sub-dependencies और sub-dependencies के "trees" हो सकते हैं, और उनमें से कोई भी या सभी `yield` का उपयोग कर सकती हैं। + +**FastAPI** यह सुनिश्चित करेगा कि `yield` वाली हर dependency में "exit code" सही क्रम में run हो। + +उदाहरण के लिए, `dependency_c` की dependency `dependency_b` पर हो सकती है, और `dependency_b` की `dependency_a` पर: + +{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[6,14,22] *} + +और वे सभी `yield` का उपयोग कर सकती हैं। + +इस case में `dependency_c` को अपना exit code execute करने के लिए `dependency_b` से मिला value (यहाँ `dep_b` नाम दिया गया है) अभी भी उपलब्ध चाहिए। + +और, बदले में, `dependency_b` को अपने exit code के लिए `dependency_a` से मिला value (यहाँ `dep_a` नाम दिया गया है) उपलब्ध चाहिए। + +{* ../../docs_src/dependencies/tutorial008_an_py310.py hl[18:19,26:27] *} + +इसी तरह, आपके पास कुछ dependencies `yield` वाली और कुछ अन्य dependencies `return` वाली हो सकती हैं, और उनमें से कुछ बाकी कुछ पर depend कर सकती हैं। + +और आपके पास एक single dependency हो सकती है जिसे `yield` वाली कई अन्य dependencies required हों, आदि। + +आप dependencies के कोई भी combinations रख सकते हैं। + +**FastAPI** यह सुनिश्चित करेगा कि सब कुछ सही क्रम में run हो। + +/// note | तकनीकी विवरण + +यह Python के [Context Managers](https://docs.python.org/3/library/contextlib.html) की वजह से काम करता है। + +**FastAPI** इसे हासिल करने के लिए internally उनका उपयोग करता है। + +/// + +## `yield` और `HTTPException` वाली Dependencies { #dependencies-with-yield-and-httpexception } + +आपने देखा कि आप `yield` वाली dependencies का उपयोग कर सकते हैं और ऐसे `try` blocks रख सकते हैं जो कुछ code execute करने की कोशिश करते हैं और फिर `finally` के बाद कुछ exit code run करते हैं। + +आप raise की गई exception को catch करने और उसके साथ कुछ करने के लिए `except` का भी उपयोग कर सकते हैं। + +उदाहरण के लिए, आप कोई अलग exception raise कर सकते हैं, जैसे `HTTPException`। + +/// tip | सुझाव + +यह थोड़ी advanced technique है, और ज्यादातर cases में आपको वास्तव में इसकी ज़रूरत नहीं होगी, क्योंकि आप अपने application code के बाकी हिस्से के अंदर से exceptions (जिसमें `HTTPException` भी शामिल है) raise कर सकते हैं, उदाहरण के लिए, *path operation function* में। + +लेकिन अगर आपको इसकी ज़रूरत हो तो यह उपलब्ध है। 🤓 + +/// + +{* ../../docs_src/dependencies/tutorial008b_an_py310.py hl[18:22,31] *} + +अगर आप exceptions को catch करके उसके आधार पर custom response बनाना चाहते हैं, तो [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers) बनाएँ। + +## `yield` और `except` वाली Dependencies { #dependencies-with-yield-and-except } + +अगर आप `yield` वाली dependency में `except` का उपयोग करके exception catch करते हैं और उसे फिर से raise नहीं करते (या कोई नई exception raise नहीं करते), तो FastAPI यह notice नहीं कर पाएगा कि कोई exception हुई थी, ठीक वैसे ही जैसे regular Python में होता: + +{* ../../docs_src/dependencies/tutorial008c_an_py310.py hl[15:16] *} + +इस case में, client को *HTTP 500 Internal Server Error* response दिखेगा, जैसा कि होना चाहिए, क्योंकि हम `HTTPException` या उसके जैसी कोई चीज़ raise नहीं कर रहे हैं, लेकिन server के पास **कोई logs नहीं होंगे** या error क्या था इसका कोई अन्य संकेत नहीं होगा। 😱 + +### `yield` और `except` वाली Dependencies में हमेशा `raise` करें { #always-raise-in-dependencies-with-yield-and-except } + +अगर आप `yield` वाली dependency में exception catch करते हैं, तो जब तक आप कोई दूसरी `HTTPException` या similar चीज़ raise नहीं कर रहे हैं, **आपको original exception को फिर से raise करना चाहिए**। + +आप `raise` का उपयोग करके उसी exception को फिर से raise कर सकते हैं: + +{* ../../docs_src/dependencies/tutorial008d_an_py310.py hl[17] *} + +अब client को वही *HTTP 500 Internal Server Error* response मिलेगा, लेकिन server के logs में हमारा custom `InternalError` होगा। 😎 + +## `yield` वाली dependencies का Execution { #execution-of-dependencies-with-yield } + +Execution का sequence कमोबेश इस diagram जैसा है। Time ऊपर से नीचे की ओर चलता है। और हर column code के साथ interact करने या execute करने वाले parts में से एक है। + +```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,operation: Can raise exceptions, including HTTPException + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise Exception + dep -->> handler: Raise Exception + handler -->> client: HTTP error response + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + 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 + 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 -->> tasks: Handle exceptions in the background task code + end +``` + +/// note | नोट + +Client को केवल **एक response** भेजा जाएगा। यह error responses में से एक हो सकता है या *path operation* से आया response होगा। + +उन responses में से एक भेजे जाने के बाद, कोई अन्य response नहीं भेजा जा सकता। + +/// + +/// tip | सुझाव + +अगर आप *path operation function* के code में कोई भी exception raise करते हैं, तो उसे yield वाली dependencies को pass किया जाएगा, जिसमें `HTTPException` भी शामिल है। ज्यादातर cases में आप चाहेंगे कि `yield` वाली dependency से वही exception या कोई नई exception फिर से raise करें ताकि यह सुनिश्चित हो सके कि उसे सही तरीके से handle किया गया है। + +/// + +## Early exit और `scope` { #early-exit-and-scope } + +आम तौर पर `yield` वाली dependencies का exit code client को **response** भेजे जाने के बाद execute होता है। + +लेकिन अगर आपको पता है कि *path operation function* से return करने के बाद आपको dependency का उपयोग करने की ज़रूरत नहीं होगी, तो आप `Depends(scope="function")` का उपयोग करके FastAPI को बता सकते हैं कि उसे dependency को *path operation function* के return करने के बाद, लेकिन **response भेजे जाने से पहले** close करना चाहिए। + +{* ../../docs_src/dependencies/tutorial008e_an_py310.py hl[12,16] *} + +`Depends()` एक `scope` parameter receive करता है जो यह हो सकता है: + +* `"function"`: request handle करने वाले *path operation function* से पहले dependency शुरू करें, *path operation function* खत्म होने के बाद dependency खत्म करें, लेकिन client को response वापस भेजे जाने से **पहले**। यानी, dependency function *path operation **function*** के **around** execute होगा। +* `"request"`: request handle करने वाले *path operation function* से पहले dependency शुरू करें (`"function"` उपयोग करने जैसा), लेकिन client को response वापस भेजे जाने के **बाद** खत्म करें। यानी, dependency function **request** और response cycle के **around** execute होगा। + +अगर specify नहीं किया गया है और dependency में `yield` है, तो उसका `scope` default रूप से `"request"` होगा। + +### Sub-dependencies के लिए `scope` { #scope-for-sub-dependencies } + +जब आप `scope="request"` (default) वाली dependency declare करते हैं, तो किसी भी sub-dependency का `scope` भी `"request"` होना चाहिए। + +लेकिन `"function"` के `scope` वाली dependency के पास `"function"` और `"request"` scope वाली dependencies हो सकती हैं। + +ऐसा इसलिए है क्योंकि किसी भी dependency को sub-dependencies से पहले अपना exit code run करने में सक्षम होना चाहिए, क्योंकि उसे अपने exit code के दौरान अभी भी उनका उपयोग करने की ज़रूरत हो सकती है। + +```mermaid +sequenceDiagram + +participant client as Client +participant dep_req as Dep scope="request" +participant dep_func as Dep scope="function" +participant operation as Path Operation + + client ->> dep_req: Start request + Note over dep_req: Run code up to yield + dep_req ->> dep_func: Pass dependency + Note over dep_func: Run code up to yield + dep_func ->> operation: Run path operation with dependency + operation ->> dep_func: Return from path operation + Note over dep_func: Run code after yield + Note over dep_func: ✅ Dependency closed + dep_func ->> client: Send response to client + Note over client: Response sent + Note over dep_req: Run code after yield + Note over dep_req: ✅ Dependency closed +``` + +## `yield`, `HTTPException`, `except` और Background Tasks वाली Dependencies { #dependencies-with-yield-httpexception-except-and-background-tasks } + +`yield` वाली Dependencies समय के साथ अलग-अलग use cases cover करने और कुछ issues fix करने के लिए evolve हुई हैं। + +अगर आप देखना चाहते हैं कि FastAPI के अलग-अलग versions में क्या बदला है, तो आप इसके बारे में advanced guide में, [Advanced Dependencies - `yield`, `HTTPException`, `except` और Background Tasks वाली Dependencies](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks) में और पढ़ सकते हैं। + +## Context Managers { #context-managers } + +### "Context Managers" क्या हैं { #what-are-context-managers } + +"Context Managers" उन Python objects में से कोई भी हैं जिनका उपयोग आप `with` statement में कर सकते हैं। + +उदाहरण के लिए, [आप file पढ़ने के लिए `with` का उपयोग कर सकते हैं](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files): + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +अंदर से, `open("./somefile.txt")` एक object बनाता है जिसे "Context Manager" कहा जाता है। + +जब `with` block खत्म होता है, तो यह file को close करना सुनिश्चित करता है, भले ही exceptions आई हों। + +जब आप `yield` वाली dependency बनाते हैं, तो **FastAPI** internally उसके लिए एक context manager बनाएगा, और उसे कुछ अन्य related tools के साथ combine करेगा। + +### `yield` वाली dependencies में context managers का उपयोग करना { #using-context-managers-in-dependencies-with-yield } + +/// warning | चेतावनी + +यह कमोबेश एक "advanced" idea है। + +अगर आप अभी **FastAPI** शुरू ही कर रहे हैं, तो शायद आप इसे अभी skip करना चाहेंगे। + +/// + +Python में, आप [दो methods वाली class बनाकर: `__enter__()` और `__exit__()`](https://docs.python.org/3/reference/datamodel.html#context-managers) Context Managers बना सकते हैं। + +आप dependency function के अंदर `with` या `async with` statements का उपयोग करके इन्हें `yield` वाली **FastAPI** dependencies के अंदर भी उपयोग कर सकते हैं: + +{* ../../docs_src/dependencies/tutorial010_py310.py hl[1:9,13] *} + +/// tip | सुझाव + +Context manager बनाने का एक और तरीका है: + +* [`@contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager) या +* [`@contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager) + +इनका उपयोग single `yield` वाले function को decorate करने के लिए करना। + +**FastAPI** internally `yield` वाली dependencies के लिए यही उपयोग करता है। + +लेकिन आपको FastAPI dependencies के लिए decorators का उपयोग करने की ज़रूरत नहीं है (और आपको नहीं करना चाहिए)। + +FastAPI internally आपके लिए यह कर देगा। + +/// diff --git a/docs/hi/docs/tutorial/dependencies/global-dependencies.md b/docs/hi/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 000000000..e313b40f0 --- /dev/null +++ b/docs/hi/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,16 @@ +# वैश्विक Dependencies { #global-dependencies } + +कुछ प्रकार के applications के लिए आप पूरे application में dependencies जोड़ना चाह सकते हैं। + +जिस तरह आप [*path operation decorators* में `dependencies` जोड़ सकते हैं](dependencies-in-path-operation-decorators.md), उसी तरह आप उन्हें `FastAPI` application में भी जोड़ सकते हैं। + +उस स्थिति में, वे application की सभी *path operations* पर लागू होंगी: + +{* ../../docs_src/dependencies/tutorial012_an_py310.py hl[17] *} + + +और [*path operation decorators* में `dependencies` जोड़ने](dependencies-in-path-operation-decorators.md) वाले section की सभी बातें अभी भी लागू होती हैं, लेकिन इस मामले में, app की सभी *path operations* पर। + +## *path operations* के समूहों के लिए Dependencies { #dependencies-for-groups-of-path-operations } + +बाद में, जब आप बड़े applications को संरचित करने के तरीके के बारे में पढ़ेंगे ([बड़े Applications - कई Files](../../tutorial/bigger-applications.md)), संभवतः कई files के साथ, तो आप सीखेंगे कि *path operations* के एक समूह के लिए एक ही `dependencies` parameter कैसे declare किया जाए। diff --git a/docs/hi/docs/tutorial/dependencies/index.md b/docs/hi/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..903e43391 --- /dev/null +++ b/docs/hi/docs/tutorial/dependencies/index.md @@ -0,0 +1,250 @@ +# Dependencies { #dependencies } + +**FastAPI** में एक बहुत शक्तिशाली लेकिन सहज **Dependency Injection** system है। + +इसे उपयोग में बहुत सरल होने के लिए, और किसी भी developer के लिए दूसरे components को **FastAPI** के साथ integrate करना बहुत आसान बनाने के लिए design किया गया है। + +## "Dependency Injection" क्या है { #what-is-dependency-injection } + +**"Dependency Injection"** का मतलब programming में यह है कि आपके code (इस मामले में, आपके *path operation functions*) के पास यह declare करने का एक तरीका होता है कि उसे काम करने और उपयोग करने के लिए किन चीज़ों की ज़रूरत है: "dependencies"। + +और फिर, वह system (इस मामले में **FastAPI**) आपके code को वे ज़रूरी dependencies उपलब्ध कराने के लिए जो भी required है, उसका ध्यान रखेगा (dependencies को "inject" करेगा)। + +यह तब बहुत उपयोगी होता है जब आपको: + +* shared logic चाहिए (वही code logic बार-बार)। +* database connections share करने हों। +* security, authentication, role requirements, आदि enforce करने हों। +* और भी कई चीज़ें... + +ये सब, code repetition को कम से कम रखते हुए। + +## पहले कदम { #first-steps } + +आइए एक बहुत सरल उदाहरण देखते हैं। यह इतना सरल होगा कि अभी के लिए बहुत उपयोगी नहीं है। + +लेकिन इस तरह हम इस बात पर focus कर सकते हैं कि **Dependency Injection** system कैसे काम करता है। + +### एक dependency, या "dependable" बनाएँ { #create-a-dependency-or-dependable } + +पहले dependency पर focus करते हैं। + +यह बस एक function है जो वे सभी समान parameters ले सकता है जो एक *path operation function* ले सकता है: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} + +बस इतना ही। + +**2 lines**। + +और इसका shape और structure वही है जो आपके सभी *path operation functions* का होता है। + +आप इसे "decorator" के बिना एक *path operation function* के रूप में सोच सकते हैं (`@app.get("/some-path")` के बिना)। + +और यह आपकी इच्छा के अनुसार कुछ भी return कर सकता है। + +इस मामले में, यह dependency अपेक्षा करती है: + +* एक optional query parameter `q` जो `str` है। +* एक optional query parameter `skip` जो `int` है, और default रूप से `0` है। +* एक optional query parameter `limit` जो `int` है, और default रूप से `100` है। + +और फिर यह बस उन values वाला एक `dict` return करता है। + +/// note | नोट + +FastAPI ने version 0.95.0 में `Annotated` के लिए support जोड़ा (और इसे recommend करना शुरू किया)। + +अगर आपके पास पुराना version है, तो `Annotated` का उपयोग करने की कोशिश करते समय आपको errors मिलेंगे। + +`Annotated` का उपयोग करने से पहले सुनिश्चित करें कि आप [FastAPI version को Upgrade](../../deployment/versions.md#upgrading-the-fastapi-versions) करके कम से कम 0.95.1 कर लें। + +/// + +### `Depends` import करें { #import-depends } + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} + +### "dependant" में dependency declare करें { #declare-the-dependency-in-the-dependant } + +जिस तरह आप अपने *path operation function* parameters के साथ `Body`, `Query`, आदि का उपयोग करते हैं, उसी तरह एक नए parameter के साथ `Depends` का उपयोग करें: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} + +हालाँकि आप अपने function के parameters में `Depends` का उपयोग उसी तरह करते हैं जैसे आप `Body`, `Query`, आदि का उपयोग करते हैं, `Depends` थोड़ा अलग तरीके से काम करता है। + +आप `Depends` को केवल एक parameter देते हैं। + +यह parameter किसी function जैसा होना चाहिए। + +आप इसे सीधे **call नहीं करते** (अंत में parentheses नहीं जोड़ते), आप बस इसे `Depends()` को एक parameter के रूप में pass करते हैं। + +और वह function उसी तरह parameters लेता है जैसे *path operation functions* लेते हैं। + +/// tip | सुझाव + +अगले chapter में आप देखेंगे कि functions के अलावा कौन सी दूसरी "चीज़ें" dependencies के रूप में उपयोग की जा सकती हैं। + +/// + +जब भी कोई नया request आता है, **FastAPI** इन बातों का ध्यान रखेगा: + +* आपकी dependency ("dependable") function को सही parameters के साथ call करना। +* आपके function से result लेना। +* उस result को आपके *path operation function* के parameter को assign करना। + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +इस तरह आप shared code एक बार लिखते हैं और **FastAPI** आपके *path operations* के लिए उसे call करने का ध्यान रखता है। + +/// tip | सुझाव + +ध्यान दें कि आपको कोई special class बनाकर उसे **FastAPI** को "register" करने के लिए कहीं pass करने या ऐसा कुछ करने की ज़रूरत नहीं है। + +आप बस इसे `Depends` को pass करते हैं और **FastAPI** जानता है कि बाकी कैसे करना है। + +/// + +## `Annotated` dependencies share करें { #share-annotated-dependencies } + +ऊपर के उदाहरणों में, आप देखते हैं कि **code duplication** का थोड़ा सा हिस्सा है। + +जब आपको `common_parameters()` dependency का उपयोग करना हो, तो आपको type annotation और `Depends()` के साथ पूरा parameter लिखना पड़ता है: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +लेकिन क्योंकि हम `Annotated` का उपयोग कर रहे हैं, हम उस `Annotated` value को एक variable में store कर सकते हैं और कई जगहों पर उपयोग कर सकते हैं: + +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} + +/// tip | सुझाव + +यह बस standard Python है, इसे "type alias" कहा जाता है, यह वास्तव में **FastAPI** के लिए specific नहीं है। + +लेकिन क्योंकि **FastAPI** Python standards पर आधारित है, जिसमें `Annotated` भी शामिल है, आप अपने code में इस trick का उपयोग कर सकते हैं। 😎 + +/// + +dependencies अपेक्षित रूप से काम करती रहेंगी, और **सबसे अच्छी बात** यह है कि **type information preserve रहेगी**, जिसका मतलब है कि आपका editor आपको **autocompletion**, **inline errors**, आदि प्रदान करना जारी रख सकेगा। यही बात `mypy` जैसे दूसरे tools के लिए भी लागू होती है। + +यह खास तौर पर तब उपयोगी होगा जब आप इसे एक **large code base** में उपयोग करते हैं जहाँ आप **वही dependencies** बार-बार **कई *path operations*** में उपयोग करते हैं। + +## `async` करें या `async` न करें { #to-async-or-not-to-async } + +क्योंकि dependencies को भी **FastAPI** द्वारा call किया जाएगा (आपके *path operation functions* की तरह), functions define करते समय वही rules लागू होते हैं। + +आप `async def` या सामान्य `def` का उपयोग कर सकते हैं। + +और आप normal `def` *path operation functions* के अंदर `async def` dependencies declare कर सकते हैं, या `async def` *path operation functions* के अंदर `def` dependencies, आदि। + +इससे फर्क नहीं पड़ता। **FastAPI** जानता होगा कि क्या करना है। + +/// note | नोट + +अगर आपको नहीं पता, तो docs में `async` और `await` के बारे में [Async: *"In a hurry?"*](../../async.md#in-a-hurry) section देखें। + +/// + +## OpenAPI के साथ integrated { #integrated-with-openapi } + +आपकी dependencies (और sub-dependencies) की सभी request declarations, validations और requirements उसी OpenAPI schema में integrate की जाएँगी। + +इसलिए, interactive docs में इन dependencies की सारी जानकारी भी होगी: + + + +## सरल उपयोग { #simple-usage } + +अगर आप इसे देखें, तो *path operation functions* इस तरह declare किए जाते हैं कि जब भी कोई *path* और *operation* match करता है, उनका उपयोग किया जाए, और फिर **FastAPI** सही parameters के साथ function को call करने और request से data extract करने का ध्यान रखता है। + +असल में, सभी (या अधिकांश) web frameworks इसी तरह काम करते हैं। + +आप उन functions को कभी सीधे call नहीं करते। वे आपके framework द्वारा call किए जाते हैं (इस मामले में, **FastAPI**)। + +Dependency Injection system के साथ, आप **FastAPI** को यह भी बता सकते हैं कि आपका *path operation function* किसी और चीज़ पर भी "depend" करता है जिसे आपके *path operation function* से पहले execute किया जाना चाहिए, और **FastAPI** उसे execute करने और results को "inject" करने का ध्यान रखेगा। + +"dependency injection" के इसी idea के लिए अन्य common terms हैं: + +* resources +* providers +* services +* injectables +* components + +## **FastAPI** plug-ins { #fastapi-plug-ins } + +Integrations और "plug-ins" **Dependency Injection** system का उपयोग करके बनाए जा सकते हैं। लेकिन वास्तव में, **"plug-ins" बनाने की कोई ज़रूरत नहीं है**, क्योंकि dependencies का उपयोग करके अनगिनत integrations और interactions declare किए जा सकते हैं जो आपके *path operation functions* के लिए उपलब्ध हो जाते हैं। + +और dependencies को बहुत सरल और सहज तरीके से बनाया जा सकता है, जिससे आप बस अपने required Python packages import कर सकते हैं, और उन्हें अपने API functions के साथ कुछ lines of code में integrate कर सकते हैं, *literally*। + +आप अगले chapters में relational और NoSQL databases, security, आदि के बारे में इसके examples देखेंगे। + +## **FastAPI** compatibility { #fastapi-compatibility } + +Dependency injection system की सरलता **FastAPI** को इनके साथ compatible बनाती है: + +* सभी relational databases +* NoSQL databases +* external packages +* external APIs +* authentication और authorization systems +* API usage monitoring systems +* response data injection systems +* आदि। + +## सरल और शक्तिशाली { #simple-and-powerful } + +हालाँकि hierarchical dependency injection system को define और use करना बहुत सरल है, फिर भी यह बहुत शक्तिशाली है। + +आप ऐसी dependencies define कर सकते हैं जो बदले में खुद dependencies define कर सकती हैं। + +अंत में, dependencies का एक hierarchical tree बनता है, और **Dependency Injection** system आपके लिए इन सभी dependencies (और उनकी sub-dependencies) को solve करने और हर step पर results प्रदान करने (inject करने) का ध्यान रखता है। + +उदाहरण के लिए, मान लें कि आपके पास 4 API endpoints (*path operations*) हैं: + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +तो आप उनमें से हर एक के लिए अलग-अलग permission requirements केवल dependencies और sub-dependencies के साथ जोड़ सकते हैं: + +```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 +``` + +## **OpenAPI** के साथ integrated { #integrated-with-openapi_1 } + +ये सभी dependencies, अपनी requirements declare करते समय, आपके *path operations* में parameters, validations, आदि भी जोड़ती हैं। + +**FastAPI** यह सब OpenAPI schema में जोड़ने का ध्यान रखेगा, ताकि यह interactive documentation systems में दिखाया जा सके। diff --git a/docs/hi/docs/tutorial/dependencies/sub-dependencies.md b/docs/hi/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..7fb4bbdb7 --- /dev/null +++ b/docs/hi/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,105 @@ +# Sub-dependencies { #sub-dependencies } + +आप ऐसी dependencies बना सकते हैं जिनकी अपनी **sub-dependencies** हों। + +वे उतनी **deep** हो सकती हैं जितनी आपको चाहिए। + +**FastAPI** उन्हें solve करने का ध्यान रखेगा। + +## पहली dependency "dependable" { #first-dependency-dependable } + +आप पहली dependency ("dependable") इस तरह बना सकते हैं: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} + +यह एक optional query parameter `q` को `str` के रूप में declare करता है, और फिर बस उसे return करता है। + +यह काफी सरल है (बहुत उपयोगी नहीं), लेकिन इससे हमें यह समझने पर ध्यान देने में मदद मिलेगी कि sub-dependencies कैसे काम करती हैं। + +## दूसरी dependency, "dependable" और "dependant" { #second-dependency-dependable-and-dependant } + +फिर आप एक और dependency function (एक "dependable") बना सकते हैं जो उसी समय अपनी खुद की dependency declare करता है (इसलिए यह एक "dependant" भी है): + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} + +आइए declared parameters पर ध्यान दें: + +* भले ही यह function खुद एक dependency ("dependable") है, यह एक और dependency भी declare करता है (यह किसी और चीज़ पर "depends" करता है)। + * यह `query_extractor` पर depends करता है, और उसके द्वारा return किए गए value को parameter `q` में assign करता है। +* यह एक optional `last_query` cookie को भी `str` के रूप में declare करता है। + * अगर user ने कोई query `q` provide नहीं की, तो हम पिछली इस्तेमाल की गई query का उपयोग करते हैं, जिसे हमने पहले एक cookie में save किया था। + +## dependency का उपयोग करें { #use-the-dependency } + +फिर हम dependency का उपयोग इस तरह कर सकते हैं: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} + +/// note | नोट + +ध्यान दें कि हम *path operation function* में केवल एक dependency declare कर रहे हैं, `query_or_cookie_extractor`। + +लेकिन **FastAPI** को पता होगा कि `query_or_cookie_extractor` को call करते समय उसके results pass करने के लिए पहले `query_extractor` को solve करना है। + +/// + +```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 +``` + +## उसी dependency को कई बार उपयोग करना { #using-the-same-dependency-multiple-times } + +अगर आपकी किसी dependency को उसी *path operation* के लिए कई बार declare किया गया है, उदाहरण के लिए, कई dependencies की कोई common sub-dependency है, तो **FastAPI** जानता होगा कि उस sub-dependency को प्रति request केवल एक बार call करना है। + +और यह return किए गए value को एक "cache" में save करेगा और उसे उन सभी "dependants" को pass करेगा जिन्हें उस specific request में इसकी ज़रूरत है, बजाय उसी request के लिए dependency को कई बार call करने के। + +एक advanced scenario में, जहाँ आप जानते हैं कि आपको उसी request में "cached" value का उपयोग करने के बजाय हर step पर dependency को call करवाना है (संभवतः कई बार), आप `Depends` का उपयोग करते समय parameter `use_cache=False` set कर सकते हैं: + +//// tab | Python 3.10+ + +```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.10+ non-Annotated + +/// tip | सुझाव + +अगर संभव हो तो `Annotated` version का उपयोग करना पसंद करें। + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// + +## Recap { #recap } + +यहाँ इस्तेमाल किए गए सभी fancy words को छोड़ दें, तो **Dependency Injection** system काफी सरल है। + +बस ऐसे functions जो *path operation functions* जैसे ही दिखते हैं। + +लेकिन फिर भी, यह बहुत powerful है, और आपको arbitrarily deeply nested dependency "graphs" (trees) declare करने देता है। + +/// tip | सुझाव + +इन सरल examples के साथ यह सब इतना उपयोगी नहीं लग सकता। + +लेकिन **security** के बारे में chapters में आप देखेंगे कि यह कितना उपयोगी है। + +और आप यह भी देखेंगे कि यह आपका कितना code बचाएगा। + +/// diff --git a/docs/hi/docs/tutorial/encoder.md b/docs/hi/docs/tutorial/encoder.md new file mode 100644 index 000000000..66dbbca2b --- /dev/null +++ b/docs/hi/docs/tutorial/encoder.md @@ -0,0 +1,35 @@ +# JSON संगत Encoder { #json-compatible-encoder } + +कुछ मामलों में आपको किसी data type (जैसे Pydantic model) को JSON के साथ संगत किसी चीज़ (जैसे `dict`, `list`, आदि) में convert करने की ज़रूरत पड़ सकती है। + +उदाहरण के लिए, अगर आपको इसे database में store करना हो। + +इसके लिए, **FastAPI** एक `jsonable_encoder()` function प्रदान करता है। + +## `jsonable_encoder` का उपयोग करना { #using-the-jsonable-encoder } + +कल्पना करें कि आपके पास एक database `fake_db` है जो केवल JSON संगत data ही स्वीकार करता है। + +उदाहरण के लिए, यह `datetime` objects स्वीकार नहीं करता, क्योंकि वे JSON के साथ संगत नहीं होते। + +इसलिए, एक `datetime` object को [ISO format](https://en.wikipedia.org/wiki/ISO_8601) में data रखने वाले `str` में convert करना होगा। + +इसी तरह, यह database Pydantic model (attributes वाला एक object) स्वीकार नहीं करेगा, केवल एक `dict`। + +इसके लिए आप `jsonable_encoder` का उपयोग कर सकते हैं। + +यह एक object, जैसे Pydantic model, प्राप्त करता है और JSON संगत version लौटाता है: + +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} + +इस उदाहरण में, यह Pydantic model को `dict` में और `datetime` को `str` में convert करेगा। + +इसे call करने का परिणाम कुछ ऐसा होता है जिसे Python standard [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps) के साथ encode किया जा सकता है। + +यह JSON format में data रखने वाला कोई बड़ा `str` (string के रूप में) return नहीं करता। यह एक Python standard data structure (जैसे `dict`) return करता है, जिसमें values और sub-values होती हैं जो सभी JSON के साथ संगत होती हैं। + +/// note | नोट + +`jsonable_encoder` वास्तव में **FastAPI** द्वारा internally data convert करने के लिए उपयोग किया जाता है। लेकिन यह कई अन्य scenarios में भी उपयोगी है। + +/// diff --git a/docs/hi/docs/tutorial/extra-data-types.md b/docs/hi/docs/tutorial/extra-data-types.md new file mode 100644 index 000000000..a157ea017 --- /dev/null +++ b/docs/hi/docs/tutorial/extra-data-types.md @@ -0,0 +1,62 @@ +# अतिरिक्त Data Types { #extra-data-types } + +अब तक, आप सामान्य data types का उपयोग करते रहे हैं, जैसे: + +* `int` +* `float` +* `str` +* `bool` + +लेकिन आप अधिक जटिल data types भी उपयोग कर सकते हैं। + +और आपको अब तक देखी गई वही features मिलती रहेंगी: + +* शानदार editor support. +* आने वाली requests से data conversion. +* response data के लिए data conversion. +* Data validation. +* Automatic annotation और documentation. + +## अन्य data types { #other-data-types } + +यहाँ कुछ अतिरिक्त data types हैं जिनका आप उपयोग कर सकते हैं: + +* `UUID`: + * एक standard "Universally Unique Identifier", जो कई databases और systems में ID के रूप में आम है। + * requests और responses में इसे `str` के रूप में दर्शाया जाएगा। +* `datetime.datetime`: + * एक Python `datetime.datetime`. + * requests और responses में इसे ISO 8601 format में `str` के रूप में दर्शाया जाएगा, जैसे: `2008-09-15T15:53:00+05:00`. +* `datetime.date`: + * Python `datetime.date`. + * requests और responses में इसे ISO 8601 format में `str` के रूप में दर्शाया जाएगा, जैसे: `2008-09-15`. +* `datetime.time`: + * एक Python `datetime.time`. + * requests और responses में इसे ISO 8601 format में `str` के रूप में दर्शाया जाएगा, जैसे: `14:23:55.003`. +* `datetime.timedelta`: + * एक Python `datetime.timedelta`. + * requests और responses में इसे कुल seconds के `float` के रूप में दर्शाया जाएगा। + * Pydantic इसे "ISO 8601 time diff encoding" के रूप में दर्शाने की अनुमति भी देता है, [अधिक जानकारी के लिए docs देखें](https://docs.pydantic.dev/latest/concepts/serialization/#custom-serializers). +* `frozenset`: + * requests और responses में, इसे `set` जैसा ही माना जाता है: + * requests में, एक list पढ़ी जाएगी, duplicates हटाए जाएँगे और उसे `set` में convert किया जाएगा। + * responses में, `set` को `list` में convert किया जाएगा। + * generate किया गया schema बताएगा कि `set` values unique हैं (JSON Schema के `uniqueItems` का उपयोग करते हुए)। +* `bytes`: + * Standard Python `bytes`. + * requests और responses में इसे `str` की तरह माना जाएगा। + * generate किया गया schema बताएगा कि यह `binary` "format" वाला `str` है। +* `Decimal`: + * Standard Python `Decimal`. + * requests और responses में, इसे `float` जैसा ही handle किया जाएगा। +* आप सभी valid Pydantic data types यहाँ देख सकते हैं: [Pydantic data types](https://docs.pydantic.dev/latest/usage/types/types/). + +## उदाहरण { #example } + +यहाँ ऊपर दिए गए कुछ types का उपयोग करते हुए parameters वाला एक उदाहरण *path operation* है। + +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} + +ध्यान दें कि function के अंदर parameters के अपने natural data type होते हैं, और उदाहरण के लिए, आप सामान्य date manipulations कर सकते हैं, जैसे: + +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/hi/docs/tutorial/extra-models.md b/docs/hi/docs/tutorial/extra-models.md new file mode 100644 index 000000000..93a4e91dc --- /dev/null +++ b/docs/hi/docs/tutorial/extra-models.md @@ -0,0 +1,211 @@ +# Extra Models { #extra-models } + +पिछले उदाहरण को आगे बढ़ाते हुए, एक से अधिक संबंधित model होना आम बात होगी। + +यह खासकर user models के मामले में होता है, क्योंकि: + +* **input model** में password हो सकने की क्षमता चाहिए। +* **output model** में password नहीं होना चाहिए। +* **database model** में शायद hashed password होना चाहिए। + +/// danger | खतरा + +user के plaintext passwords कभी store न करें। हमेशा एक "secure hash" store करें जिसे आप बाद में verify कर सकें। + +अगर आप नहीं जानते, तो आप [security chapters](security/simple-oauth2.md#password-hashing) में सीखेंगे कि "password hash" क्या होता है। + +/// + +## कई models { #multiple-models } + +यह एक सामान्य idea है कि models अपने password fields और जहाँ वे इस्तेमाल होते हैं, वहाँ कैसे दिख सकते हैं: + +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} + +### `**user_in.model_dump()` के बारे में { #about-user-in-model-dump } + +#### Pydantic का `.model_dump()` { #pydantics-model-dump } + +`user_in`, class `UserIn` का एक Pydantic model है। + +Pydantic models में एक `.model_dump()` method होता है जो model के data के साथ एक `dict` return करता है। + +तो, अगर हम इस तरह एक Pydantic object `user_in` बनाते हैं: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +और फिर हम call करते हैं: + +```Python +user_dict = user_in.model_dump() +``` + +तो अब हमारे पास variable `user_dict` में data के साथ एक `dict` है (यह Pydantic model object के बजाय एक `dict` है)। + +और अगर हम call करते हैं: + +```Python +print(user_dict) +``` + +तो हमें यह Python `dict` मिलेगा: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### एक `dict` को unpack करना { #unpacking-a-dict } + +अगर हम `user_dict` जैसा एक `dict` लेते हैं और उसे किसी function (या class) को `**user_dict` के साथ pass करते हैं, तो Python उसे "unpack" करेगा। यह `user_dict` की keys और values को सीधे key-value arguments के रूप में pass करेगा। + +तो, ऊपर वाले `user_dict` को जारी रखते हुए, यह लिखना: + +```Python +UserInDB(**user_dict) +``` + +कुछ इस equivalent result देगा: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +या अधिक सही रूप में, `user_dict` को सीधे इस्तेमाल करते हुए, उसमें भविष्य में जो भी contents हों: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### दूसरे model के contents से एक Pydantic model { #a-pydantic-model-from-the-contents-of-another } + +जैसा कि ऊपर के उदाहरण में हमें `user_in.model_dump()` से `user_dict` मिला, यह code: + +```Python +user_dict = user_in.model_dump() +UserInDB(**user_dict) +``` + +इसके equivalent होगा: + +```Python +UserInDB(**user_in.model_dump()) +``` + +...क्योंकि `user_in.model_dump()` एक `dict` है, और फिर हम उसे `**` prefix के साथ `UserInDB` को pass करके Python से उसे "unpack" करवाते हैं। + +तो, हमें एक Pydantic model के data से दूसरा Pydantic model मिलता है। + +#### एक `dict` को unpack करना और extra keywords { #unpacking-a-dict-and-extra-keywords } + +और फिर extra keyword argument `hashed_password=hashed_password` जोड़ना, जैसे: + +```Python +UserInDB(**user_in.model_dump(), hashed_password=hashed_password) +``` + +...अंत में ऐसा बन जाता है: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +/// warning | चेतावनी + +supporting additional functions `fake_password_hasher` और `fake_save_user` सिर्फ data के एक possible flow को demo करने के लिए हैं, लेकिन वे निश्चित रूप से कोई real security नहीं दे रहे हैं। + +/// + +## Duplication कम करें { #reduce-duplication } + +Code duplication कम करना **FastAPI** के core ideas में से एक है। + +क्योंकि code duplication बढ़ने से bugs, security issues, code desynchronization issues (जब आप एक जगह update करते हैं लेकिन बाकी जगह नहीं), आदि की संभावना बढ़ जाती है। + +और ये models बहुत सारा data share कर रहे हैं और attribute names और types को duplicate कर रहे हैं। + +हम इससे बेहतर कर सकते हैं। + +हम एक `UserBase` model declare कर सकते हैं जो हमारे दूसरे models के लिए base की तरह काम करता है। और फिर हम उस model की subclasses बना सकते हैं जो उसके attributes (type declarations, validation, आदि) inherit करती हैं। + +सारा data conversion, validation, documentation, आदि सामान्य रूप से काम करता रहेगा। + +इस तरह, हम केवल models के बीच के अंतर declare कर सकते हैं (plaintext `password` के साथ, `hashed_password` के साथ और password के बिना): + +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} + +## `Union` या `anyOf` { #union-or-anyof } + +आप response को दो या अधिक types के `Union` के रूप में declare कर सकते हैं, जिसका मतलब है कि response उनमें से कोई भी हो सकता है। + +इसे OpenAPI में `anyOf` के साथ define किया जाएगा। + +ऐसा करने के लिए, standard Python type hint [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union) का इस्तेमाल करें: + +/// note | नोट + +[`Union`](https://docs.pydantic.dev/latest/concepts/types/#unions) define करते समय, सबसे specific type को पहले include करें, उसके बाद कम specific type को। नीचे दिए गए उदाहरण में, अधिक specific `PlaneItem`, `Union[PlaneItem, CarItem]` में `CarItem` से पहले आता है। + +/// + +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} + +### Python 3.10 में `Union` { #union-in-python-3-10 } + +इस उदाहरण में हम argument `response_model` की value के रूप में `Union[PlaneItem, CarItem]` pass करते हैं। + +क्योंकि हम इसे **type annotation** में रखने के बजाय **argument को value** के रूप में pass कर रहे हैं, इसलिए हमें Python 3.10 में भी `Union` इस्तेमाल करना होगा। + +अगर यह type annotation में होता तो हम vertical bar इस्तेमाल कर सकते थे, जैसे: + +```Python +some_variable: PlaneItem | CarItem +``` + +लेकिन अगर हम इसे assignment `response_model=PlaneItem | CarItem` में डालते, तो हमें error मिलता, क्योंकि Python इसे type annotation के रूप में interpret करने के बजाय `PlaneItem` और `CarItem` के बीच एक **invalid operation** perform करने की कोशिश करता। + +## Models की list { #list-of-models } + +इसी तरह, आप objects की lists के responses declare कर सकते हैं। + +इसके लिए, standard Python `list` इस्तेमाल करें: + +{* ../../docs_src/extra_models/tutorial004_py310.py hl[18] *} + +## Arbitrary `dict` के साथ response { #response-with-arbitrary-dict } + +आप plain arbitrary `dict` का इस्तेमाल करके भी response declare कर सकते हैं, जिसमें Pydantic model का इस्तेमाल किए बिना केवल keys और values का type declare किया जाता है। + +यह तब उपयोगी है जब आपको valid field/attribute names (जो Pydantic model के लिए चाहिए होंगे) पहले से नहीं पता हों। + +इस मामले में, आप `dict` इस्तेमाल कर सकते हैं: + +{* ../../docs_src/extra_models/tutorial005_py310.py hl[6] *} + +## Recap { #recap } + +हर case के लिए कई Pydantic models इस्तेमाल करें और freely inherit करें। + +अगर किसी entity में अलग-अलग "states" हो सकने चाहिए, तो आपको प्रति entity एक ही data model रखने की जरूरत नहीं है। **user** "entity" एक उदाहरण है, जिसमें states में `password`, `password_hash`, या कोई password नहीं होना शामिल है। diff --git a/docs/hi/docs/tutorial/first-steps.md b/docs/hi/docs/tutorial/first-steps.md new file mode 100644 index 000000000..aa6fd4e37 --- /dev/null +++ b/docs/hi/docs/tutorial/first-steps.md @@ -0,0 +1,421 @@ +# पहले कदम { #first-steps } + +सबसे सरल FastAPI file ऐसी दिख सकती है: + +{* ../../docs_src/first_steps/tutorial001_py310.py *} + +इसे `main.py` नाम की file में copy करें। + +live server चलाएँ: + +
+ +```console +$ fastapi dev + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + +
+ +output में, कुछ ऐसी एक line होती है: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +यह line वह URL दिखाती है जहाँ आपकी app आपकी local machine पर serve की जा रही है। + +### इसे जाँचें { #check-it } + +अपने browser में [http://127.0.0.1:8000](http://127.0.0.1:8000) खोलें। + +आपको JSON response इस तरह दिखेगा: + +```JSON +{"message": "Hello World"} +``` + +### Interactive API docs { #interactive-api-docs } + +अब [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) पर जाएँ। + +आपको automatic interactive API documentation दिखेगी ([Swagger UI](https://github.com/swagger-api/swagger-ui) द्वारा प्रदान की गई): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### वैकल्पिक API docs { #alternative-api-docs } + +और अब, [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) पर जाएँ। + +आपको वैकल्पिक automatic documentation दिखेगी ([ReDoc](https://github.com/Rebilly/ReDoc) द्वारा प्रदान की गई): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI { #openapi } + +**FastAPI** APIs को define करने के लिए **OpenAPI** standard का उपयोग करके आपकी पूरी API के साथ एक "schema" generate करता है। + +#### "Schema" { #schema } + +"schema" किसी चीज़ की definition या description है। वह code नहीं जो इसे implement करता है, बल्कि सिर्फ़ एक abstract description है। + +#### API "schema" { #api-schema } + +इस मामले में, [OpenAPI](https://github.com/OAI/OpenAPI-Specification) एक specification है जो बताती है कि आपकी API का schema कैसे define करना है। + +इस schema definition में आपकी API paths, उनके द्वारा लिए जा सकने वाले संभावित parameters आदि शामिल होते हैं। + +#### Data "schema" { #data-schema } + +"schema" शब्द कुछ data के आकार को भी refer कर सकता है, जैसे JSON content। + +उस मामले में, इसका मतलब JSON attributes, और उनके data types आदि होगा। + +#### OpenAPI और JSON Schema { #openapi-and-json-schema } + +OpenAPI आपकी API के लिए API schema define करता है। और उस schema में **JSON Schema**, जो JSON data schemas के लिए standard है, का उपयोग करके आपकी API द्वारा भेजे और प्राप्त किए गए data की definitions (या "schemas") शामिल होती हैं। + +#### `openapi.json` जाँचें { #check-the-openapi-json } + +अगर आप यह जानने को उत्सुक हैं कि raw OpenAPI schema कैसा दिखता है, FastAPI आपकी पूरी API के descriptions के साथ अपने आप एक JSON (schema) generate करता है। + +आप इसे सीधे यहाँ देख सकते हैं: [http://127.0.0.1:8000/openapi.json](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 किसलिए है { #what-is-openapi-for } + +OpenAPI schema ही शामिल किए गए दो interactive documentation systems को power देता है। + +और दर्जनों विकल्प हैं, सभी OpenAPI पर आधारित। आप **FastAPI** से बनी अपनी application में इनमें से कोई भी विकल्प आसानी से जोड़ सकते हैं। + +आप इसका उपयोग उन clients के लिए अपने आप code generate करने के लिए भी कर सकते हैं जो आपकी API से communicate करते हैं। उदाहरण के लिए, frontend, mobile या IoT applications। + +### `pyproject.toml` में app `entrypoint` configure करें { #configure-the-app-entrypoint-in-pyproject-toml } + +आप `pyproject.toml` file में अपनी app कहाँ स्थित है, इसे इस तरह configure कर सकते हैं: + +```toml +[tool.fastapi] +entrypoint = "main:app" +``` + +वह `entrypoint` `fastapi` command को बताएगा कि उसे app को इस तरह import करना चाहिए: + +```python +from main import app +``` + +अगर आपका code इस तरह structured था: + +``` +. +├── backend +│   ├── main.py +│   ├── __init__.py +``` + +तो आप `entrypoint` को इस तरह set करेंगे: + +```toml +[tool.fastapi] +entrypoint = "backend.main:app" +``` + +जो इसके equivalent होगा: + +```python +from backend.main import app +``` + +### `fastapi dev` path के साथ या `--entrypoint` CLI option के साथ { #fastapi-dev-with-path-or-with-entrypoint-cli-option } + +आप `fastapi dev` command को file path भी pass कर सकते हैं, और यह उपयोग करने के लिए FastAPI app object का अनुमान लगा लेगा: + +```console +$ fastapi dev main.py +``` + +या, आप `fastapi dev` command को `--entrypoint` option भी pass कर सकते हैं: + +```console +$ fastapi dev --entrypoint main:app +``` + +लेकिन हर बार `fastapi` command call करते समय आपको सही path\entrypoint pass करना याद रखना होगा। + +इसके अलावा, दूसरे tools इसे ढूँढ नहीं पाएँगे, उदाहरण के लिए [VS Code Extension](../editor-support.md) या [FastAPI Cloud](https://fastapicloud.com), इसलिए `pyproject.toml` में `entrypoint` का उपयोग करने की सलाह दी जाती है। + +### अपनी app deploy करें (वैकल्पिक) { #deploy-your-app-optional } + +आप वैकल्पिक रूप से अपनी FastAPI app को एक single command से [FastAPI Cloud](https://fastapicloud.com) पर deploy कर सकते हैं। 🚀 + +
+ +```console +$ fastapi deploy + +Deploying to FastAPI Cloud... + +✅ Deployment successful! + +🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev +``` + +
+ +CLI आपकी FastAPI application को अपने आप detect करेगा और उसे cloud पर deploy करेगा। अगर आप logged in नहीं हैं, तो authentication process पूरा करने के लिए आपका browser खुलेगा। + +बस इतना ही! अब आप उस URL पर अपनी app access कर सकते हैं। ✨ + +## Recap, चरण दर चरण { #recap-step-by-step } + +### चरण 1: `FastAPI` import करें { #step-1-import-fastapi } + +{* ../../docs_src/first_steps/tutorial001_py310.py hl[1] *} + +`FastAPI` एक Python class है जो आपकी API के लिए सारी functionality प्रदान करती है। + +/// note | तकनीकी विवरण + +`FastAPI` एक class है जो सीधे `Starlette` से inherit करती है। + +आप `FastAPI` के साथ सारी [Starlette](https://www.starlette.dev/) functionality भी उपयोग कर सकते हैं। + +/// + +### चरण 2: एक `FastAPI` "instance" बनाएँ { #step-2-create-a-fastapi-instance } + +{* ../../docs_src/first_steps/tutorial001_py310.py hl[3] *} + +यहाँ `app` variable class `FastAPI` का एक "instance" होगा। + +यह आपकी पूरी API बनाने के लिए interaction का मुख्य point होगा। + +### चरण 3: एक *path operation* बनाएँ { #step-3-create-a-path-operation } + +#### Path { #path } + +यहाँ "Path" URL के पहले `/` से शुरू होने वाले आख़िरी हिस्से को refer करता है। + +तो, ऐसे URL में: + +``` +https://example.com/items/foo +``` + +...path होगा: + +``` +/items/foo +``` + +/// note | नोट + +एक "path" को आमतौर पर "endpoint" या "route" भी कहा जाता है। + +/// + +API बनाते समय, "path" "concerns" और "resources" को अलग करने का मुख्य तरीका है। + +#### Operation { #operation } + +यहाँ "Operation" HTTP "methods" में से किसी एक को refer करता है। + +इनमें से एक: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +...और कुछ अधिक असामान्य वाले: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +HTTP protocol में, आप इन "methods" में से एक (या अधिक) का उपयोग करके हर path से communicate कर सकते हैं। + +--- + +APIs बनाते समय, आप आमतौर पर कोई specific action करने के लिए इन specific HTTP methods का उपयोग करते हैं। + +आम तौर पर आप उपयोग करते हैं: + +* `POST`: data बनाने के लिए। +* `GET`: data पढ़ने के लिए। +* `PUT`: data update करने के लिए। +* `DELETE`: data delete करने के लिए। + +इसलिए, OpenAPI में, हर HTTP method को एक "operation" कहा जाता है। + +हम उन्हें भी "**operations**" कहेंगे। + +#### एक *path operation decorator* define करें { #define-a-path-operation-decorator } + +{* ../../docs_src/first_steps/tutorial001_py310.py hl[6] *} + +`@app.get("/")` **FastAPI** को बताता है कि ठीक नीचे वाला function उन requests को handle करने का प्रभारी है जो यहाँ जाती हैं: + +* path `/` +* get operation का उपयोग करते हुए + +/// note | `@decorator` जानकारी + +Python में उस `@something` syntax को "decorator" कहा जाता है। + +आप इसे किसी function के ऊपर लगाते हैं। जैसे एक सुंदर सजावटी टोपी (मुझे लगता है term वहीं से आया है)। + +एक "decorator" नीचे वाले function को लेता है और उसके साथ कुछ करता है। + +हमारे मामले में, यह decorator **FastAPI** को बताता है कि नीचे वाला function **path** `/` के साथ **operation** `get` से संबंधित है। + +यह "**path operation decorator**" है। + +/// + +आप दूसरे operations भी उपयोग कर सकते हैं: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +और कुछ अधिक असामान्य वाले: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +/// tip | सुझाव + +आप हर operation (HTTP method) को अपनी इच्छा के अनुसार उपयोग करने के लिए स्वतंत्र हैं। + +**FastAPI** कोई specific अर्थ enforce नहीं करता। + +यहाँ दी गई जानकारी guideline के रूप में प्रस्तुत की गई है, requirement के रूप में नहीं। + +उदाहरण के लिए, GraphQL का उपयोग करते समय आप आम तौर पर सभी actions केवल `POST` operations का उपयोग करके करते हैं। + +/// + +### चरण 4: **path operation function** define करें { #step-4-define-the-path-operation-function } + +यह हमारा "**path operation function**" है: + +* **path**: `/` है। +* **operation**: `get` है। +* **function**: "decorator" के नीचे वाला function है (`@app.get("/")` के नीचे)। + +{* ../../docs_src/first_steps/tutorial001_py310.py hl[7] *} + +यह एक Python function है। + +जब भी **FastAPI** को `GET` operation का उपयोग करके URL "`/`" पर कोई request मिलती है, तो यह इसे call करेगा। + +इस मामले में, यह एक `async` function है। + +--- + +आप इसे `async def` के बजाय normal function के रूप में भी define कर सकते हैं: + +{* ../../docs_src/first_steps/tutorial003_py310.py hl[7] *} + +/// note | नोट + +अगर आपको अंतर नहीं पता है, तो [Async: *"In a hurry?"*](../async.md#in-a-hurry) देखें। + +/// + +### चरण 5: content return करें { #step-5-return-the-content } + +{* ../../docs_src/first_steps/tutorial001_py310.py hl[8] *} + +आप `dict`, `list`, `str`, `int` आदि जैसे singular values return कर सकते हैं। + +आप Pydantic models भी return कर सकते हैं (इसके बारे में आप आगे और देखेंगे)। + +कई अन्य objects और models हैं जिन्हें अपने आप JSON में convert किया जाएगा (ORMs आदि सहित)। अपने पसंदीदा ones उपयोग करके देखें, बहुत संभावना है कि वे पहले से supported हों। + +### चरण 6: इसे Deploy करें { #step-6-deploy-it } + +अपनी app को **[FastAPI Cloud](https://fastapicloud.com)** पर एक command से deploy करें: `fastapi deploy`। 🎉 + +#### FastAPI Cloud के बारे में { #about-fastapi-cloud } + +**[FastAPI Cloud](https://fastapicloud.com)** को **FastAPI** के पीछे मौजूद उसी author और team ने बनाया है। + +यह कम से कम प्रयास के साथ API को **बनाने**, **deploy करने**, और **access करने** की process को streamlined करता है। + +यह FastAPI के साथ apps बनाने जैसा ही **developer experience**, उन्हें cloud पर **deploy** करने में लाता है। 🎉 + +FastAPI Cloud *FastAPI and friends* open source projects का प्राथमिक sponsor और funding provider है। ✨ + +#### दूसरे cloud providers पर deploy करें { #deploy-to-other-cloud-providers } + +FastAPI open source है और standards पर आधारित है। आप FastAPI apps को अपनी पसंद के किसी भी cloud provider पर deploy कर सकते हैं। + +FastAPI apps को उनके साथ deploy करने के लिए अपने cloud provider की guides follow करें। 🤓 + +## Recap { #recap } + +* `FastAPI` import करें। +* एक `app` instance बनाएँ। +* `@app.get("/")` जैसे decorators का उपयोग करके एक **path operation decorator** लिखें। +* एक **path operation function** define करें; उदाहरण के लिए, `def root(): ...`। +* `fastapi dev` command का उपयोग करके development server चलाएँ। +* वैकल्पिक रूप से अपनी app को `fastapi deploy` के साथ deploy करें। diff --git a/docs/hi/docs/tutorial/frontend.md b/docs/hi/docs/tutorial/frontend.md new file mode 100644 index 000000000..bc8e188fc --- /dev/null +++ b/docs/hi/docs/tutorial/frontend.md @@ -0,0 +1,139 @@ +# Frontend { #frontend } + +आप `app.frontend()` (या `router.frontend()`) के साथ static frontend apps serve कर सकते हैं। + +यह उन frontend tools के लिए उपयोगी है जो static files generate करते हैं, जैसे React with Vite, TanStack Router, Astro, Vue, Svelte, Angular, Solid, और अन्य। + +इन tools के साथ, आपके पास आमतौर पर एक step होता है जो frontend को build करता है, जैसे इस command के साथ: + +```bash +npm run build +``` + +यह आपके frontend files के साथ `./dist/` जैसी एक directory generate करेगा। + +आप उस directory को इन frontend frameworks के लिए required conventions के अनुसार serve करने के लिए `app.frontend()` का उपयोग कर सकते हैं। + +**FastAPI** पहले *path operations* की जाँच करता है। frontend files की जाँच केवल तब की जाती है जब कोई सामान्य route match नहीं हुआ हो, इसलिए आपकी API प्रभावित नहीं होगी। + +## Frontend Serve करें { #serve-a-frontend } + +अपना frontend build करने के बाद, उदाहरण के लिए `npm run build` के साथ, generate की गई files को किसी directory में रखें, उदाहरण के लिए, `dist`। + +आपकी project संरचना ऐसी दिख सकती है: + +```text +. +├── pyproject.toml +├── app +│ ├── __init__.py +│ └── main.py +└── dist + ├── index.html + └── assets + └── app.js +``` + +फिर इसे `app.frontend()` के साथ serve करें: + +{* ../../docs_src/frontend/tutorial001_py310.py hl[5] *} + +इसके साथ, `/assets/app.js` के लिए एक request `dist/assets/app.js` serve कर सकती है। + +अगर आपके पास एक **FastAPI** *path operation* भी है, तो *path operation* को प्राथमिकता मिलती है। + +## Client-Side Routing { #client-side-routing } + +कई frontend apps, जिनमें **single-page apps** (SPAs) शामिल हैं, client-side routing का उपयोग करते हैं। `/dashboard/settings` जैसा path असली file नहीं हो सकता है, लेकिन framework इसे handle करने का ध्यान रखेगा। + +इसलिए, अगर उस URL को सीधे access किया जा रहा है (app के अंदर navigate करने के बजाय), तो backend को frontend app को `index.html` से serve करना चाहिए, ताकि frontend framework फिर client-side routing को handle कर सके। + +इसके लिए, `fallback="index.html"` का उपयोग करें: + +{* ../../docs_src/frontend/tutorial002_py310.py hl[5] *} + +**FastAPI** इस fallback का उपयोग केवल उन `GET` और `HEAD` requests के लिए करता है जो browser navigation जैसी दिखती हैं। JavaScript, CSS, और images जैसी missing files अभी भी `404` लौटाती हैं। + +अन्य methods वाली requests, जैसे `POST` या `PUT`, उन paths पर जो केवल frontend fallback से match करते हैं, वे भी `404` लौटाती हैं। नियमित **FastAPI** *path operations* की priority अभी भी frontend routes से अधिक होती है। + +/// tip | सुझाव + +Default रूप से, `fallback` की value `fallback="auto"` होती है। अधिकतर मामलों में आपको `fallback` specify करने की ज़रूरत नहीं होगी। विवरण के लिए नीचे पढ़ें। + +/// + +यह वही है जो आप कई frontend apps के साथ चाहेंगे जो client-side routing का उपयोग करते हैं, उदाहरण के लिए, React with TanStack Router, Vue, Angular, SvelteKit, या Solid। + +## Custom 404 Page { #custom-404-page } + +आप missing frontend paths के लिए static `404.html` page भी serve कर सकते हैं: + +{* ../../docs_src/frontend/tutorial003_py310.py hl[5] *} + +वह response `404` का status code बनाए रखती है। + +इस मामले में, **FastAPI** missing frontend paths के लिए `index.html` serve नहीं करेगा। इसके बजाय यह `404.html` file लौटाएगा। + +/// tip | सुझाव + +Default रूप से, `fallback` की value `fallback="auto"` होती है। इसके साथ, अगर `404.html` file मिलती है, तो उसे अपने-आप fallback के रूप में उपयोग किया जाएगा। + +इसलिए, आप सामान्यतः `fallback` argument छोड़ सकते हैं। + +/// + +यह उन frontend tools के साथ उपयोगी है जो हर page के लिए static HTML files generate करते हैं, जैसे Astro। + +## Fallback Auto { #fallback-auto } + +Default रूप से, `app.frontend()` `fallback="auto"` का उपयोग करता है। + +अगर frontend directory में `404.html` file है, तो missing frontend paths उस file को status code `404` के साथ serve करते हैं। + +अन्यथा, अगर `index.html` file है, तो missing browser navigation paths `index.html` serve करते हैं, जो client-side routing वाले कई frontend apps अपेक्षा करते हैं। + +इसलिए, अधिकतर मामलों में आप `fallback` argument specify किए बिना `app.frontend("/", directory="dist")` का उपयोग कर सकते हैं। + +{* ../../docs_src/frontend/tutorial001_py310.py hl[5] *} + +## Fallback बंद करें { #disable-fallback } + +अगर आप missing frontend paths के लिए fallback file serve नहीं करना चाहते, तो `fallback=None` का उपयोग करें: + +{* ../../docs_src/frontend/tutorial005_py310.py hl[5] *} + +फिर missing frontend paths सामान्य `404` लौटाते हैं। + +## Directory जाँचें { #check-directory } + +Default रूप से, `app.frontend()` app बनाते समय जाँचता है कि directory मौजूद है। + +यह configuration errors को जल्दी पकड़ने में मदद करता है। उदाहरण के लिए, अगर frontend build output directory missing है, तो **FastAPI** startup पर error raise करेगा। + +अगर आपकी frontend files बाद में बनाई जाती हैं, उदाहरण के लिए app object बनने के बाद किसी अलग build step द्वारा, तो `check_dir=False` set करें: + +{* ../../docs_src/frontend/tutorial006_py310.py hl[5] *} + +`check_dir=False` के साथ, **FastAPI** app बनाते समय directory की जाँच नहीं करेगा। अगर configured directory किसी request को handle करते समय अभी भी missing है, तो **FastAPI** तब error raise करेगा। + +## इसे `APIRouter` के साथ उपयोग करें { #use-it-with-apirouter } + +आप frontend files को `APIRouter` में भी जोड़ सकते हैं और उसे prefix के साथ include कर सकते हैं: + +{* ../../docs_src/frontend/tutorial004_py310.py hl[6,7] *} + +इस उदाहरण में, frontend paths `/app` के अंतर्गत serve किए जाते हैं। + +App में कोई भी नियमित *path operations* अभी भी precedence लेंगे, अन्य routers में शामिल ones भी। + +## Dependencies और Middleware { #dependencies-and-middleware } + +Frontend responses सामान्य **FastAPI** application के अंदर run करती हैं, इसलिए HTTP middleware उन पर लागू होता है। + +App से, `APIRouter` से, और `include_router()` से dependencies भी frontend responses पर लागू होती हैं। यह cookie authentication या इसी तरह से frontend को protect करने के लिए उपयोगी हो सकता है। + +## केवल Static Build Output { #static-build-output-only } + +`app.frontend()` आपके frontend build द्वारा पहले से generate की गई files serve करता है। + +यह server-side rendering run नहीं करता। यह उन frontend frameworks के लिए है जो static files generate करते हैं, न कि उन frameworks के लिए जिन्हें हर request के लिए server पर dynamic rendering की ज़रूरत होती है। diff --git a/docs/hi/docs/tutorial/handling-errors.md b/docs/hi/docs/tutorial/handling-errors.md new file mode 100644 index 000000000..ee4570761 --- /dev/null +++ b/docs/hi/docs/tutorial/handling-errors.md @@ -0,0 +1,244 @@ +# Errors को हैंडल करना { #handling-errors } + +ऐसी कई स्थितियाँ होती हैं जिनमें आपको अपनी API का उपयोग कर रहे client को error report करना पड़ता है। + +यह client frontend वाला कोई browser, किसी और का code, कोई IoT device आदि हो सकता है। + +आपको client को यह बताने की ज़रूरत पड़ सकती है कि: + +* client के पास उस operation के लिए पर्याप्त privileges नहीं हैं। +* client के पास उस resource का access नहीं है। +* जिस item को client access करने की कोशिश कर रहा था, वह मौजूद नहीं है। +* आदि। + +इन मामलों में, आप सामान्यतः **400** की range (400 से 499 तक) में एक **HTTP status code** return करेंगे। + +यह 200 HTTP status codes (200 से 299 तक) जैसा ही है। वे "200" status codes का मतलब है कि request में किसी तरह "success" हुआ था। + +400 range के status codes का मतलब है कि client की तरफ़ से कोई error था। + +वे सभी **"404 Not Found"** errors (और jokes) याद हैं? + +## `HTTPException` का उपयोग करें { #use-httpexception } + +Client को errors वाली HTTP responses return करने के लिए आप `HTTPException` का उपयोग करते हैं। + +### `HTTPException` import करें { #import-httpexception } + +{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *} + +### अपने code में `HTTPException` raise करें { #raise-an-httpexception-in-your-code } + +`HTTPException` APIs के लिए प्रासंगिक अतिरिक्त data के साथ एक सामान्य Python exception है। + +क्योंकि यह एक Python exception है, आप इसे `return` नहीं करते, आप इसे `raise` करते हैं। + +इसका यह भी मतलब है कि अगर आप किसी utility function के अंदर हैं जिसे आप अपनी *path operation function* के अंदर call कर रहे हैं, और आप उस utility function के अंदर से `HTTPException` raise करते हैं, तो यह *path operation function* में बाकी code नहीं चलाएगा, यह उस request को तुरंत समाप्त कर देगा और `HTTPException` से HTTP error client को भेज देगा। + +किसी value को return करने के बजाय exception raise करने का लाभ Dependencies और Security वाले section में अधिक स्पष्ट होगा। + +इस example में, जब client किसी ऐसे ID से item request करता है जो मौजूद नहीं है, तो `404` के status code के साथ exception raise करें: + +{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *} + +### परिणामी response { #the-resulting-response } + +अगर client `http://example.com/items/foo` (एक `item_id` `"foo"`) request करता है, तो उस client को 200 का HTTP status code और यह JSON response मिलेगा: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +लेकिन अगर client `http://example.com/items/bar` (एक non-existent `item_id` `"bar"`) request करता है, तो उस client को 404 का HTTP status code ("not found" error) और यह JSON response मिलेगा: + +```JSON +{ + "detail": "Item not found" +} +``` + +/// tip | सुझाव + +`HTTPException` raise करते समय, आप `detail` parameter के रूप में ऐसी कोई भी value pass कर सकते हैं जिसे JSON में convert किया जा सकता हो, केवल `str` ही नहीं। + +आप `dict`, `list` आदि pass कर सकते हैं। + +इन्हें **FastAPI** अपने आप handle करता है और JSON में convert करता है। + +/// + +## custom headers जोड़ें { #add-custom-headers } + +कुछ स्थितियाँ ऐसी होती हैं जहाँ HTTP error में custom headers जोड़ पाना उपयोगी होता है। उदाहरण के लिए, कुछ प्रकार की security के लिए। + +आपको शायद अपने code में सीधे इसका उपयोग करने की ज़रूरत नहीं होगी। + +लेकिन अगर किसी advanced scenario में आपको इसकी ज़रूरत पड़े, तो आप custom headers जोड़ सकते हैं: + +{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *} + +## custom exception handlers install करें { #install-custom-exception-handlers } + +आप [Starlette से वही exception utilities](https://www.starlette.dev/exceptions/) के साथ custom exception handlers जोड़ सकते हैं। + +मान लीजिए आपके पास एक custom exception `UnicornException` है जिसे आप (या कोई library जिसका आप उपयोग करते हैं) `raise` कर सकते हैं। + +और आप इस exception को FastAPI के साथ globally handle करना चाहते हैं। + +आप `@app.exception_handler()` के साथ custom exception handler जोड़ सकते हैं: + +{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *} + +यहाँ, अगर आप `/unicorns/yolo` request करते हैं, तो *path operation* एक `UnicornException` `raise` करेगा। + +लेकिन इसे `unicorn_exception_handler` द्वारा handle किया जाएगा। + +इसलिए, आपको `418` के HTTP status code और इस JSON content के साथ एक साफ़ error मिलेगा: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +/// note | Technical Details + +आप `from starlette.requests import Request` और `from starlette.responses import JSONResponse` का भी उपयोग कर सकते हैं। + +**FastAPI** आपकी, developer की, सुविधा के लिए `starlette.responses` को `fastapi.responses` के रूप में उपलब्ध कराता है। लेकिन उपलब्ध अधिकांश responses सीधे Starlette से आते हैं। `Request` के साथ भी यही है। + +/// + +## default exception handlers को override करें { #override-the-default-exception-handlers } + +**FastAPI** में कुछ default exception handlers होते हैं। + +ये handlers default JSON responses return करने के लिए ज़िम्मेदार होते हैं, जब आप `HTTPException` `raise` करते हैं और जब request में invalid data होता है। + +आप इन exception handlers को अपने खुद के handlers से override कर सकते हैं। + +### request validation exceptions को override करें { #override-request-validation-exceptions } + +जब किसी request में invalid data होता है, तो **FastAPI** internally एक `RequestValidationError` raise करता है। + +और इसमें इसके लिए एक default exception handler भी शामिल होता है। + +इसे override करने के लिए, `RequestValidationError` import करें और exception handler को decorate करने के लिए इसे `@app.exception_handler(RequestValidationError)` के साथ उपयोग करें। + +Exception handler को एक `Request` और exception मिलेगा। + +{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *} + +अब, अगर आप `/items/foo` पर जाते हैं, तो default JSON error पाने के बजाय: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +आपको text version मिलेगा, जिसमें होगा: + +``` +Validation errors: +Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer +``` + +### `HTTPException` error handler को override करें { #override-the-httpexception-error-handler } + +उसी तरह, आप `HTTPException` handler को override कर सकते हैं। + +उदाहरण के लिए, आप इन errors के लिए JSON के बजाय plain text response return करना चाह सकते हैं: + +{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *} + +/// note | Technical Details + +आप `from starlette.responses import PlainTextResponse` का भी उपयोग कर सकते हैं। + +**FastAPI** आपकी, developer की, सुविधा के लिए `starlette.responses` को `fastapi.responses` के रूप में उपलब्ध कराता है। लेकिन उपलब्ध अधिकांश responses सीधे Starlette से आते हैं। + +/// + +/// warning | चेतावनी + +ध्यान रखें कि `RequestValidationError` में file name और उस line की जानकारी होती है जहाँ validation error होता है, ताकि अगर आप चाहें तो relevant जानकारी के साथ उसे अपने logs में दिखा सकें। + +लेकिन इसका मतलब है कि अगर आप इसे केवल string में convert करके वह जानकारी सीधे return कर देते हैं, तो आप अपने system के बारे में थोड़ी जानकारी leak कर सकते हैं, इसलिए यहाँ code हर error को अलग-अलग extract करके दिखाता है। + +/// + +### `RequestValidationError` body का उपयोग करें { #use-the-requestvalidationerror-body } + +`RequestValidationError` में वह `body` होता है जो इसे invalid data के साथ मिला था। + +आप अपनी app develop करते समय body को log और debug करने, user को return करने आदि के लिए इसका उपयोग कर सकते हैं। + +{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *} + +अब ऐसा invalid item भेजकर देखें: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +आपको एक response मिलेगा जो बताता है कि data invalid है और जिसमें received body शामिल होगा: + +```JSON hl_lines="12-15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### FastAPI का `HTTPException` बनाम Starlette का `HTTPException` { #fastapis-httpexception-vs-starlettes-httpexception } + +**FastAPI** का अपना `HTTPException` है। + +और **FastAPI** की `HTTPException` error class, Starlette की `HTTPException` error class से inherit करती है। + +केवल अंतर यह है कि **FastAPI** का `HTTPException`, `detail` field के लिए कोई भी JSON-able data accept करता है, जबकि Starlette का `HTTPException` इसके लिए केवल strings accept करता है। + +इसलिए, आप अपने code में सामान्य रूप से **FastAPI** का `HTTPException` raise करते रह सकते हैं। + +लेकिन जब आप exception handler register करते हैं, तो आपको उसे Starlette के `HTTPException` के लिए register करना चाहिए। + +इस तरह, अगर Starlette के internal code का कोई हिस्सा, या कोई Starlette extension या plug-in, Starlette `HTTPException` raise करता है, तो आपका handler उसे catch और handle कर पाएगा। + +इस example में, एक ही code में दोनों `HTTPException`s रखने के लिए, Starlette के exceptions को `StarletteHTTPException` नाम दिया गया है: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### **FastAPI** के exception handlers का फिर से उपयोग करें { #reuse-fastapis-exception-handlers } + +अगर आप **FastAPI** के उन्हीं default exception handlers के साथ exception का उपयोग करना चाहते हैं, तो आप `fastapi.exception_handlers` से default exception handlers import करके उनका फिर से उपयोग कर सकते हैं: + +{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *} + +इस example में आप केवल error को बहुत expressive message के साथ print कर रहे हैं, लेकिन आप बात समझ गए। आप exception का उपयोग कर सकते हैं और फिर बस default exception handlers का फिर से उपयोग कर सकते हैं। diff --git a/docs/hi/docs/tutorial/header-param-models.md b/docs/hi/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..4c15aa579 --- /dev/null +++ b/docs/hi/docs/tutorial/header-param-models.md @@ -0,0 +1,72 @@ +# Header Parameter Models { #header-parameter-models } + +अगर आपके पास संबंधित **header parameters** का एक समूह है, तो आप उन्हें declare करने के लिए एक **Pydantic model** बना सकते हैं। + +इससे आप **model को फिर से उपयोग** कर पाएंगे, **कई जगहों** पर, और साथ ही सभी parameters के लिए validations और metadata एक साथ declare कर पाएंगे। 😎 + +/// note | नोट + +यह FastAPI version `0.115.0` से समर्थित है। 🤓 + +/// + +## Pydantic Model के साथ Header Parameters { #header-parameters-with-a-pydantic-model } + +जिन **header parameters** की आपको ज़रूरत है, उन्हें एक **Pydantic model** में declare करें, और फिर parameter को `Header` के रूप में declare करें: + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +**FastAPI** request में **headers** से **हर field** का data **extract** करेगा और आपको वह Pydantic model देगा जिसे आपने define किया है। + +## Docs देखें { #check-the-docs } + +आप `/docs` पर docs UI में required headers देख सकते हैं: + +
+ +
+ +## Extra Headers को मना करें { #forbid-extra-headers } + +कुछ विशेष use cases में (शायद बहुत आम नहीं), आप उन headers को **restrict** करना चाह सकते हैं जिन्हें आप receive करना चाहते हैं। + +आप Pydantic की model configuration का उपयोग करके किसी भी `extra` fields को `forbid` कर सकते हैं: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +अगर कोई client कुछ **extra headers** भेजने की कोशिश करता है, तो उन्हें एक **error** response मिलेगा। + +उदाहरण के लिए, अगर client `plumbus` के value के साथ एक `tool` header भेजने की कोशिश करता है, तो उन्हें एक **error** response मिलेगा जो बताएगा कि header parameter `tool` की अनुमति नहीं है: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## Convert Underscores को Disable करें { #disable-convert-underscores } + +नियमित header parameters की तरह ही, जब parameter names में underscore characters होते हैं, तो वे **स्वचालित रूप से hyphens में convert** हो जाते हैं। + +उदाहरण के लिए, अगर आपके code में header parameter `save_data` है, तो अपेक्षित HTTP header `save-data` होगा, और docs में भी वह इसी तरह दिखाई देगा। + +अगर किसी कारण से आपको इस automatic conversion को disable करना है, तो आप header parameters के लिए Pydantic models में भी ऐसा कर सकते हैं। + +{* ../../docs_src/header_param_models/tutorial003_an_py310.py hl[19] *} + +/// warning | चेतावनी + +`convert_underscores` को `False` पर set करने से पहले, ध्यान रखें कि कुछ HTTP proxies और servers underscores वाले headers के उपयोग की अनुमति नहीं देते। + +/// + +## सारांश { #summary } + +आप **FastAPI** में **headers** declare करने के लिए **Pydantic models** का उपयोग कर सकते हैं। 😎 diff --git a/docs/hi/docs/tutorial/header-params.md b/docs/hi/docs/tutorial/header-params.md new file mode 100644 index 000000000..1b683248c --- /dev/null +++ b/docs/hi/docs/tutorial/header-params.md @@ -0,0 +1,91 @@ +# Header Parameters { #header-parameters } + +आप Header parameters को उसी तरह define कर सकते हैं जैसे आप `Query`, `Path` और `Cookie` parameters को define करते हैं। + +## `Header` import करें { #import-header } + +पहले `Header` import करें: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} + +## `Header` parameters घोषित करें { #declare-header-parameters } + +फिर `Path`, `Query` और `Cookie` जैसी ही structure का उपयोग करके header parameters घोषित करें। + +आप default value के साथ-साथ सभी अतिरिक्त validation या annotation parameters भी define कर सकते हैं: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} + +/// note | तकनीकी विवरण + +`Header` `Path`, `Query` और `Cookie` की एक "sister" class है। यह भी उसी common `Param` class से inherit करता है। + +लेकिन याद रखें कि जब आप `fastapi` से `Query`, `Path`, `Header`, और अन्य import करते हैं, तो वे वास्तव में functions होते हैं जो special classes return करते हैं। + +/// + +/// note | नोट + +headers घोषित करने के लिए, आपको `Header` का उपयोग करना होगा, क्योंकि अन्यथा parameters को query parameters के रूप में interpret किया जाएगा। + +/// + +## स्वचालित conversion { #automatic-conversion } + +`Header` में `Path`, `Query` और `Cookie` द्वारा दी जाने वाली functionality के ऊपर थोड़ी अतिरिक्त functionality होती है। + +अधिकांश standard headers एक "hyphen" character से अलग किए जाते हैं, जिसे "minus symbol" (`-`) भी कहा जाता है। + +लेकिन Python में `user-agent` जैसा variable invalid है। + +इसलिए, default रूप से, `Header` headers को extract और document करने के लिए parameter names के characters को underscore (`_`) से hyphen (`-`) में convert करेगा। + +साथ ही, HTTP headers case-insensitive होते हैं, इसलिए, आप उन्हें standard Python style (जिसे "snake_case" भी कहा जाता है) में declare कर सकते हैं। + +इसलिए, Python code में सामान्य रूप से जैसे आप `user_agent` का उपयोग करते हैं, वैसा ही कर सकते हैं, बजाय इसके कि आपको पहले अक्षरों को `User_Agent` की तरह capitalize करना पड़े या कुछ समान करना पड़े। + +अगर किसी कारण से आपको underscores से hyphens में automatic conversion disable करना हो, तो `Header` के parameter `convert_underscores` को `False` पर set करें: + +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} + +/// warning | चेतावनी + +`convert_underscores` को `False` पर set करने से पहले, ध्यान रखें कि कुछ HTTP proxies और servers underscores वाले headers के उपयोग की अनुमति नहीं देते। + +/// + +## Duplicate headers { #duplicate-headers } + +duplicate headers receive करना संभव है। इसका मतलब है, कई values वाला वही header। + +आप type declaration में list का उपयोग करके ऐसे cases define कर सकते हैं। + +आप duplicate header से सभी values Python `list` के रूप में receive करेंगे। + +उदाहरण के लिए, `X-Token` का header declare करने के लिए जो एक से अधिक बार आ सकता है, आप लिख सकते हैं: + +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} + +यदि आप उस *path operation* के साथ दो HTTP headers भेजते हुए communicate करते हैं, जैसे: + +``` +X-Token: foo +X-Token: bar +``` + +response ऐसा होगा: + +```JSON +{ + "X-Token values": [ + "bar", + "foo" + ] +} +``` + +## Recap { #recap } + +`Query`, `Path` और `Cookie` जैसे ही common pattern का उपयोग करते हुए, `Header` के साथ headers declare करें। + +और अपनी variables में underscores के बारे में चिंता न करें, **FastAPI** उन्हें convert करने का ध्यान रखेगा। diff --git a/docs/hi/docs/tutorial/index.md b/docs/hi/docs/tutorial/index.md new file mode 100644 index 000000000..f5aff090f --- /dev/null +++ b/docs/hi/docs/tutorial/index.md @@ -0,0 +1,101 @@ +# Tutorial - उपयोगकर्ता गाइड { #tutorial-user-guide } + +यह tutorial आपको step by step दिखाता है कि **FastAPI** को इसकी अधिकतर features के साथ कैसे उपयोग करें। + +हर section धीरे-धीरे पिछले section पर आधारित होता है, लेकिन इसे topics को अलग रखने के लिए संरचित किया गया है, ताकि आप अपनी खास API ज़रूरतों को हल करने के लिए सीधे किसी भी specific topic पर जा सकें। + +इसे भविष्य के reference के रूप में काम करने के लिए भी बनाया गया है, ताकि आप वापस आकर ठीक वही देख सकें जिसकी आपको ज़रूरत है। + +## code चलाएँ { #run-the-code } + +सभी code blocks को copy करके सीधे उपयोग किया जा सकता है (वे वास्तव में tested Python files हैं)। + +किसी भी example को चलाने के लिए, code को `main.py` file में copy करें, और `fastapi dev` शुरू करें: + +
+ +```console +$ fastapi dev + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + +
+ +यह **बहुत ज़्यादा प्रोत्साहित** किया जाता है कि आप code लिखें या copy करें, उसे edit करें और locally चलाएँ। + +इसे अपने editor में उपयोग करना ही वास्तव में आपको FastAPI के लाभ दिखाता है, जैसे आपको कितना कम code लिखना पड़ता है, सभी type checks, autocompletion, आदि। + +--- + +## FastAPI install करें { #install-fastapi } + +पहला step FastAPI install करना है। + +सुनिश्चित करें कि आप एक [virtual environment](../virtual-environments.md) बनाएँ, उसे activate करें, और फिर **FastAPI install करें**: + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +/// note | नोट + +जब आप `pip install "fastapi[standard]"` के साथ install करते हैं, तो यह कुछ default optional standard dependencies के साथ आता है, जिनमें `fastapi-cloud-cli` शामिल है, जो आपको [FastAPI Cloud](https://fastapicloud.com) पर deploy करने देता है। + +अगर आप वे optional dependencies नहीं चाहते, तो इसके बजाय आप `pip install fastapi` install कर सकते हैं। + +अगर आप standard dependencies install करना चाहते हैं लेकिन `fastapi-cloud-cli` के बिना, तो आप `pip install "fastapi[standard-no-fastapi-cloud-cli]"` के साथ install कर सकते हैं। + +/// + +/// tip | सुझाव + +FastAPI के पास [VS Code के लिए official extension](https://marketplace.visualstudio.com/items?itemName=FastAPILabs.fastapi-vscode) (और Cursor) है, जो बहुत सारी features देता है, जिनमें path operation explorer, path operation search, tests में CodeLens navigation (tests से definition पर jump करना), और FastAPI Cloud deployment और logs शामिल हैं — सब कुछ आपके editor से। + +/// + +## उन्नत उपयोगकर्ता गाइड { #advanced-user-guide } + +एक **उन्नत उपयोगकर्ता गाइड** भी है जिसे आप इस **Tutorial - उपयोगकर्ता गाइड** के बाद पढ़ सकते हैं। + +**उन्नत उपयोगकर्ता गाइड** इसी पर आधारित है, वही concepts उपयोग करता है, और आपको कुछ अतिरिक्त features सिखाता है। + +लेकिन आपको पहले **Tutorial - उपयोगकर्ता गाइड** पढ़ना चाहिए (जो आप अभी पढ़ रहे हैं)। + +इसे इस तरह design किया गया है कि आप सिर्फ **Tutorial - उपयोगकर्ता गाइड** के साथ एक complete application बना सकें, और फिर अपनी ज़रूरतों के अनुसार **उन्नत उपयोगकर्ता गाइड** के कुछ अतिरिक्त ideas का उपयोग करके उसे अलग-अलग तरीकों से extend कर सकें। diff --git a/docs/hi/docs/tutorial/metadata.md b/docs/hi/docs/tutorial/metadata.md new file mode 100644 index 000000000..ef3f817a2 --- /dev/null +++ b/docs/hi/docs/tutorial/metadata.md @@ -0,0 +1,120 @@ +# Metadata और Docs URLs { #metadata-and-docs-urls } + +आप अपनी **FastAPI** application में कई metadata configurations को customize कर सकते हैं। + +## API के लिए Metadata { #metadata-for-api } + +आप निम्नलिखित fields set कर सकते हैं, जिनका उपयोग OpenAPI specification और automatic API docs UIs में किया जाता है: + +| Parameter | Type | विवरण | +|------------|------|-------------| +| `title` | `str` | API का title। | +| `summary` | `str` | API का एक छोटा summary। OpenAPI 3.1.0, FastAPI 0.99.0 से उपलब्ध। | +| `description` | `str` | API का एक छोटा description। यह Markdown का उपयोग कर सकता है। | +| `version` | `str` | API का version। यह आपकी अपनी application का version है, OpenAPI का नहीं। उदाहरण के लिए `2.5.0`। | +| `terms_of_service` | `str` | API के Terms of Service के लिए एक URL। यदि दिया गया हो, तो यह URL होना चाहिए। | +| `contact` | `dict` | exposed API के लिए contact information। इसमें कई fields हो सकते हैं।
contact fields
ParameterTypeविवरण
namestrcontact person/organization का identifying name।
urlstrcontact information की ओर point करने वाला URL। URL के format में होना चाहिए।
emailstrcontact person/organization का email address। email address के format में होना चाहिए।
| +| `license_info` | `dict` | exposed API के लिए license information। इसमें कई fields हो सकते हैं।
license_info fields
ParameterTypeविवरण
namestrREQUIRED (यदि license_info set किया गया हो)। API के लिए उपयोग किया गया license name।
identifierstrAPI के लिए एक [SPDX](https://spdx.org/licenses/) license expression। identifier field, url field के साथ mutually exclusive है। OpenAPI 3.1.0, FastAPI 0.99.0 से उपलब्ध।
urlstrAPI के लिए उपयोग किए गए license का URL। URL के format में होना चाहिए।
| + +आप इन्हें इस तरह set कर सकते हैं: + +{* ../../docs_src/metadata/tutorial001_py310.py hl[3:16, 19:32] *} + +/// tip | सुझाव + +आप `description` field में Markdown लिख सकते हैं और यह output में render होगा। + +/// + +इस configuration के साथ, automatic API docs इस तरह दिखेंगे: + + + +## License identifier { #license-identifier } + +OpenAPI 3.1.0 और FastAPI 0.99.0 से, आप `license_info` को `url` के बजाय `identifier` के साथ भी set कर सकते हैं। + +उदाहरण के लिए: + +{* ../../docs_src/metadata/tutorial001_1_py310.py hl[31] *} + +## Tags के लिए Metadata { #metadata-for-tags } + +आप अपने path operations को group करने के लिए उपयोग किए गए अलग-अलग tags के लिए `openapi_tags` parameter के साथ अतिरिक्त metadata भी जोड़ सकते हैं। + +यह प्रत्येक tag के लिए एक dictionary वाली list लेता है। + +प्रत्येक dictionary में हो सकता है: + +* `name` (**required**): वही tag name वाला `str`, जिसे आप अपने *path operations* और `APIRouter`s में `tags` parameter में उपयोग करते हैं। +* `description`: tag के लिए short description वाला `str`। इसमें Markdown हो सकता है और यह docs UI में दिखाया जाएगा। +* `externalDocs`: external documentation का वर्णन करने वाला `dict`, जिसमें: + * `description`: external docs के लिए short description वाला `str`। + * `url` (**required**): external documentation के लिए URL वाला `str`। + +### Tags के लिए metadata बनाएँ { #create-metadata-for-tags } + +आइए इसे `users` और `items` के tags वाले एक उदाहरण में आज़माते हैं। + +अपने tags के लिए metadata बनाएँ और उसे `openapi_tags` parameter में pass करें: + +{* ../../docs_src/metadata/tutorial004_py310.py hl[3:16,18] *} + +ध्यान दें कि आप descriptions के अंदर Markdown का उपयोग कर सकते हैं, उदाहरण के लिए "login" bold (**login**) में दिखेगा और "fancy" italics (_fancy_) में दिखेगा। + +/// tip | सुझाव + +आपको अपने उपयोग किए गए सभी tags के लिए metadata जोड़ना ज़रूरी नहीं है। + +/// + +### अपने tags का उपयोग करें { #use-your-tags } + +अपने *path operations* (और `APIRouter`s) के साथ `tags` parameter का उपयोग करें, ताकि उन्हें अलग-अलग tags में assign किया जा सके: + +{* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *} + +/// note | नोट + +Tags के बारे में और पढ़ें [Path Operation Configuration](path-operation-configuration.md#tags) में। + +/// + +### Docs जाँचें { #check-the-docs } + +अब, अगर आप docs जाँचते हैं, तो वे सभी अतिरिक्त metadata दिखाएँगे: + + + +### Tags का क्रम { #order-of-tags } + +हर tag metadata dictionary का क्रम भी docs UI में दिखाए जाने वाले क्रम को define करता है। + +उदाहरण के लिए, भले ही `users` alphabetical order में `items` के बाद आता, यह उनसे पहले दिखाया जाता है, क्योंकि हमने उनकी metadata को list में पहली dictionary के रूप में जोड़ा था। + +## OpenAPI URL { #openapi-url } + +Default रूप से, OpenAPI schema `/openapi.json` पर serve किया जाता है। + +लेकिन आप इसे `openapi_url` parameter के साथ configure कर सकते हैं। + +उदाहरण के लिए, इसे `/api/v1/openapi.json` पर serve करने के लिए set करने हेतु: + +{* ../../docs_src/metadata/tutorial002_py310.py hl[3] *} + +यदि आप OpenAPI schema को पूरी तरह disable करना चाहते हैं, तो आप `openapi_url=None` set कर सकते हैं, इससे इसका उपयोग करने वाले documentation user interfaces भी disable हो जाएँगे। + +## Docs URLs { #docs-urls } + +आप शामिल किए गए दो documentation user interfaces configure कर सकते हैं: + +* **Swagger UI**: `/docs` पर serve किया जाता है। + * आप इसका URL `docs_url` parameter के साथ set कर सकते हैं। + * आप `docs_url=None` set करके इसे disable कर सकते हैं। +* **ReDoc**: `/redoc` पर serve किया जाता है। + * आप इसका URL `redoc_url` parameter के साथ set कर सकते हैं। + * आप `redoc_url=None` set करके इसे disable कर सकते हैं। + +उदाहरण के लिए, Swagger UI को `/documentation` पर serve करने के लिए set करना और ReDoc को disable करना: + +{* ../../docs_src/metadata/tutorial003_py310.py hl[3] *} diff --git a/docs/hi/docs/tutorial/middleware.md b/docs/hi/docs/tutorial/middleware.md new file mode 100644 index 000000000..0fd2be7a9 --- /dev/null +++ b/docs/hi/docs/tutorial/middleware.md @@ -0,0 +1,95 @@ +# Middleware { #middleware } + +आप **FastAPI** applications में middleware जोड़ सकते हैं। + +"middleware" एक function है जो हर **request** के साथ काम करता है, इससे पहले कि उसे किसी विशेष *path operation* द्वारा process किया जाए। और हर **response** के साथ भी, उसे लौटाने से पहले। + +* यह आपके application में आने वाली हर **request** लेता है। +* फिर यह उस **request** के साथ कुछ कर सकता है या कोई required code चला सकता है। +* फिर यह **request** को application के बाकी हिस्से द्वारा process होने के लिए आगे भेजता है (किसी *path operation* द्वारा)। +* फिर यह application द्वारा generate किया गया **response** लेता है (किसी *path operation* द्वारा)। +* यह उस **response** के साथ कुछ कर सकता है या कोई required code चला सकता है। +* फिर यह **response** लौटाता है। + +/// note | तकनीकी विवरण + +अगर आपके पास `yield` वाली dependencies हैं, तो exit code middleware के *बाद* चलेगा। + +अगर कोई background tasks थे ([Background Tasks](background-tasks.md) section में कवर किया गया है, आप इसे बाद में देखेंगे), तो वे सभी middleware के *बाद* चलेंगे। + +/// + +## Middleware बनाएं { #create-a-middleware } + +middleware बनाने के लिए आप किसी function के ऊपर decorator `@app.middleware("http")` का उपयोग करते हैं। + +middleware function को मिलता है: + +* `request`। +* एक function `call_next` जो `request` को parameter के रूप में प्राप्त करेगा। + * यह function `request` को संबंधित *path operation* तक पास करेगा। + * फिर यह संबंधित *path operation* द्वारा generate किया गया `response` लौटाता है। +* फिर आप `response` लौटाने से पहले उसे और modify कर सकते हैं। + +{* ../../docs_src/middleware/tutorial001_py310.py hl[8:9,11,14] *} + +/// tip | सुझाव + +ध्यान रखें कि custom proprietary headers को [`X-` prefix का उपयोग करके](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) जोड़ा जा सकता है। + +लेकिन अगर आपके पास custom headers हैं जिन्हें आप browser में client को दिखाना चाहते हैं, तो आपको उन्हें अपने CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md)) में `expose_headers` parameter का उपयोग करके जोड़ना होगा, जैसा कि [Starlette के CORS docs](https://www.starlette.dev/middleware/#corsmiddleware) में documented है। + +/// + +/// note | तकनीकी विवरण + +आप `from starlette.requests import Request` भी उपयोग कर सकते हैं। + +**FastAPI** इसे आपके लिए, developer की सुविधा के रूप में provide करता है। लेकिन यह सीधे Starlette से आता है। + +/// + +### `response` से पहले और बाद में { #before-and-after-the-response } + +आप `request` के साथ चलाने के लिए code जोड़ सकते हैं, इससे पहले कि कोई *path operation* उसे प्राप्त करे। + +और `response` generate होने के बाद भी, उसे लौटाने से पहले। + +उदाहरण के लिए, आप एक custom header `X-Process-Time` जोड़ सकते हैं जिसमें seconds में वह time हो जो request को process करने और response generate करने में लगा: + +{* ../../docs_src/middleware/tutorial001_py310.py hl[10,12:13] *} + +/// tip | सुझाव + +यहाँ हम `time.time()` के बजाय [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) का उपयोग करते हैं क्योंकि यह इन use cases के लिए अधिक precise हो सकता है। 🤓 + +/// + +## कई middleware का execution order { #multiple-middleware-execution-order } + +जब आप `@app.middleware()` decorator या `app.add_middleware()` method का उपयोग करके कई middleware जोड़ते हैं, तो हर नया middleware application को wrap करता है, जिससे एक stack बनता है। जो middleware अंत में जोड़ा जाता है वह *outermost* होता है, और पहला *innermost* होता है। + +request path पर, *outermost* middleware पहले चलता है। + +response path पर, यह अंत में चलता है। + +उदाहरण के लिए: + +```Python +app.add_middleware(MiddlewareA) +app.add_middleware(MiddlewareB) +``` + +इससे execution order यह होता है: + +* **Request**: MiddlewareB → MiddlewareA → route + +* **Response**: route → MiddlewareA → MiddlewareB + +यह stacking behavior सुनिश्चित करता है कि middleware एक predictable और controllable order में execute हों। + +## अन्य middleware { #other-middlewares } + +आप बाद में [Advanced User Guide: Advanced Middleware](../advanced/middleware.md) में अन्य middleware के बारे में और पढ़ सकते हैं। + +आप अगले section में middleware के साथ CORS को handle करने के बारे में पढ़ेंगे। diff --git a/docs/hi/docs/tutorial/path-operation-configuration.md b/docs/hi/docs/tutorial/path-operation-configuration.md new file mode 100644 index 000000000..99c63aec9 --- /dev/null +++ b/docs/hi/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,107 @@ +# Path Operation Configuration { #path-operation-configuration } + +कई parameters हैं जिन्हें आप अपने *path operation decorator* को configure करने के लिए pass कर सकते हैं। + +/// warning | चेतावनी + +ध्यान दें कि ये parameters सीधे *path operation decorator* को pass किए जाते हैं, आपके *path operation function* को नहीं। + +/// + +## Response Status Code { #response-status-code } + +आप अपनी *path operation* की response में उपयोग किए जाने वाला (HTTP) `status_code` define कर सकते हैं। + +आप सीधे `int` code pass कर सकते हैं, जैसे `404`। + +लेकिन अगर आपको याद नहीं है कि हर number code किसके लिए है, तो आप `status` में shortcut constants का उपयोग कर सकते हैं: + +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} + +वह status code response में उपयोग किया जाएगा और OpenAPI schema में जोड़ा जाएगा। + +/// note | तकनीकी विवरण + +आप `from starlette import status` भी उपयोग कर सकते हैं। + +**FastAPI** आपकी सुविधा के लिए, developer के रूप में, वही `starlette.status` `fastapi.status` के रूप में प्रदान करता है। लेकिन यह सीधे Starlette से आता है। + +/// + +## Tags { #tags } + +आप अपनी *path operation* में tags जोड़ सकते हैं, parameter `tags` को `str` की `list` के साथ pass करें (आम तौर पर सिर्फ एक `str`): + +{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *} + +वे OpenAPI schema में जोड़े जाएंगे और automatic documentation interfaces द्वारा उपयोग किए जाएंगे: + + + +### Enums के साथ Tags { #tags-with-enums } + +अगर आपके पास एक बड़ी application है, तो आप अंत में **कई tags** जमा कर सकते हैं, और आप यह सुनिश्चित करना चाहेंगे कि related *path operations* के लिए आप हमेशा **एक ही tag** का उपयोग करें। + +इन मामलों में, tags को एक `Enum` में store करना समझदारी हो सकती है। + +**FastAPI** इसे plain strings की तरह ही support करता है: + +{* ../../docs_src/path_operation_configuration/tutorial002b_py310.py hl[1,8:10,13,18] *} + +## Summary और description { #summary-and-description } + +आप `summary` और `description` जोड़ सकते हैं: + +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[17:18] *} + +## Docstring से description { #description-from-docstring } + +क्योंकि descriptions आम तौर पर लंबी होती हैं और कई lines में फैलती हैं, आप *path operation* की description को function docstring में declare कर सकते हैं और **FastAPI** उसे वहीं से पढ़ेगा। + +आप docstring में [Markdown](https://en.wikipedia.org/wiki/Markdown) लिख सकते हैं, इसे सही तरीके से interpret और display किया जाएगा (docstring indentation को ध्यान में रखते हुए)। + +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} + +इसे interactive docs में उपयोग किया जाएगा: + + + +## Response description { #response-description } + +आप parameter `response_description` के साथ response description specify कर सकते हैं: + +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *} + +/// note | नोट + +ध्यान दें कि `response_description` विशेष रूप से response को refer करता है, जबकि `description` सामान्य रूप से *path operation* को refer करता है। + +/// + +/// tip | सुझाव + +OpenAPI specify करता है कि प्रत्येक *path operation* को response description required होती है। + +इसलिए, अगर आप कोई provide नहीं करते, तो **FastAPI** अपने आप "Successful response" generate कर देगा। + +/// + + + +## एक *path operation* को Deprecated करें { #deprecate-a-path-operation } + +अगर आपको किसी *path operation* को deprecated के रूप में mark करना है, लेकिन उसे हटाना नहीं है, तो parameter `deprecated` pass करें: + +{* ../../docs_src/path_operation_configuration/tutorial006_py310.py hl[16] *} + +इसे interactive docs में स्पष्ट रूप से deprecated के रूप में mark किया जाएगा: + + + +देखें कि deprecated और non-deprecated *path operations* कैसे दिखते हैं: + + + +## Recap { #recap } + +आप *path operation decorators* को parameters pass करके अपनी *path operations* के लिए metadata आसानी से configure और add कर सकते हैं। diff --git a/docs/hi/docs/tutorial/path-params-numeric-validations.md b/docs/hi/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..59ecd7c4e --- /dev/null +++ b/docs/hi/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,154 @@ +# Path Parameters और संख्यात्मक Validations { #path-parameters-and-numeric-validations } + +जिस तरह आप `Query` के साथ query parameters के लिए अधिक validations और metadata घोषित कर सकते हैं, उसी तरह आप `Path` के साथ path parameters के लिए उसी प्रकार की validations और metadata घोषित कर सकते हैं। + +## `Path` import करें { #import-path } + +सबसे पहले, `fastapi` से `Path` import करें, और `Annotated` import करें: + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} + +/// note | नोट + +FastAPI ने version 0.95.0 में `Annotated` के लिए support जोड़ा था (और इसकी सिफारिश करना शुरू किया था)। + +अगर आपके पास पुराना version है, तो `Annotated` का उपयोग करने की कोशिश करते समय आपको errors मिलेंगे। + +`Annotated` का उपयोग करने से पहले सुनिश्चित करें कि आप [FastAPI version को Upgrade करें](../deployment/versions.md#upgrading-the-fastapi-versions) कम से कम 0.95.1 तक। + +/// + +## Metadata घोषित करें { #declare-metadata } + +आप `Query` के लिए जैसे सभी parameters घोषित करते हैं, वैसे ही यहाँ भी कर सकते हैं। + +उदाहरण के लिए, path parameter `item_id` के लिए `title` metadata value घोषित करने के लिए आप लिख सकते हैं: + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} + +/// note | नोट + +एक path parameter हमेशा required होता है क्योंकि उसे path का हिस्सा होना होता है। भले ही आपने इसे `None` के साथ घोषित किया हो या कोई default value सेट की हो, इससे कुछ भी प्रभावित नहीं होगा, यह फिर भी हमेशा required रहेगा। + +/// + +## Parameters को अपनी ज़रूरत के अनुसार क्रम दें { #order-the-parameters-as-you-need } + +/// tip | सुझाव + +यदि आप `Annotated` का उपयोग करते हैं, तो यह शायद उतना महत्वपूर्ण या ज़रूरी नहीं है। + +/// + +मान लें कि आप query parameter `q` को required `str` के रूप में घोषित करना चाहते हैं। + +और आपको उस parameter के लिए कुछ और घोषित करने की ज़रूरत नहीं है, इसलिए वास्तव में आपको `Query` का उपयोग करने की ज़रूरत नहीं है। + +लेकिन आपको फिर भी `item_id` path parameter के लिए `Path` का उपयोग करना होगा। और किसी कारण से आप `Annotated` का उपयोग नहीं करना चाहते। + +यदि आप किसी ऐसे value को, जिसके पास "default" है, ऐसे value से पहले रखते हैं जिसके पास "default" नहीं है, तो Python शिकायत करेगा। + +लेकिन आप उनका क्रम बदल सकते हैं, और बिना default वाले value (query parameter `q`) को पहले रख सकते हैं। + +**FastAPI** के लिए इससे फर्क नहीं पड़ता। यह parameters को उनके नामों, types और default declarations (`Query`, `Path`, आदि) से पहचान लेगा, इसे क्रम से कोई फर्क नहीं पड़ता। + +तो, आप अपनी function इस तरह घोषित कर सकते हैं: + +{* ../../docs_src/path_params_numeric_validations/tutorial002_py310.py hl[7] *} + +लेकिन ध्यान रखें कि यदि आप `Annotated` का उपयोग करते हैं, तो आपको यह समस्या नहीं होगी, क्योंकि आप `Query()` या `Path()` के लिए function parameter default values का उपयोग नहीं कर रहे हैं। + +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py310.py *} + +## Parameters को अपनी ज़रूरत के अनुसार क्रम दें, tricks { #order-the-parameters-as-you-need-tricks } + +/// tip | सुझाव + +यदि आप `Annotated` का उपयोग करते हैं, तो यह शायद उतना महत्वपूर्ण या ज़रूरी नहीं है। + +/// + +यहाँ एक **छोटी trick** है जो काम आ सकती है, लेकिन आपको इसकी अक्सर ज़रूरत नहीं पड़ेगी। + +यदि आप चाहते हैं कि: + +* `q` query parameter को बिना `Query` और बिना किसी default value के घोषित करें +* path parameter `item_id` को `Path` का उपयोग करके घोषित करें +* उन्हें अलग क्रम में रखें +* `Annotated` का उपयोग न करें + +...तो Python में इसके लिए एक छोटी विशेष syntax है। + +function के पहले parameter के रूप में `*` पास करें। + +Python उस `*` के साथ कुछ नहीं करेगा, लेकिन उसे पता चल जाएगा कि उसके बाद आने वाले सभी parameters को keyword arguments (key-value pairs) के रूप में call किया जाना चाहिए, जिन्हें kwargs भी कहा जाता है। भले ही उनके पास default value न हो। + +{* ../../docs_src/path_params_numeric_validations/tutorial003_py310.py hl[7] *} + +### `Annotated` के साथ बेहतर { #better-with-annotated } + +ध्यान रखें कि यदि आप `Annotated` का उपयोग करते हैं, तो चूँकि आप function parameter default values का उपयोग नहीं कर रहे हैं, आपको यह समस्या नहीं होगी, और शायद आपको `*` का उपयोग करने की ज़रूरत नहीं पड़ेगी। + +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py310.py hl[10] *} + +## Number validations: greater than or equal { #number-validations-greater-than-or-equal } + +`Query` और `Path` (और अन्य जिन्हें आप बाद में देखेंगे) के साथ आप number constraints घोषित कर सकते हैं। + +यहाँ, `ge=1` के साथ, `item_id` को `1` से "`g`reater than or `e`qual" integer number होना होगा। + +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py310.py hl[10] *} + +## Number validations: greater than और less than or equal { #number-validations-greater-than-and-less-than-or-equal } + +यही बात इन पर भी लागू होती है: + +* `gt`: `g`reater `t`han +* `le`: `l`ess than or `e`qual + +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py310.py hl[10] *} + +## Number validations: floats, greater than और less than { #number-validations-floats-greater-than-and-less-than } + +Number validations `float` values के लिए भी काम करती हैं। + +यहीं पर gt घोषित कर पाना महत्वपूर्ण हो जाता है, सिर्फ ge नहीं। क्योंकि इसके साथ आप, उदाहरण के लिए, यह require कर सकते हैं कि कोई value `0` से अधिक होनी चाहिए, भले ही वह `1` से कम हो। + +तो, `0.5` एक valid value होगा। लेकिन `0.0` या `0` नहीं होंगे। + +और यही बात lt के लिए भी है। + +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py310.py hl[13] *} + +## Recap { #recap } + +`Query`, `Path` (और अन्य जिन्हें आपने अभी तक नहीं देखा है) के साथ आप metadata और string validations उसी तरह घोषित कर सकते हैं जैसे [Query Parameters और String Validations](query-params-str-validations.md) के साथ। + +और आप numeric validations भी घोषित कर सकते हैं: + +* `gt`: `g`reater `t`han +* `ge`: `g`reater than or `e`qual +* `lt`: `l`ess `t`han +* `le`: `l`ess than or `e`qual + +/// note | नोट + +`Query`, `Path`, और अन्य classes जिन्हें आप बाद में देखेंगे, एक common `Param` class की subclasses हैं। + +वे सभी अतिरिक्त validation और metadata के लिए वही parameters साझा करती हैं जिन्हें आपने देखा है। + +/// + +/// note | तकनीकी विवरण + +जब आप `fastapi` से `Query`, `Path` और अन्य import करते हैं, तो वे वास्तव में functions होते हैं। + +जब उन्हें call किया जाता है, तो वे उसी नाम की classes के instances return करते हैं। + +तो, आप `Query` import करते हैं, जो एक function है। और जब आप इसे call करते हैं, तो यह `Query` नाम की class का एक instance return करता है। + +ये functions इसलिए हैं (classes को सीधे उपयोग करने के बजाय) ताकि आपका editor उनके types के बारे में errors mark न करे। + +इस तरह आप उन errors को ignore करने के लिए custom configurations जोड़े बिना अपने सामान्य editor और coding tools का उपयोग कर सकते हैं। + +/// diff --git a/docs/hi/docs/tutorial/path-params.md b/docs/hi/docs/tutorial/path-params.md new file mode 100644 index 000000000..602ff1212 --- /dev/null +++ b/docs/hi/docs/tutorial/path-params.md @@ -0,0 +1,251 @@ +# Path Parameters { #path-parameters } + +आप Python format strings द्वारा इस्तेमाल किए जाने वाले समान syntax के साथ path "parameters" या "variables" declare कर सकते हैं: + +{* ../../docs_src/path_params/tutorial001_py310.py hl[6:7] *} + +path parameter `item_id` की value आपके function को argument `item_id` के रूप में pass की जाएगी। + +इसलिए, अगर आप यह example run करते हैं और [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo) पर जाते हैं, तो आपको ऐसा response दिखाई देगा: + +```JSON +{"item_id":"foo"} +``` + +## Types के साथ Path parameters { #path-parameters-with-types } + +आप standard Python type annotations का उपयोग करके function में किसी path parameter का type declare कर सकते हैं: + +{* ../../docs_src/path_params/tutorial002_py310.py hl[7] *} + +इस मामले में, `item_id` को `int` declare किया गया है। + +/// tip | सुझाव + +इससे आपको अपने function के अंदर editor support मिलेगा, जिसमें error checks, completion आदि शामिल हैं। + +/// + +## Data conversion { #data-conversion } + +अगर आप यह example run करते हैं और अपने browser में [http://127.0.0.1:8000/items/3](http://127.0.0.1:8000/items/3) खोलते हैं, तो आपको ऐसा response दिखाई देगा: + +```JSON +{"item_id":3} +``` + +/// tip | सुझाव + +ध्यान दें कि आपके function ने जो value प्राप्त की (और return की) वह `3` है, Python `int` के रूप में, न कि string `"3"`। + +तो, उस type declaration के साथ, **FastAPI** आपको automatic request "parsing" देता है। + +/// + +## Data validation { #data-validation } + +लेकिन अगर आप browser में [http://127.0.0.1:8000/items/foo](http://127.0.0.1:8000/items/foo) पर जाते हैं, तो आपको ऐसा अच्छा HTTP error दिखाई देगा: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo" + } + ] +} +``` + +क्योंकि path parameter `item_id` की value `"foo"` थी, जो कि `int` नहीं है। + +अगर आपने `int` के बजाय `float` दिया, तो भी वही error दिखाई देगा, जैसे: [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2) + +/// tip | सुझाव + +तो, उसी Python type declaration के साथ, **FastAPI** आपको data validation देता है। + +ध्यान दें कि error यह भी स्पष्ट रूप से बताता है कि validation किस जगह pass नहीं हुआ। + +यह आपके API के साथ interact करने वाले code को develop और debug करते समय बेहद मददगार होता है। + +/// + +## Documentation { #documentation } + +और जब आप अपने browser में [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) खोलते हैं, तो आपको ऐसा automatic, interactive, API documentation दिखाई देगा: + + + +/// tip | सुझाव + +फिर से, बस उसी Python type declaration के साथ, **FastAPI** आपको automatic, interactive documentation देता है (Swagger UI को integrate करते हुए)। + +ध्यान दें कि path parameter को integer के रूप में declare किया गया है। + +/// + +## Standard-आधारित लाभ, वैकल्पिक documentation { #standards-based-benefits-alternative-documentation } + +और क्योंकि generate किया गया schema [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md) standard से है, इसलिए कई compatible tools हैं। + +इसी वजह से, **FastAPI** स्वयं एक वैकल्पिक API documentation प्रदान करता है (ReDoc का उपयोग करते हुए), जिसे आप [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc) पर access कर सकते हैं: + + + +इसी तरह, कई compatible tools हैं। इनमें कई भाषाओं के लिए code generation tools भी शामिल हैं। + +## Pydantic { #pydantic } + +सारा data validation अंदरूनी तौर पर [Pydantic](https://docs.pydantic.dev/) द्वारा किया जाता है, इसलिए आपको इसके सभी लाभ मिलते हैं। और आप जानते हैं कि आप अच्छे हाथों में हैं। + +आप `str`, `float`, `bool` और कई अन्य जटिल data types के साथ वही type declarations इस्तेमाल कर सकते हैं। + +इनमें से कई को tutorial के अगले chapters में explore किया गया है। + +## क्रम मायने रखता है { #order-matters } + +*path operations* बनाते समय, आपको ऐसी स्थितियाँ मिल सकती हैं जहाँ आपके पास एक fixed path हो। + +जैसे `/users/me`, मान लें कि यह current user के बारे में data प्राप्त करने के लिए है। + +और फिर आपके पास `/users/{user_id}` path भी हो सकता है, किसी specific user के बारे में किसी user ID से data प्राप्त करने के लिए। + +क्योंकि *path operations* का evaluation क्रम में किया जाता है, आपको यह सुनिश्चित करना होगा कि `/users/me` के लिए path, `/users/{user_id}` वाले path से पहले declare किया गया हो: + +{* ../../docs_src/path_params/tutorial003_py310.py hl[6,11] *} + +अन्यथा, `/users/{user_id}` के लिए path `/users/me` से भी match करेगा, यह "सोचते हुए" कि उसे `user_id` parameter मिल रहा है जिसकी value `"me"` है। + +इसी तरह, आप किसी path operation को फिर से define नहीं कर सकते: + +{* ../../docs_src/path_params/tutorial003b_py310.py hl[6,11] *} + +पहला वाला हमेशा इस्तेमाल किया जाएगा क्योंकि path पहले match करता है। + +## पहले से तय values { #predefined-values } + +अगर आपके पास ऐसा *path operation* है जो एक *path parameter* प्राप्त करता है, लेकिन आप चाहते हैं कि संभव valid *path parameter* values पहले से तय हों, तो आप standard Python `Enum` का उपयोग कर सकते हैं। + +### एक `Enum` class बनाएं { #create-an-enum-class } + +`Enum` import करें और एक sub-class बनाएं जो `str` और `Enum` से inherit करती हो। + +`str` से inherit करने पर API docs यह जान पाएंगे कि values का type `string` होना चाहिए और उन्हें सही तरह से render कर पाएंगे। + +फिर fixed values के साथ class attributes बनाएं, जो उपलब्ध valid values होंगी: + +{* ../../docs_src/path_params/tutorial005_py310.py hl[1,6:9] *} + +/// tip | सुझाव + +अगर आप सोच रहे हैं, "AlexNet", "ResNet", और "LeNet" बस Machine Learning models के नाम हैं। + +/// + +### एक *path parameter* declare करें { #declare-a-path-parameter } + +फिर आपके द्वारा बनाई गई enum class (`ModelName`) का उपयोग करके type annotation के साथ एक *path parameter* बनाएं: + +{* ../../docs_src/path_params/tutorial005_py310.py hl[16] *} + +### Docs देखें { #check-the-docs } + +क्योंकि *path parameter* के लिए उपलब्ध values पहले से तय हैं, interactive docs उन्हें अच्छे से दिखा सकते हैं: + + + +### Python *enumerations* के साथ काम करना { #working-with-python-enumerations } + +*path parameter* की value एक *enumeration member* होगी। + +#### *Enumeration members* की तुलना करें { #compare-enumeration-members } + +आप इसकी तुलना अपने बनाए हुए enum `ModelName` में मौजूद *enumeration member* से कर सकते हैं: + +{* ../../docs_src/path_params/tutorial005_py310.py hl[17] *} + +#### *Enumeration value* प्राप्त करें { #get-the-enumeration-value } + +आप `model_name.value` का उपयोग करके actual value (इस मामले में एक `str`) प्राप्त कर सकते हैं, या सामान्य रूप से, `your_enum_member.value`: + +{* ../../docs_src/path_params/tutorial005_py310.py hl[20] *} + +/// tip | सुझाव + +आप `ModelName.lenet.value` के साथ value `"lenet"` भी access कर सकते हैं। + +/// + +#### *Enumeration members* return करें { #return-enumeration-members } + +आप अपने *path operation* से *enum members* return कर सकते हैं, यहाँ तक कि JSON body में nested भी (जैसे एक `dict`)। + +Client को return करने से पहले उन्हें उनकी संबंधित values (इस मामले में strings) में convert कर दिया जाएगा: + +{* ../../docs_src/path_params/tutorial005_py310.py hl[18,21,23] *} + +अपने client में आपको ऐसा JSON response मिलेगा: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Paths रखने वाले Path parameters { #path-parameters-containing-paths } + +मान लें आपके पास path `/files/{file_path}` के साथ एक *path operation* है। + +लेकिन आपको `file_path` में स्वयं एक *path* रखना है, जैसे `home/johndoe/myfile.txt`। + +तो, उस file के लिए URL कुछ ऐसा होगा: `/files/home/johndoe/myfile.txt`। + +### OpenAPI support { #openapi-support } + +OpenAPI किसी *path parameter* को उसके अंदर एक *path* रखने के लिए declare करने का तरीका support नहीं करता, क्योंकि इससे ऐसे scenarios बन सकते हैं जिन्हें test और define करना कठिन हो। + +फिर भी, आप **FastAPI** में Starlette के internal tools में से एक का उपयोग करके यह कर सकते हैं। + +और docs फिर भी काम करेंगे, हालांकि ऐसा कोई documentation नहीं जोड़ेंगे जो बताए कि parameter में path होना चाहिए। + +### Path convertor { #path-convertor } + +Starlette से सीधे एक option का उपयोग करके, आप इस तरह के URL का उपयोग करते हुए एक *path* रखने वाला *path parameter* declare कर सकते हैं: + +``` +/files/{file_path:path} +``` + +इस मामले में, parameter का नाम `file_path` है, और आखिरी हिस्सा, `:path`, इसे बताता है कि parameter किसी भी *path* से match करना चाहिए। + +तो, आप इसे इसके साथ इस्तेमाल कर सकते हैं: + +{* ../../docs_src/path_params/tutorial004_py310.py hl[6] *} + +/// tip | सुझाव + +आपको parameter में `/home/johndoe/myfile.txt` रखना पड़ सकता है, leading slash (`/`) के साथ। + +उस मामले में, URL होगा: `/files//home/johndoe/myfile.txt`, `files` और `home` के बीच double slash (`//`) के साथ। + +/// + +## Recap { #recap } + +**FastAPI** के साथ, छोटे, सहज और standard Python type declarations का उपयोग करके, आपको मिलता है: + +* Editor support: error checks, autocompletion आदि। +* Data "parsing" +* Data validation +* API annotation और automatic documentation + +और आपको इन्हें केवल एक बार declare करना होता है। + +वैकल्पिक frameworks की तुलना में **FastAPI** का शायद यही मुख्य दिखने वाला लाभ है (raw performance के अलावा)। diff --git a/docs/hi/docs/tutorial/query-param-models.md b/docs/hi/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..1727b7654 --- /dev/null +++ b/docs/hi/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# Query Parameter Models { #query-parameter-models } + +अगर आपके पास संबंधित **query parameters** का एक समूह है, तो आप उन्हें declare करने के लिए एक **Pydantic model** बना सकते हैं। + +इससे आप **model को फिर से उपयोग** कर पाएँगे, **कई जगहों** पर, और साथ ही सभी parameters के लिए validations और metadata एक साथ declare कर पाएँगे। 😎 + +/// note | नोट + +यह FastAPI version `0.115.0` से supported है। 🤓 + +/// + +## Pydantic Model के साथ Query Parameters { #query-parameters-with-a-pydantic-model } + +जिन **query parameters** की आपको ज़रूरत है उन्हें एक **Pydantic model** में declare करें, और फिर parameter को `Query` के रूप में declare करें: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI** request में मौजूद **query parameters** से **हर field** के लिए data **extract** करेगा और आपको वह Pydantic model देगा जिसे आपने define किया है। + +## Docs देखें { #check-the-docs } + +आप `/docs` पर docs UI में query parameters देख सकते हैं: + +
+ +
+ +## Extra Query Parameters को Forbid करें { #forbid-extra-query-parameters } + +कुछ विशेष use cases में (शायद बहुत आम नहीं), आप उन query parameters को **restrict** करना चाह सकते हैं जिन्हें आप receive करना चाहते हैं। + +आप किसी भी `extra` fields को `forbid` करने के लिए Pydantic की model configuration का उपयोग कर सकते हैं: + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +अगर कोई client **query parameters** में कुछ **extra** data भेजने की कोशिश करता है, तो उसे एक **error** response मिलेगा। + +उदाहरण के लिए, अगर client `plumbus` value के साथ `tool` query parameter भेजने की कोशिश करता है, जैसे: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +उसे एक **error** response मिलेगा जो बताएगा कि query parameter `tool` allowed नहीं है: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## सारांश { #summary } + +आप **FastAPI** में **query parameters** declare करने के लिए **Pydantic models** का उपयोग कर सकते हैं। 😎 + +/// tip | सुझाव + +Spoiler alert: आप cookies और headers declare करने के लिए भी Pydantic models का उपयोग कर सकते हैं, लेकिन आप इसके बारे में tutorial में बाद में पढ़ेंगे। 🤫 + +/// diff --git a/docs/hi/docs/tutorial/query-params-str-validations.md b/docs/hi/docs/tutorial/query-params-str-validations.md new file mode 100644 index 000000000..05f2634a7 --- /dev/null +++ b/docs/hi/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,450 @@ +# Query Parameters और String Validations { #query-parameters-and-string-validations } + +**FastAPI** आपको अपने parameters के लिए अतिरिक्त जानकारी और validation declare करने देता है। + +इस application को example के रूप में लेते हैं: + +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} + +query parameter `q` का type `str | None` है, इसका मतलब है कि यह type `str` का है लेकिन `None` भी हो सकता है, और वास्तव में, default value `None` है, इसलिए FastAPI जान जाएगा कि यह required नहीं है। + +/// note | नोट + +FastAPI जान जाएगा कि `q` की value required नहीं है क्योंकि default value `= None` है। + +`str | None` होने से आपका editor आपको बेहतर support दे पाएगा और errors detect कर पाएगा। + +/// + +## अतिरिक्त validation { #additional-validation } + +हम यह enforce करने जा रहे हैं कि भले ही `q` optional हो, जब भी यह provide किया जाए, **इसकी length 50 characters से अधिक न हो**। + +### `Query` और `Annotated` import करें { #import-query-and-annotated } + +इसे हासिल करने के लिए, पहले import करें: + +* `fastapi` से `Query` +* `typing` से `Annotated` + +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[1,3] *} + +/// note | नोट + +FastAPI ने version 0.95.0 में `Annotated` के लिए support जोड़ा (और इसकी recommendation शुरू की)। + +अगर आपके पास पुराना version है, तो `Annotated` use करने की कोशिश करने पर आपको errors मिलेंगे। + +`Annotated` use करने से पहले सुनिश्चित करें कि आप [FastAPI version Upgrade करें](../deployment/versions.md#upgrading-the-fastapi-versions) कम से कम 0.95.1 तक। + +/// + +## `q` parameter के type में `Annotated` use करें { #use-annotated-in-the-type-for-the-q-parameter } + +याद है मैंने आपको पहले बताया था कि [Python Types Intro](../python-types.md#type-hints-with-metadata-annotations) में `Annotated` का उपयोग आपके parameters में metadata जोड़ने के लिए किया जा सकता है? + +अब इसे FastAPI के साथ use करने का समय है। 🚀 + +हमारे पास यह type annotation था: + +```Python +q: str | None = None +``` + +हम इसे `Annotated` के साथ wrap करेंगे, तो यह बन जाता है: + +```Python +q: Annotated[str | None] = None +``` + +इन दोनों versions का मतलब एक ही है, `q` एक parameter है जो `str` या `None` हो सकता है, और default रूप से, यह `None` है। + +अब मज़ेदार चीज़ों पर चलते हैं। 🎉 + +## `q` parameter में `Annotated` में `Query` जोड़ें { #add-query-to-annotated-in-the-q-parameter } + +अब जब हमारे पास यह `Annotated` है जहाँ हम अधिक जानकारी रख सकते हैं (इस case में कुछ अतिरिक्त validation), `Annotated` के अंदर `Query` जोड़ें, और parameter `max_length` को `50` पर set करें: + +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} + +ध्यान दें कि default value अभी भी `None` है, इसलिए parameter अभी भी optional है। + +लेकिन अब, `Annotated` के अंदर `Query(max_length=50)` होने से, हम FastAPI को बता रहे हैं कि हम चाहते हैं कि इस value के लिए **अतिरिक्त validation** हो, हम चाहते हैं कि इसमें अधिकतम 50 characters हों। 😎 + +/// tip | टिप + +यहाँ हम `Query()` use कर रहे हैं क्योंकि यह एक **query parameter** है। बाद में हम `Path()`, `Body()`, `Header()`, और `Cookie()` जैसे अन्य देखेंगे, जो `Query()` जैसे ही arguments accept करते हैं। + +/// + +FastAPI अब: + +* data को **Validate** करेगा यह सुनिश्चित करते हुए कि max length 50 characters है +* जब data valid नहीं होगा तो client के लिए **clear error** दिखाएगा +* OpenAPI schema *path operation* में parameter को **Document** करेगा (ताकि यह **automatic docs UI** में दिखाई दे) + +## Alternative (पुराना): default value के रूप में `Query` { #alternative-old-query-as-the-default-value } + +FastAPI के पिछले versions (0.95.0 से पहले) में आपको अपने parameter की default value के रूप में `Query` use करना required था, बजाय इसे `Annotated` में रखने के, इसकी अच्छी संभावना है कि आपको आसपास ऐसा code दिखेगा, इसलिए मैं आपको इसे समझाऊंगा। + +/// tip | टिप + +नए code के लिए और जब भी संभव हो, ऊपर समझाए अनुसार `Annotated` use करें। इसके कई फायदे हैं (नीचे समझाए गए हैं) और कोई नुकसान नहीं। 🍰 + +/// + +इस तरह आप अपने function parameter की default value के रूप में `Query()` use करेंगे, parameter `max_length` को 50 पर set करते हुए: + +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} + +चूँकि इस case में (`Annotated` use किए बिना) हमें function में default value `None` को `Query()` से replace करना होता है, अब हमें parameter `Query(default=None)` के साथ default value set करनी होगी, यह उस default value को define करने का वही उद्देश्य पूरा करता है (कम से कम FastAPI के लिए)। + +तो: + +```Python +q: str | None = Query(default=None) +``` + +...parameter को optional बनाता है, `None` की default value के साथ, बिल्कुल इसके समान: + + +```Python +q: str | None = None +``` + +लेकिन `Query` version इसे स्पष्ट रूप से query parameter के रूप में declare करता है। + +फिर, हम `Query` को और parameters pass कर सकते हैं। इस case में, `max_length` parameter जो strings पर apply होता है: + +```Python +q: str | None = Query(default=None, max_length=50) +``` + +यह data को validate करेगा, data valid न होने पर clear error दिखाएगा, और OpenAPI schema *path operation* में parameter को document करेगा। + +### default value के रूप में या `Annotated` में `Query` { #query-as-the-default-value-or-in-annotated } + +ध्यान रखें कि `Annotated` के अंदर `Query` use करते समय आप `Query` के लिए `default` parameter use नहीं कर सकते। + +इसके बजाय, function parameter की वास्तविक default value use करें। अन्यथा, यह inconsistent होगा। + +उदाहरण के लिए, इसकी अनुमति नहीं है: + +```Python +q: Annotated[str, Query(default="rick")] = "morty" +``` + +...क्योंकि यह clear नहीं है कि default value `"rick"` होनी चाहिए या `"morty"`। + +तो, आप use करेंगे (preferably): + +```Python +q: Annotated[str, Query()] = "rick" +``` + +...या पुराने code bases में आपको मिलेगा: + +```Python +q: str = Query(default="rick") +``` + +### `Annotated` के फायदे { #advantages-of-annotated } + +function parameters में default value के बजाय **`Annotated` use करने की recommendation है**, यह कई कारणों से **बेहतर** है। 🤓 + +**function parameter** की **default** value ही **वास्तविक default** value है, यह सामान्य रूप से Python के साथ अधिक intuitive है। 😌 + +आप उसी function को FastAPI के बिना **अन्य जगहों** पर **call** कर सकते हैं, और यह **उम्मीद के अनुसार काम** करेगा। अगर कोई **required** parameter है (बिना default value के), तो आपका **editor** आपको error के साथ बता देगा, **Python** भी required parameter pass किए बिना इसे run करने पर complain करेगा। + +जब आप `Annotated` use नहीं करते और इसके बजाय **(पुराना) default value style** use करते हैं, अगर आप उस function को FastAPI के बिना **अन्य जगहों** पर call करते हैं, तो आपको function को सही से काम कराने के लिए arguments pass करना **याद रखना** होगा, अन्यथा values आपकी अपेक्षा से अलग होंगी (जैसे `str` के बजाय `QueryInfo` या कुछ similar)। और आपका editor complain नहीं करेगा, और Python भी उस function को run करते समय complain नहीं करेगा, केवल तब जब अंदर के operations error दें। + +क्योंकि `Annotated` में एक से अधिक metadata annotation हो सकते हैं, अब आप उसी function को अन्य tools के साथ भी use कर सकते हैं, जैसे [Typer](https://typer.tiangolo.com/)। 🚀 + +## और validations जोड़ें { #add-more-validations } + +आप parameter `min_length` भी जोड़ सकते हैं: + +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} + +## regular expressions जोड़ें { #add-regular-expressions } + +आप एक regular expression `pattern` define कर सकते हैं जिससे parameter match करना चाहिए: + +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} + +यह specific regular expression pattern check करता है कि received parameter value: + +* `^`: निम्न characters से शुरू होती है, पहले कोई characters नहीं हैं। +* `fixedquery`: exact value `fixedquery` रखती है। +* `$`: वहीं समाप्त होती है, `fixedquery` के बाद कोई और characters नहीं हैं। + +अगर आप इन सभी **"regular expression"** ideas से खोया हुआ महसूस करते हैं, तो चिंता न करें। यह कई लोगों के लिए कठिन topic है। आप अभी regular expressions की जरूरत के बिना भी बहुत कुछ कर सकते हैं। + +अब आप जानते हैं कि जब भी आपको इनकी जरूरत हो, आप इन्हें **FastAPI** में use कर सकते हैं। + +## Default values { #default-values } + +बेशक, आप `None` के अलावा default values use कर सकते हैं। + +मान लीजिए कि आप `q` query parameter को `3` की `min_length` और `"fixedquery"` की default value के साथ declare करना चाहते हैं: + +{* ../../docs_src/query_params_str_validations/tutorial005_an_py310.py hl[9] *} + +/// note | नोट + +`None` सहित किसी भी type की default value होना parameter को optional (not required) बनाता है। + +/// + +## Required parameters { #required-parameters } + +जब हमें अधिक validations या metadata declare करने की जरूरत नहीं होती, तो हम default value declare न करके ही `q` query parameter को required बना सकते हैं, जैसे: + +```Python +q: str +``` + +इसके बजाय: + +```Python +q: str | None = None +``` + +लेकिन अब हम इसे `Query` के साथ declare कर रहे हैं, उदाहरण के लिए ऐसे: + +```Python +q: Annotated[str | None, Query(min_length=3)] = None +``` + +तो, जब आपको `Query` use करते हुए किसी value को required के रूप में declare करना हो, तो आप बस default value declare न करें: + +{* ../../docs_src/query_params_str_validations/tutorial006_an_py310.py hl[9] *} + +### Required, `None` हो सकता है { #required-can-be-none } + +आप declare कर सकते हैं कि parameter `None` accept कर सकता है, लेकिन फिर भी यह required है। यह clients को value भेजने के लिए मजबूर करेगा, भले ही value `None` हो। + +ऐसा करने के लिए, आप declare कर सकते हैं कि `None` एक valid type है लेकिन बस default value declare न करें: + +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} + +## Query parameter list / multiple values { #query-parameter-list-multiple-values } + +जब आप query parameter को स्पष्ट रूप से `Query` के साथ define करते हैं तो आप इसे values की list receive करने के लिए भी declare कर सकते हैं, या दूसरे शब्दों में, multiple values receive करने के लिए। + +उदाहरण के लिए, query parameter `q` declare करने के लिए जो URL में कई बार आ सकता है, आप लिख सकते हैं: + +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} + +फिर, ऐसे URL के साथ: + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +आप multiple `q` *query parameters* की values (`foo` और `bar`) को अपने *path operation function* के अंदर Python `list` में, *function parameter* `q` में receive करेंगे। + +तो, उस URL का response होगा: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +/// tip | टिप + +ऊपर के example की तरह, `list` type वाला query parameter declare करने के लिए, आपको स्पष्ट रूप से `Query` use करना होगा, अन्यथा इसे request body के रूप में interpret किया जाएगा। + +/// + +interactive API docs accordingly update होंगे, ताकि multiple values allow हो सकें: + + + +### Defaults के साथ Query parameter list / multiple values { #query-parameter-list-multiple-values-with-defaults } + +अगर कोई values provide नहीं की गई हैं, तो आप values की default `list` भी define कर सकते हैं: + +{* ../../docs_src/query_params_str_validations/tutorial012_an_py310.py hl[9] *} + +अगर आप यहाँ जाते हैं: + +``` +http://localhost:8000/items/ +``` + +`q` का default होगा: `["foo", "bar"]` और आपका response होगा: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +#### केवल `list` use करना { #using-just-list } + +आप `list[str]` के बजाय सीधे `list` भी use कर सकते हैं: + +{* ../../docs_src/query_params_str_validations/tutorial013_an_py310.py hl[9] *} + +/// note | नोट + +ध्यान रखें कि इस case में, FastAPI list की contents check नहीं करेगा। + +उदाहरण के लिए, `list[int]` check (और document) करेगा कि list की contents integers हैं। लेकिन केवल `list` ऐसा नहीं करेगा। + +/// + +## अधिक metadata declare करें { #declare-more-metadata } + +आप parameter के बारे में अधिक जानकारी जोड़ सकते हैं। + +वह जानकारी generated OpenAPI में शामिल होगी और documentation user interfaces और external tools द्वारा use की जाएगी। + +/// note | नोट + +ध्यान रखें कि अलग-अलग tools में OpenAPI support के अलग-अलग levels हो सकते हैं। + +उनमें से कुछ अभी declare की गई सारी extra information नहीं दिखा सकते, हालांकि अधिकतर cases में, missing feature पहले से ही development के लिए planned है। + +/// + +आप एक `title` जोड़ सकते हैं: + +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} + +और एक `description`: + +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} + +## Alias parameters { #alias-parameters } + +कल्पना करें कि आप parameter को `item-query` बनाना चाहते हैं। + +जैसे: + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +लेकिन `item-query` valid Python variable name नहीं है। + +सबसे निकटतम `item_query` होगा। + +लेकिन आपको अभी भी यह exactly `item-query` ही चाहिए... + +तब आप एक `alias` declare कर सकते हैं, और वही alias parameter value खोजने के लिए use किया जाएगा: + +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} + +## Parameters को deprecate करना { #deprecating-parameters } + +अब मान लीजिए कि आपको यह parameter अब पसंद नहीं है। + +आपको इसे कुछ समय के लिए वहीं छोड़ना होगा क्योंकि clients इसे use कर रहे हैं, लेकिन आप चाहते हैं कि docs इसे स्पष्ट रूप से deprecated के रूप में दिखाएँ। + +फिर parameter `deprecated=True` को `Query` में pass करें: + +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} + +docs इसे इस तरह दिखाएँगे: + + + +## OpenAPI से parameters exclude करें { #exclude-parameters-from-openapi } + +generated OpenAPI schema से query parameter exclude करने के लिए (और इस प्रकार, automatic documentation systems से), `Query` के parameter `include_in_schema` को `False` पर set करें: + +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} + +## Custom Validation { #custom-validation } + +ऐसे cases हो सकते हैं जहाँ आपको कुछ **custom validation** करना पड़े जो ऊपर दिखाए गए parameters से नहीं किया जा सकता। + +ऐसे cases में, आप एक **custom validator function** use कर सकते हैं जो normal validation के बाद apply होता है (जैसे value के `str` होने की validation के बाद)। + +आप इसे `Annotated` के अंदर [Pydantic के `AfterValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-after-validator) का उपयोग करके हासिल कर सकते हैं। + +/// tip | टिप + +Pydantic में [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/validators/#field-before-validator) और अन्य भी हैं। 🤓 + +/// + +उदाहरण के लिए, यह custom validator check करता है कि item ID किसी ISBN book number के लिए `isbn-` से शुरू होती है या किसी IMDB movie URL ID के लिए `imdb-` से: + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *} + +/// note | नोट + +यह Pydantic version 2 या उससे ऊपर के साथ available है। 😎 + +/// + +/// tip | टिप + +अगर आपको किसी भी प्रकार की validation करनी है जिसके लिए किसी **external component** से communicate करना required है, जैसे database या कोई अन्य API, तो आपको इसके बजाय **FastAPI Dependencies** use करनी चाहिए, आप इनके बारे में बाद में सीखेंगे। + +ये custom validators उन चीज़ों के लिए हैं जिन्हें request में provide किए गए **सिर्फ** **उसी data** से check किया जा सकता है। + +/// + +### उस Code को समझें { #understand-that-code } + +महत्वपूर्ण बात बस **`Annotated` के अंदर एक function के साथ `AfterValidator` use करना** है। आप चाहें तो इस part को skip कर सकते हैं। 🤸 + +--- + +लेकिन अगर आप इस specific code example के बारे में curious हैं और अभी भी entertained हैं, तो यहाँ कुछ extra details हैं। + +#### `value.startswith()` के साथ String { #string-with-value-startswith } + +क्या आपने ध्यान दिया? `value.startswith()` use करने वाली string tuple ले सकती है, और यह tuple की हर value check करेगी: + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *} + +#### एक Random Item { #a-random-item } + +`data.items()` के साथ हमें tuples वाला एक iterable object मिलता है जिसमें हर dictionary item के लिए key और value होती है। + +हम इस iterable object को `list(data.items())` के साथ proper `list` में convert करते हैं। + +फिर `random.choice()` के साथ हम list से एक **random value** प्राप्त कर सकते हैं, तो हमें `(id, name)` वाला tuple मिलता है। यह कुछ ऐसा होगा `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`। + +फिर हम tuple की **उन दो values को assign** करते हैं variables `id` और `name` को। + +तो, अगर user ने item ID provide नहीं की, तब भी उन्हें एक random suggestion receive होगा। + +...हम यह सब **एक single simple line** में करते हैं। 🤯 क्या आपको Python पसंद नहीं है? 🐍 + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *} + +## Recap { #recap } + +आप अपने parameters के लिए अतिरिक्त validations और metadata declare कर सकते हैं। + +Generic validations और metadata: + +* `alias` +* `title` +* `description` +* `deprecated` + +Strings के लिए specific validations: + +* `min_length` +* `max_length` +* `pattern` + +`AfterValidator` का उपयोग करके custom validations। + +इन examples में आपने देखा कि `str` values के लिए validations कैसे declare करें। + +अगले chapters देखें ताकि आप सीख सकें कि numbers जैसे अन्य types के लिए validations कैसे declare करें। diff --git a/docs/hi/docs/tutorial/query-params.md b/docs/hi/docs/tutorial/query-params.md new file mode 100644 index 000000000..bc8573179 --- /dev/null +++ b/docs/hi/docs/tutorial/query-params.md @@ -0,0 +1,188 @@ +# Query Parameters { #query-parameters } + +जब आप ऐसे दूसरे function parameters declare करते हैं जो path parameters का हिस्सा नहीं हैं, तो उन्हें अपने-आप "query" parameters के रूप में समझा जाता है। + +{* ../../docs_src/query_params/tutorial001_py310.py hl[9] *} + +query उन key-value pairs का सेट है जो URL में `?` के बाद आते हैं, और `&` characters से अलग किए जाते हैं। + +उदाहरण के लिए, इस URL में: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +...query parameters हैं: + +* `skip`: `0` value के साथ +* `limit`: `10` value के साथ + +क्योंकि वे URL का हिस्सा हैं, वे "स्वाभाविक रूप से" strings होते हैं। + +लेकिन जब आप उन्हें Python types के साथ declare करते हैं (ऊपर दिए गए उदाहरण में, `int` के रूप में), तो उन्हें उस type में convert किया जाता है और उसके अनुसार validate किया जाता है। + +path parameters पर लागू होने वाली सभी वही प्रक्रियाएँ query parameters पर भी लागू होती हैं: + +* Editor support (स्पष्ट रूप से) +* Data "parsing" +* Data validation +* Automatic documentation + +## Defaults { #defaults } + +क्योंकि query parameters किसी path का fixed हिस्सा नहीं होते, वे optional हो सकते हैं और उनके default values हो सकते हैं। + +ऊपर दिए गए उदाहरण में उनके default values `skip=0` और `limit=10` हैं। + +तो, इस 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 +``` + +तो आपके function में parameter values होंगी: + +* `skip=20`: क्योंकि आपने इसे URL में सेट किया है +* `limit=10`: क्योंकि वह default value था + +## Optional parameters { #optional-parameters } + +उसी तरह, आप optional query parameters declare कर सकते हैं, उनका default `None` सेट करके: + +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} + +इस मामले में, function parameter `q` optional होगा, और default रूप से `None` होगा। + +/// tip | सुझाव + +यह भी ध्यान दें कि **FastAPI** इतना smart है कि यह पहचान लेता है कि path parameter `item_id` एक path parameter है और `q` नहीं है, इसलिए, यह एक query parameter है। + +/// + +## Query parameter type conversion { #query-parameter-type-conversion } + +आप `bool` types भी declare कर सकते हैं, और वे convert हो जाएँगे: + +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} + +इस मामले में, अगर आप इस पर जाते हैं: + +``` +http://127.0.0.1:8000/items/foo?short=1 +``` + +या + +``` +http://127.0.0.1:8000/items/foo?short=True +``` + +या + +``` +http://127.0.0.1:8000/items/foo?short=true +``` + +या + +``` +http://127.0.0.1:8000/items/foo?short=on +``` + +या + +``` +http://127.0.0.1:8000/items/foo?short=yes +``` + +या कोई भी दूसरी case variation (uppercase, पहले अक्षर को uppercase, आदि), आपका function parameter `short` को `True` के `bool` value के साथ देखेगा। अन्यथा `False` के रूप में। + + +## कई path और query parameters { #multiple-path-and-query-parameters } + +आप एक ही समय में कई path parameters और query parameters declare कर सकते हैं, **FastAPI** जानता है कि कौन सा कौन है। + +और आपको उन्हें किसी विशेष order में declare करने की ज़रूरत नहीं है। + +उन्हें नाम से detect किया जाएगा: + +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} + +## Required query parameters { #required-query-parameters } + +जब आप non-path parameters के लिए default value declare करते हैं (अभी तक, हमने केवल query parameters देखे हैं), तो वह required नहीं होता। + +अगर आप कोई specific value नहीं जोड़ना चाहते लेकिन बस उसे optional बनाना चाहते हैं, तो default को `None` के रूप में सेट करें। + +लेकिन जब आप किसी query parameter को required बनाना चाहते हैं, तो आप बस कोई default value declare न करें: + +{* ../../docs_src/query_params/tutorial005_py310.py hl[6:7] *} + +यहाँ query parameter `needy` type `str` का एक required query parameter है। + +अगर आप अपने browser में इस तरह का URL खोलते हैं: + +``` +http://127.0.0.1:8000/items/foo-item +``` + +...required parameter `needy` जोड़े बिना, तो आपको इस तरह की error दिखाई देगी: + +```JSON +{ + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null + } + ] +} +``` + +क्योंकि `needy` एक required parameter है, आपको इसे URL में सेट करना होगा: + +``` +http://127.0.0.1:8000/items/foo-item?needy=sooooneedy +``` + +...यह काम करेगा: + +```JSON +{ + "item_id": "foo-item", + "needy": "sooooneedy" +} +``` + +और निश्चित रूप से, आप कुछ parameters को required, कुछ को default value वाला, और कुछ को पूरी तरह optional define कर सकते हैं: + +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} + +इस मामले में, 3 query parameters हैं: + +* `needy`, एक required `str`. +* `skip`, default value `0` के साथ एक `int`. +* `limit`, एक optional `int`. + +/// tip | सुझाव + +आप `Enum`s को भी उसी तरह use कर सकते हैं जैसे [Path Parameters](path-params.md#predefined-values) के साथ। + +/// diff --git a/docs/hi/docs/tutorial/request-files.md b/docs/hi/docs/tutorial/request-files.md new file mode 100644 index 000000000..4a79ca2b9 --- /dev/null +++ b/docs/hi/docs/tutorial/request-files.md @@ -0,0 +1,176 @@ +# Request Files { #request-files } + +आप client द्वारा अपलोड की जाने वाली files को `File` का उपयोग करके परिभाषित कर सकते हैं। + +/// note | नोट + +अपलोड की गई files प्राप्त करने के लिए, पहले [`python-multipart`](https://github.com/Kludex/python-multipart) install करें। + +सुनिश्चित करें कि आप एक [virtual environment](../virtual-environments.md) बनाते हैं, उसे activate करते हैं, और फिर इसे install करते हैं, उदाहरण के लिए: + +```console +$ pip install python-multipart +``` + +ऐसा इसलिए है क्योंकि अपलोड की गई files "form data" के रूप में भेजी जाती हैं। + +/// + +## `File` Import करें { #import-file } + +`fastapi` से `File` और `UploadFile` import करें: + +{* ../../docs_src/request_files/tutorial001_an_py310.py hl[3] *} + +## `File` Parameters परिभाषित करें { #define-file-parameters } + +file parameters उसी तरह बनाएं जैसे आप `Body` या `Form` के लिए बनाते हैं: + +{* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *} + +/// note | नोट + +`File` एक class है जो सीधे `Form` से inherit करती है। + +लेकिन याद रखें कि जब आप `fastapi` से `Query`, `Path`, `File` और अन्य import करते हैं, तो वे वास्तव में functions होते हैं जो विशेष classes return करते हैं। + +/// + +/// tip | सुझाव + +File bodies घोषित करने के लिए, आपको `File` का उपयोग करना होगा, क्योंकि अन्यथा parameters को query parameters या body (JSON) parameters के रूप में समझा जाएगा। + +/// + +files "form data" के रूप में अपलोड की जाएंगी। + +यदि आप अपने *path operation function* parameter का type `bytes` के रूप में घोषित करते हैं, तो **FastAPI** आपके लिए file पढ़ेगा और आपको सामग्री `bytes` के रूप में प्राप्त होगी। + +ध्यान रखें कि इसका मतलब है कि पूरी सामग्री memory में संग्रहीत होगी। यह छोटी files के लिए अच्छी तरह काम करेगा। + +लेकिन कई मामलों में आपको `UploadFile` का उपयोग करने से लाभ हो सकता है। + +## `UploadFile` के साथ File Parameters { #file-parameters-with-uploadfile } + +`UploadFile` type के साथ file parameter परिभाषित करें: + +{* ../../docs_src/request_files/tutorial001_an_py310.py hl[14] *} + +`bytes` की तुलना में `UploadFile` का उपयोग करने के कई फायदे हैं: + +* आपको parameter के default value में `File()` का उपयोग नहीं करना पड़ता। +* यह एक "spooled" file का उपयोग करता है: + * एक file जो अधिकतम size limit तक memory में संग्रहीत होती है, और इस limit को पार करने के बाद disk पर संग्रहीत होती है। +* इसका मतलब है कि यह images, videos, बड़े binaries आदि जैसी बड़ी files के लिए सारी memory का उपयोग किए बिना अच्छी तरह काम करेगा। +* आप अपलोड की गई file से metadata प्राप्त कर सकते हैं। +* इसमें [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) `async` interface है। +* यह एक वास्तविक Python [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) object expose करता है जिसे आप सीधे अन्य libraries को पास कर सकते हैं जो file-like object की अपेक्षा करती हैं। + +### `UploadFile` { #uploadfile } + +`UploadFile` में निम्नलिखित attributes होते हैं: + +* `filename`: मूल file name के साथ एक `str` जो अपलोड किया गया था (जैसे `myimage.jpg`)। +* `content_type`: content type (MIME type / media type) के साथ एक `str` (जैसे `image/jpeg`)। +* `file`: एक [`SpooledTemporaryFile`](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) (एक [file-like](https://docs.python.org/3/glossary.html#term-file-like-object) object)। यह वास्तविक Python file object है जिसे आप सीधे अन्य functions या libraries को पास कर सकते हैं जो "file-like" object की अपेक्षा करती हैं। + +`UploadFile` में निम्नलिखित `async` methods होते हैं। ये सभी अंदर से संबंधित file methods को call करते हैं (internal `SpooledTemporaryFile` का उपयोग करके)। + +* `write(data)`: `data` (`str` या `bytes`) को file में लिखता है। +* `read(size)`: file के `size` (`int`) bytes/characters पढ़ता है। +* `seek(offset)`: file में byte position `offset` (`int`) पर जाता है। + * उदाहरण के लिए, `await myfile.seek(0)` file की शुरुआत पर जाएगा। + * यह विशेष रूप से तब उपयोगी है जब आप एक बार `await myfile.read()` चलाते हैं और फिर सामग्री को दोबारा पढ़ने की आवश्यकता होती है। +* `close()`: file को बंद करता है। + +क्योंकि ये सभी methods `async` methods हैं, आपको उन्हें "await" करना होगा। + +उदाहरण के लिए, एक `async` *path operation function* के अंदर आप सामग्री इस तरह प्राप्त कर सकते हैं: + +```Python +contents = await myfile.read() +``` + +यदि आप एक सामान्य `def` *path operation function* के अंदर हैं, तो आप सीधे `UploadFile.file` access कर सकते हैं, उदाहरण के लिए: + +```Python +contents = myfile.file.read() +``` + +/// note | `async` तकनीकी विवरण + +जब आप `async` methods का उपयोग करते हैं, तो **FastAPI** file methods को threadpool में चलाता है और उनके लिए await करता है। + +/// + +/// note | Starlette तकनीकी विवरण + +**FastAPI** का `UploadFile` सीधे **Starlette** के `UploadFile` से inherit करता है, लेकिन **Pydantic** और FastAPI के अन्य भागों के साथ इसे compatible बनाने के लिए कुछ आवश्यक हिस्से जोड़ता है। + +/// + +## "Form Data" क्या है { #what-is-form-data } + +HTML forms (`
`) सामान्यतः data को server पर भेजने के लिए उस data के लिए एक "special" encoding का उपयोग करते हैं, यह JSON से अलग होता है। + +**FastAPI** यह सुनिश्चित करेगा कि उस data को JSON के बजाय सही जगह से पढ़ा जाए। + +/// note | तकनीकी विवरण + +forms से data सामान्यतः "media type" `application/x-www-form-urlencoded` का उपयोग करके encoded होता है जब इसमें files शामिल नहीं होतीं। + +लेकिन जब form में files शामिल होती हैं, तो यह `multipart/form-data` के रूप में encoded होता है। यदि आप `File` का उपयोग करते हैं, तो **FastAPI** जान जाएगा कि उसे body के सही भाग से files प्राप्त करनी हैं। + +यदि आप इन encodings और form fields के बारे में अधिक पढ़ना चाहते हैं, तो [`POST` के लिए MDN web docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) पर जाएं। + +/// + +/// warning | चेतावनी + +आप एक *path operation* में कई `File` और `Form` parameters घोषित कर सकते हैं, लेकिन आप ऐसे `Body` fields भी घोषित नहीं कर सकते जिन्हें आप JSON के रूप में प्राप्त करने की अपेक्षा करते हैं, क्योंकि request में body `application/json` के बजाय `multipart/form-data` का उपयोग करके encoded होगी। + +यह **FastAPI** की limitation नहीं है, यह HTTP protocol का हिस्सा है। + +/// + +## Optional File Upload { #optional-file-upload } + +आप standard type annotations का उपयोग करके और default value `None` set करके file को optional बना सकते हैं: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## अतिरिक्त Metadata के साथ `UploadFile` { #uploadfile-with-additional-metadata } + +आप `UploadFile` के साथ `File()` का भी उपयोग कर सकते हैं, उदाहरण के लिए, अतिरिक्त metadata set करने के लिए: + +{* ../../docs_src/request_files/tutorial001_03_an_py310.py hl[9,15] *} + +## Multiple File Uploads { #multiple-file-uploads } + +एक ही समय में कई files अपलोड करना संभव है। + +वे "form data" का उपयोग करके भेजे गए उसी "form field" से संबंधित होंगी। + +इसका उपयोग करने के लिए, `bytes` या `UploadFile` की list घोषित करें: + +{* ../../docs_src/request_files/tutorial002_an_py310.py hl[10,15] *} + +आपको, जैसा घोषित किया गया है, `bytes` या `UploadFile`s की एक `list` प्राप्त होगी। + +/// note | तकनीकी विवरण + +आप `from starlette.responses import HTMLResponse` का भी उपयोग कर सकते हैं। + +**FastAPI** आपकी सुविधा के लिए, developer के रूप में, वही `starlette.responses` को `fastapi.responses` के रूप में प्रदान करता है। लेकिन उपलब्ध अधिकांश responses सीधे Starlette से आते हैं। + +/// + +### अतिरिक्त Metadata के साथ Multiple File Uploads { #multiple-file-uploads-with-additional-metadata } + +और पहले की तरह ही, आप अतिरिक्त parameters set करने के लिए `File()` का उपयोग कर सकते हैं, यहां तक कि `UploadFile` के लिए भी: + +{* ../../docs_src/request_files/tutorial003_an_py310.py hl[11,18:20] *} + +## Recap { #recap } + +request में अपलोड की जाने वाली files घोषित करने के लिए `File`, `bytes`, और `UploadFile` का उपयोग करें, जिन्हें form data के रूप में भेजा जाता है। diff --git a/docs/hi/docs/tutorial/request-form-models.md b/docs/hi/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..98fc91ac8 --- /dev/null +++ b/docs/hi/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# Form Models { #form-models } + +आप FastAPI में **form fields** declare करने के लिए **Pydantic models** का उपयोग कर सकते हैं। + +/// note | नोट + +forms का उपयोग करने के लिए, पहले [`python-multipart`](https://github.com/Kludex/python-multipart) install करें। + +सुनिश्चित करें कि आप एक [virtual environment](../virtual-environments.md) बनाते हैं, उसे activate करते हैं, और फिर इसे install करते हैं, उदाहरण के लिए: + +```console +$ pip install python-multipart +``` + +/// + +/// note | नोट + +यह FastAPI version `0.113.0` से supported है। 🤓 + +/// + +## Forms के लिए Pydantic Models { #pydantic-models-for-forms } + +आपको बस उन fields के साथ एक **Pydantic model** declare करना है जिन्हें आप **form fields** के रूप में receive करना चाहते हैं, और फिर parameter को `Form` के रूप में declare करना है: + +{* ../../docs_src/request_form_models/tutorial001_an_py310.py hl[9:11,15] *} + +**FastAPI** request में मौजूद **form data** से **हर field** के लिए data **extract** करेगा और आपको वह Pydantic model देगा जिसे आपने define किया है। + +## Docs जाँचें { #check-the-docs } + +आप इसे `/docs` पर docs UI में verify कर सकते हैं: + +
+ +
+ +## Extra Form Fields को मना करें { #forbid-extra-form-fields } + +कुछ खास use cases में (शायद बहुत आम नहीं), आप form fields को केवल उन तक **restrict** करना चाह सकते हैं जो Pydantic model में declare किए गए हैं। और किसी भी **extra** fields को **forbid** करना चाह सकते हैं। + +/// note | नोट + +यह FastAPI version `0.114.0` से supported है। 🤓 + +/// + +आप किसी भी `extra` fields को `forbid` करने के लिए Pydantic की model configuration का उपयोग कर सकते हैं: + +{* ../../docs_src/request_form_models/tutorial002_an_py310.py hl[12] *} + +अगर कोई client कुछ extra data भेजने की कोशिश करता है, तो उन्हें एक **error** response मिलेगा। + +उदाहरण के लिए, अगर client ये form fields भेजने की कोशिश करता है: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +तो उन्हें एक error response मिलेगा जो बताएगा कि field `extra` allowed नहीं है: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## सारांश { #summary } + +आप FastAPI में form fields declare करने के लिए Pydantic models का उपयोग कर सकते हैं। 😎 diff --git a/docs/hi/docs/tutorial/request-forms-and-files.md b/docs/hi/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..c43edae0e --- /dev/null +++ b/docs/hi/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,41 @@ +# Request Forms और Files { #request-forms-and-files } + +आप `File` और `Form` का उपयोग करके files और form fields को एक ही समय में define कर सकते हैं। + +/// note | नोट + +अपलोड की गई files और/या form data प्राप्त करने के लिए, पहले [`python-multipart`](https://github.com/Kludex/python-multipart) install करें। + +सुनिश्चित करें कि आप एक [virtual environment](../virtual-environments.md) बनाएँ, उसे activate करें, और फिर इसे install करें, उदाहरण के लिए: + +```console +$ pip install python-multipart +``` + +/// + +## `File` और `Form` Import करें { #import-file-and-form } + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[3] *} + +## `File` और `Form` parameters define करें { #define-file-and-form-parameters } + +file और form parameters उसी तरह बनाएँ जैसे आप `Body` या `Query` के लिए बनाते हैं: + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py310.py hl[10:12] *} + +files और form fields, form data के रूप में अपलोड किए जाएँगे और आपको files और form fields प्राप्त होंगे। + +और आप कुछ files को `bytes` के रूप में और कुछ को `UploadFile` के रूप में declare कर सकते हैं। + +/// warning | चेतावनी + +आप एक *path operation* में कई `File` और `Form` parameters declare कर सकते हैं, लेकिन आप साथ ही ऐसे `Body` fields declare नहीं कर सकते जिन्हें आप JSON के रूप में प्राप्त करने की अपेक्षा करते हैं, क्योंकि request में body `application/json` के बजाय `multipart/form-data` का उपयोग करके encoded होगी। + +यह **FastAPI** की कोई सीमा नहीं है, यह HTTP protocol का हिस्सा है। + +/// + +## Recap { #recap } + +जब आपको एक ही request में data और files प्राप्त करने की आवश्यकता हो, तो `File` और `Form` को साथ में उपयोग करें। diff --git a/docs/hi/docs/tutorial/request-forms.md b/docs/hi/docs/tutorial/request-forms.md new file mode 100644 index 000000000..32488ec1e --- /dev/null +++ b/docs/hi/docs/tutorial/request-forms.md @@ -0,0 +1,73 @@ +# Form Data { #form-data } + +जब आपको JSON के बजाय form fields प्राप्त करने हों, तो आप `Form` का उपयोग कर सकते हैं। + +/// note | नोट + +forms का उपयोग करने के लिए, पहले [`python-multipart`](https://github.com/Kludex/python-multipart) install करें। + +सुनिश्चित करें कि आप एक [virtual environment](../virtual-environments.md) बनाते हैं, उसे activate करते हैं, और फिर इसे install करते हैं, उदाहरण के लिए: + +```console +$ pip install python-multipart +``` + +/// + +## `Form` Import करें { #import-form } + +`fastapi` से `Form` import करें: + +{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[3] *} + +## `Form` parameters परिभाषित करें { #define-form-parameters } + +form parameters उसी तरह बनाएं जैसे आप `Body` या `Query` के लिए बनाते: + +{* ../../docs_src/request_forms/tutorial001_an_py310.py hl[9] *} + +उदाहरण के लिए, OAuth2 specification का उपयोग जिन तरीकों से किया जा सकता है उनमें से एक में (जिसे "password flow" कहा जाता है) `username` और `password` को form fields के रूप में भेजना required है। + +spec के अनुसार fields के नाम बिल्कुल `username` और `password` होने चाहिए, और उन्हें JSON नहीं, बल्कि form fields के रूप में भेजा जाना चाहिए। + +`Form` के साथ आप वही configurations declare कर सकते हैं जो `Body` (और `Query`, `Path`, `Cookie`) के साथ करते हैं, जिसमें validation, examples, alias (जैसे `username` के बजाय `user-name`), आदि शामिल हैं। + +/// note | नोट + +`Form` एक class है जो सीधे `Body` से inherit करती है। + +/// + +/// tip | टिप + +form bodies declare करने के लिए, आपको स्पष्ट रूप से `Form` का उपयोग करना होगा, क्योंकि इसके बिना parameters को query parameters या body (JSON) parameters के रूप में समझा जाएगा। + +/// + +## "Form Fields" के बारे में { #about-form-fields } + +HTML forms (`
`) आमतौर पर data को server पर भेजने के लिए उस data के लिए एक "special" encoding का उपयोग करते हैं, यह JSON से अलग होता है। + +**FastAPI** यह सुनिश्चित करेगा कि उस data को JSON के बजाय सही जगह से पढ़ा जाए। + +/// note | तकनीकी विवरण + +forms से आने वाला data आमतौर पर "media type" `application/x-www-form-urlencoded` का उपयोग करके encoded होता है। + +लेकिन जब form में files शामिल होती हैं, तो इसे `multipart/form-data` के रूप में encoded किया जाता है। files को handle करने के बारे में आप अगले chapter में पढ़ेंगे। + +अगर आप इन encodings और form fields के बारे में अधिक पढ़ना चाहते हैं, तो [`POST` के लिए MDN web docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) देखें। + +/// + +/// warning | चेतावनी + +आप एक *path operation* में कई `Form` parameters declare कर सकते हैं, लेकिन आप साथ में ऐसे `Body` fields declare नहीं कर सकते जिन्हें आप JSON के रूप में प्राप्त करने की उम्मीद करते हैं, क्योंकि request में body `application/json` के बजाय `application/x-www-form-urlencoded` का उपयोग करके encoded होगी। + +यह **FastAPI** की limitation नहीं है, यह HTTP protocol का हिस्सा है। + +/// + +## Recap { #recap } + +form data input parameters declare करने के लिए `Form` का उपयोग करें। diff --git a/docs/hi/docs/tutorial/response-model.md b/docs/hi/docs/tutorial/response-model.md new file mode 100644 index 000000000..76f7ba4fc --- /dev/null +++ b/docs/hi/docs/tutorial/response-model.md @@ -0,0 +1,344 @@ +# Response Model - Return Type { #response-model-return-type } + +आप response के लिए उपयोग किए जाने वाले type को *path operation function* के **return type** को annotate करके declare कर सकते हैं। + +आप **type annotations** का उपयोग उसी तरह कर सकते हैं जैसे आप function **parameters** में input data के लिए करते हैं, आप Pydantic models, lists, dictionaries, scalar values जैसे integers, booleans, आदि का उपयोग कर सकते हैं। + +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} + +FastAPI इस return type का उपयोग इनके लिए करेगा: + +* लौटाए गए data को **Validate** करना। + * अगर data invalid है (जैसे कि कोई field missing है), तो इसका मतलब है कि *आपके* app code में गड़बड़ी है, वह वह data return नहीं कर रहा जो उसे करना चाहिए, और यह incorrect data return करने के बजाय server error return करेगा। इस तरह आप और आपके clients सुनिश्चित हो सकते हैं कि उन्हें expected data और data shape मिलेगा। +* OpenAPI *path operation* में response के लिए एक **JSON Schema** जोड़ना। + * इसका उपयोग **automatic docs** द्वारा किया जाएगा। + * इसका उपयोग automatic client code generation tools द्वारा भी किया जाएगा। +* Pydantic का उपयोग करके लौटाए गए data को JSON में **Serialize** करना, जो **Rust** में लिखा गया है, इसलिए यह **बहुत तेज़** होगा। + +लेकिन सबसे महत्वपूर्ण: + +* यह output data को return type में defined data तक **limit और filter** करेगा। + * यह **security** के लिए विशेष रूप से महत्वपूर्ण है, हम नीचे इसका और अधिक देखेंगे। + +## `response_model` Parameter { #response-model-parameter } + +कुछ cases ऐसे होते हैं जहाँ आपको ऐसा data return करना होता है या आप ऐसा करना चाहते हैं जो type द्वारा declare किए गए data से बिल्कुल मेल नहीं खाता। + +उदाहरण के लिए, आप **dictionary return** करना या database object return करना चाह सकते हैं, लेकिन **उसे Pydantic model के रूप में declare** करना चाह सकते हैं। इस तरह Pydantic model आपके द्वारा लौटाए गए object (जैसे dictionary या database object) के लिए सभी data documentation, validation, आदि करेगा। + +अगर आपने return type annotation जोड़ा, तो tools और editors एक (सही) error के साथ शिकायत करेंगे कि आपका function ऐसा type (जैसे dict) return कर रहा है जो आपके द्वारा declare किए गए type (जैसे Pydantic model) से अलग है। + +ऐसे cases में, आप return type के बजाय *path operation decorator* parameter `response_model` का उपयोग कर सकते हैं। + +आप किसी भी *path operations* में `response_model` parameter का उपयोग कर सकते हैं: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* आदि। + +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} + +/// note | नोट + +ध्यान दें कि `response_model` "decorator" method (`get`, `post`, आदि) का parameter है। यह आपके *path operation function* का parameter नहीं है, जैसे सभी parameters और body होते हैं। + +/// + +`response_model` वही type receive करता है जिसे आप Pydantic model field के लिए declare करेंगे, इसलिए यह Pydantic model हो सकता है, लेकिन यह, जैसे कि `List[Item]` की तरह Pydantic models की `list` भी हो सकता है। + +FastAPI इस `response_model` का उपयोग सभी data documentation, validation, आदि के लिए करेगा और output data को इसके type declaration में **convert और filter** भी करेगा। + +/// tip | सुझाव + +अगर आपके editor, mypy, आदि में strict type checks हैं, तो आप function return type को `Any` के रूप में declare कर सकते हैं। + +इस तरह आप editor को बताते हैं कि आप जानबूझकर कुछ भी return कर रहे हैं। लेकिन FastAPI फिर भी `response_model` के साथ data documentation, validation, filtering, आदि करेगा। + +/// + +### `response_model` Priority { #response-model-priority } + +अगर आप return type और `response_model` दोनों declare करते हैं, तो `response_model` को priority मिलेगी और FastAPI द्वारा इसका उपयोग किया जाएगा। + +इस तरह आप अपने functions में सही type annotations जोड़ सकते हैं, भले ही आप response model से अलग type return कर रहे हों, ताकि editor और mypy जैसे tools उनका उपयोग कर सकें। और फिर भी FastAPI `response_model` का उपयोग करके data validation, documentation, आदि कर सकता है। + +आप उस *path operation* के लिए response model बनाना disable करने के लिए `response_model=None` का भी उपयोग कर सकते हैं, आपको ऐसा तब करना पड़ सकता है जब आप उन चीज़ों के लिए type annotations जोड़ रहे हों जो valid Pydantic fields नहीं हैं, आप नीचे के sections में से एक में इसका उदाहरण देखेंगे। + +## वही input data return करें { #return-the-same-input-data } + +यहाँ हम एक `UserIn` model declare कर रहे हैं, इसमें plaintext password होगा: + +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} + +/// note | नोट + +`EmailStr` का उपयोग करने के लिए, पहले [`email-validator`](https://github.com/JoshData/python-email-validator) install करें। + +सुनिश्चित करें कि आप एक [virtual environment](../virtual-environments.md) बनाते हैं, उसे activate करते हैं, और फिर इसे install करते हैं, उदाहरण के लिए: + +```console +$ pip install email-validator +``` + +या इसके साथ: + +```console +$ pip install "pydantic[email]" +``` + +/// + +और हम इस model का उपयोग अपने input को declare करने और उसी model का उपयोग अपने output को declare करने के लिए कर रहे हैं: + +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} + +अब, जब भी कोई browser password के साथ user बना रहा होगा, API response में वही password return करेगी। + +इस case में, यह problem नहीं हो सकती, क्योंकि password भेजने वाला वही user है। + +लेकिन अगर हम उसी model का उपयोग किसी और *path operation* के लिए करते हैं, तो हम अपने user के passwords हर client को भेज सकते हैं। + +/// danger | खतरा + +कभी भी किसी user का plain password store न करें या उसे इस तरह response में न भेजें, जब तक कि आप सभी caveats नहीं जानते और यह नहीं जानते कि आप क्या कर रहे हैं। + +/// + +## Output model जोड़ें { #add-an-output-model } + +इसके बजाय हम plaintext password के साथ एक input model और उसके बिना एक output model बना सकते हैं: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} + +यहाँ, भले ही हमारा *path operation function* वही input user return कर रहा है जिसमें password शामिल है: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} + +...हमने `response_model` को अपना model `UserOut` declare किया है, जिसमें password शामिल नहीं है: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} + +इसलिए, **FastAPI** output model में declare न किए गए सभी data को filter out करने का ध्यान रखेगा (Pydantic का उपयोग करके)। + +### `response_model` या Return Type { #response-model-or-return-type } + +इस case में, क्योंकि दोनों models अलग हैं, अगर हमने function return type को `UserOut` के रूप में annotate किया, तो editor और tools शिकायत करेंगे कि हम invalid type return कर रहे हैं, क्योंकि वे अलग classes हैं। + +इसीलिए इस उदाहरण में हमें इसे `response_model` parameter में declare करना पड़ता है। + +...लेकिन इसे कैसे overcome किया जाए, यह देखने के लिए नीचे पढ़ना जारी रखें। + +## Return Type और Data Filtering { #return-type-and-data-filtering } + +आइए पिछले उदाहरण से आगे बढ़ते हैं। हम **function को एक type के साथ annotate** करना चाहते थे, लेकिन हम function से ऐसा कुछ return कर पाना चाहते थे जिसमें वास्तव में **अधिक data** शामिल हो। + +हम चाहते हैं कि FastAPI response model का उपयोग करके data को **filter** करता रहे। ताकि भले ही function अधिक data return करे, response में केवल वही fields शामिल हों जो response model में declare किए गए हैं। + +पिछले उदाहरण में, क्योंकि classes अलग थीं, हमें `response_model` parameter का उपयोग करना पड़ा। लेकिन इसका मतलब यह भी है कि हमें function return type check करने वाले editor और tools से support नहीं मिलता। + +लेकिन अधिकतर cases में जहाँ हमें ऐसा कुछ करना होता है, हम चाहते हैं कि model बस इस उदाहरण की तरह कुछ data को **filter/remove** करे। + +और उन cases में, हम classes और inheritance का उपयोग करके function **type annotations** का लाभ उठा सकते हैं ताकि editor और tools में बेहतर support मिले, और फिर भी FastAPI **data filtering** मिल सके। + +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} + +इसके साथ, हमें editors और mypy से tooling support मिलता है क्योंकि यह code types के संदर्भ में सही है, लेकिन हमें FastAPI से data filtering भी मिलती है। + +यह कैसे काम करता है? आइए इसे देखें। 🤓 + +### Type Annotations और Tooling { #type-annotations-and-tooling } + +पहले देखते हैं कि editors, mypy और अन्य tools इसे कैसे देखेंगे। + +`BaseUser` में base fields हैं। फिर `UserIn`, `BaseUser` से inherit करता है और `password` field जोड़ता है, इसलिए इसमें दोनों models के सभी fields शामिल होंगे। + +हम function return type को `BaseUser` के रूप में annotate करते हैं, लेकिन वास्तव में हम `UserIn` instance return कर रहे हैं। + +Editor, mypy, और अन्य tools इस पर शिकायत नहीं करेंगे क्योंकि typing terms में, `UserIn`, `BaseUser` का subclass है, जिसका मतलब है कि जब expected कुछ भी `BaseUser` हो, तो यह एक *valid* type है। + +### FastAPI Data Filtering { #fastapi-data-filtering } + +अब, FastAPI के लिए, यह return type देखेगा और सुनिश्चित करेगा कि आप जो return करते हैं उसमें **केवल** वही fields शामिल हों जो type में declare किए गए हैं। + +FastAPI internally Pydantic के साथ कई चीज़ें करता है ताकि यह सुनिश्चित हो सके कि class inheritance के वही rules returned data filtering के लिए उपयोग न किए जाएँ, नहीं तो आप expected से कहीं अधिक data return कर सकते हैं। + +इस तरह, आप दोनों दुनिया का best पा सकते हैं: **tooling support** के साथ type annotations और **data filtering**। + +## इसे docs में देखें { #see-it-in-the-docs } + +जब आप automatic docs देखते हैं, तो आप check कर सकते हैं कि input model और output model दोनों का अपना JSON Schema होगा: + + + +और दोनों models interactive API documentation के लिए उपयोग किए जाएँगे: + + + +## अन्य Return Type Annotations { #other-return-type-annotations } + +ऐसे cases हो सकते हैं जहाँ आप कुछ ऐसा return करते हैं जो valid Pydantic field नहीं है और आप उसे function में annotate करते हैं, केवल tooling (editor, mypy, आदि) द्वारा दिए गए support को पाने के लिए। + +### सीधे Response Return करें { #return-a-response-directly } + +सबसे common case होगा [advanced docs में बाद में समझाए अनुसार सीधे Response return करना](../advanced/response-directly.md)। + +{* ../../docs_src/response_model/tutorial003_02_py310.py hl[8,10:11] *} + +यह simple case FastAPI द्वारा automatically handle किया जाता है क्योंकि return type annotation `Response` class (या उसका subclass) है। + +और tools भी खुश होंगे क्योंकि `RedirectResponse` और `JSONResponse` दोनों `Response` के subclasses हैं, इसलिए type annotation सही है। + +### Response Subclass Annotate करें { #annotate-a-response-subclass } + +आप type annotation में `Response` के subclass का भी उपयोग कर सकते हैं: + +{* ../../docs_src/response_model/tutorial003_03_py310.py hl[8:9] *} + +यह भी काम करेगा क्योंकि `RedirectResponse`, `Response` का subclass है, और FastAPI इस simple case को automatically handle करेगा। + +### Invalid Return Type Annotations { #invalid-return-type-annotations } + +लेकिन जब आप कोई अन्य arbitrary object return करते हैं जो valid Pydantic type नहीं है (जैसे database object) और आप उसे function में उसी तरह annotate करते हैं, तो FastAPI उस type annotation से Pydantic response model बनाने की कोशिश करेगा, और fail हो जाएगा। + +ऐसा ही होगा अगर आपके पास अलग-अलग types के बीच union जैसा कुछ हो जहाँ उनमें से एक या अधिक valid Pydantic types नहीं हैं, उदाहरण के लिए यह fail होगा 💥: + +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} + +...यह fail होता है क्योंकि type annotation Pydantic type नहीं है और केवल एक single `Response` class या subclass भी नहीं है, यह `Response` और `dict` के बीच union (दोनों में से कोई भी) है। + +### Response Model Disable करें { #disable-response-model } + +ऊपर दिए गए उदाहरण से आगे बढ़ते हुए, आप शायद default data validation, documentation, filtering, आदि नहीं चाहते हों जो FastAPI द्वारा किया जाता है। + +लेकिन आप शायद function में return type annotation फिर भी रखना चाहते हों ताकि editors और type checkers (जैसे mypy) जैसे tools से support मिल सके। + +इस case में, आप `response_model=None` set करके response model generation disable कर सकते हैं: + +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} + +इससे FastAPI response model generation skip कर देगा और इस तरह आप अपनी जरूरत के किसी भी return type annotations का उपयोग कर सकते हैं, बिना इसके कि वह आपकी FastAPI application को प्रभावित करे। 🤓 + +## Response Model encoding parameters { #response-model-encoding-parameters } + +आपके response model में default values हो सकते हैं, जैसे: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} + +* `description: Union[str, None] = None` (या Python 3.10 में `str | None = None`) का default `None` है। +* `tax: float = 10.5` का default `10.5` है। +* `tags: List[str] = []` का default खाली list है: `[]`। + +लेकिन अगर वे वास्तव में store नहीं किए गए थे तो आप उन्हें result से omit करना चाह सकते हैं। + +उदाहरण के लिए, अगर आपके पास NoSQL database में कई optional attributes वाले models हैं, लेकिन आप default values से भरे बहुत लंबे JSON responses नहीं भेजना चाहते। + +### `response_model_exclude_unset` parameter का उपयोग करें { #use-the-response-model-exclude-unset-parameter } + +आप *path operation decorator* parameter `response_model_exclude_unset=True` set कर सकते हैं: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} + +और वे default values response में शामिल नहीं होंगे, केवल वास्तव में set किए गए values ही शामिल होंगे। + +तो, अगर आप ID `foo` वाले item के लिए उस *path operation* को request भेजते हैं, तो response (default values शामिल किए बिना) होगा: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +/// note | नोट + +आप इसका भी उपयोग कर सकते हैं: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +जैसा कि `exclude_defaults` और `exclude_none` के लिए [Pydantic docs](https://docs.pydantic.dev/1.10/usage/exporting_models/#modeldict) में बताया गया है। + +/// + +#### Defaults वाले fields के लिए values वाला data { #data-with-values-for-fields-with-defaults } + +लेकिन अगर आपके data में model के default values वाले fields के लिए values हैं, जैसे ID `bar` वाला item: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +तो वे response में शामिल होंगे। + +#### Defaults जैसे ही values वाला data { #data-with-the-same-values-as-the-defaults } + +अगर data में default values जैसे ही values हैं, जैसे ID `baz` वाला item: + +```Python hl_lines="3 5-6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +FastAPI इतना smart है (दरअसल, Pydantic इतना smart है) कि यह समझ सके कि, भले ही `description`, `tax`, और `tags` के values defaults जैसे ही हैं, उन्हें explicitly set किया गया था (defaults से लिए जाने के बजाय)। + +इसलिए, वे JSON response में शामिल होंगे। + +/// tip | सुझाव + +ध्यान दें कि default values कुछ भी हो सकते हैं, केवल `None` नहीं। + +वे list (`[]`), `10.5` का `float`, आदि हो सकते हैं। + +/// + +### `response_model_include` और `response_model_exclude` { #response-model-include-and-response-model-exclude } + +आप *path operation decorator* parameters `response_model_include` और `response_model_exclude` का भी उपयोग कर सकते हैं। + +वे include करने के लिए attributes के नामों वाला `str` का `set` लेते हैं (बाकी को omit करते हुए) या exclude करने के लिए (बाकी को include करते हुए)। + +अगर आपके पास केवल एक Pydantic model है और आप output से कुछ data remove करना चाहते हैं, तो इसे quick shortcut के रूप में उपयोग किया जा सकता है। + +/// tip | सुझाव + +लेकिन फिर भी इन parameters के बजाय, multiple classes का उपयोग करते हुए, ऊपर दिए गए ideas का उपयोग करने की recommendation है। + +ऐसा इसलिए है क्योंकि आपके app के OpenAPI (और docs) में generated JSON Schema फिर भी complete model के लिए ही होगा, भले ही आप कुछ attributes omit करने के लिए `response_model_include` या `response_model_exclude` का उपयोग करें। + +यह `response_model_by_alias` पर भी लागू होता है जो इसी तरह काम करता है। + +/// + +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} + +/// tip | सुझाव + +Syntax `{"name", "description"}` उन दो values के साथ एक `set` बनाता है। + +यह `set(["name", "description"])` के equivalent है। + +/// + +#### `set`s के बजाय `list`s का उपयोग करना { #using-lists-instead-of-sets } + +अगर आप `set` का उपयोग करना भूल जाते हैं और इसके बजाय `list` या `tuple` का उपयोग करते हैं, तो FastAPI फिर भी उसे `set` में convert कर देगा और यह सही तरह काम करेगा: + +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} + +## Recap { #recap } + +Response models define करने और खासकर private data को filter out करना सुनिश्चित करने के लिए *path operation decorator* के parameter `response_model` का उपयोग करें। + +केवल explicitly set किए गए values return करने के लिए `response_model_exclude_unset` का उपयोग करें। diff --git a/docs/hi/docs/tutorial/response-status-code.md b/docs/hi/docs/tutorial/response-status-code.md new file mode 100644 index 000000000..b11bdb0ec --- /dev/null +++ b/docs/hi/docs/tutorial/response-status-code.md @@ -0,0 +1,101 @@ +# Response Status Code { #response-status-code } + +जिस तरह आप response model specify कर सकते हैं, उसी तरह आप किसी भी *path operations* में parameter `status_code` के साथ response के लिए इस्तेमाल किया जाने वाला HTTP status code भी declare कर सकते हैं: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* आदि। + +{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *} + +/// note | नोट + +ध्यान दें कि `status_code`, "decorator" method (`get`, `post`, आदि) का parameter है। यह आपके *path operation function* का parameter नहीं है, जैसे बाकी सभी parameters और body होते हैं। + +/// + +`status_code` parameter HTTP status code वाला एक number receive करता है। + +/// note | नोट + +`status_code` वैकल्पिक रूप से एक `IntEnum` भी receive कर सकता है, जैसे Python का [`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus). + +/// + +यह: + +* response में वह status code return करेगा। +* उसे OpenAPI schema में उसी तरह document करेगा (और इसलिए, user interfaces में भी): + + + +/// note | नोट + +कुछ response codes (अगला section देखें) यह indicate करते हैं कि response में body नहीं होती। + +FastAPI यह जानता है, और ऐसे OpenAPI docs बनाएगा जो बताते हैं कि कोई response body नहीं है। + +/// + +## HTTP status codes के बारे में { #about-http-status-codes } + +/// note | नोट + +अगर आप पहले से जानते हैं कि HTTP status codes क्या होते हैं, तो अगले section पर जाएँ। + +/// + +HTTP में, आप response के हिस्से के रूप में 3 digits का एक numeric status code भेजते हैं। + +इन status codes के साथ एक associated name होता है जिससे उन्हें पहचानने में मदद मिलती है, लेकिन महत्वपूर्ण हिस्सा number होता है। + +संक्षेप में: + +* `100 - 199` "Information" के लिए होते हैं। आप इन्हें सीधे बहुत कम इस्तेमाल करते हैं। इन status codes वाले responses में body नहीं हो सकती। +* **`200 - 299`** "Successful" responses के लिए होते हैं। ये वे हैं जिन्हें आप सबसे ज़्यादा इस्तेमाल करेंगे। + * `200` default status code है, जिसका मतलब है कि सब कुछ "OK" था। + * एक और उदाहरण `201`, "Created" होगा। इसे आमतौर पर database में नया record बनाने के बाद इस्तेमाल किया जाता है। + * एक विशेष case `204`, "No Content" है। यह response तब इस्तेमाल होता है जब client को return करने के लिए कोई content नहीं होता, और इसलिए response में body नहीं होनी चाहिए। +* **`300 - 399`** "Redirection" के लिए होते हैं। इन status codes वाले responses में body हो भी सकती है और नहीं भी, सिवाय `304`, "Not Modified" के, जिसमें body नहीं होनी चाहिए। +* **`400 - 499`** "Client error" responses के लिए होते हैं। ये दूसरा type है जिसे आप शायद सबसे ज़्यादा इस्तेमाल करेंगे। + * एक उदाहरण `404` है, "Not Found" response के लिए। + * client से आने वाली generic errors के लिए, आप सिर्फ़ `400` इस्तेमाल कर सकते हैं। +* `500 - 599` server errors के लिए होते हैं। आप इन्हें लगभग कभी सीधे इस्तेमाल नहीं करते। जब आपके application code या server के किसी हिस्से में कुछ गड़बड़ होती है, तो यह अपने-आप इन status codes में से एक return करेगा। + +/// tip | सुझाव + +हर status code के बारे में और कौन-सा code किसके लिए है, यह जानने के लिए [HTTP status codes के बारे में MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) देखें। + +/// + +## नाम याद रखने का shortcut { #shortcut-to-remember-the-names } + +आइए पिछले example को फिर से देखें: + +{* ../../docs_src/response_status_code/tutorial001_py310.py hl[6] *} + +`201` "Created" के लिए status code है। + +लेकिन आपको यह याद रखने की ज़रूरत नहीं है कि इनमें से हर code का क्या मतलब है। + +आप `fastapi.status` से convenience variables इस्तेमाल कर सकते हैं। + +{* ../../docs_src/response_status_code/tutorial002_py310.py hl[1,6] *} + +वे सिर्फ़ एक सुविधा हैं, उनमें वही number होता है, लेकिन इस तरह आप उन्हें खोजने के लिए editor के autocomplete का इस्तेमाल कर सकते हैं: + + + +/// note | तकनीकी विवरण + +आप `from starlette import status` भी इस्तेमाल कर सकते हैं। + +**FastAPI** आपकी सुविधा के लिए, developer के रूप में, वही `starlette.status` `fastapi.status` के रूप में provide करता है। लेकिन यह सीधे Starlette से आता है। + +/// + +## default बदलना { #changing-the-default } + +बाद में, [Advanced User Guide](../advanced/response-change-status-code.md) में, आप देखेंगे कि यहाँ declare किए जा रहे default से अलग status code कैसे return किया जाता है। diff --git a/docs/hi/docs/tutorial/schema-extra-example.md b/docs/hi/docs/tutorial/schema-extra-example.md new file mode 100644 index 000000000..dc8b29f58 --- /dev/null +++ b/docs/hi/docs/tutorial/schema-extra-example.md @@ -0,0 +1,202 @@ +# Request Example Data घोषित करें { #declare-request-example-data } + +आप उस data के examples घोषित कर सकते हैं जिसे आपका app receive कर सकता है। + +इसे करने के कई तरीके यहाँ दिए गए हैं। + +## Pydantic models में अतिरिक्त JSON Schema data { #extra-json-schema-data-in-pydantic-models } + +आप किसी Pydantic model के लिए `examples` घोषित कर सकते हैं, जिन्हें generated JSON Schema में जोड़ा जाएगा। + +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} + +वह अतिरिक्त जानकारी उस model के output **JSON Schema** में जैसी है वैसी ही जोड़ी जाएगी, और API docs में उपयोग की जाएगी। + +आप `model_config` attribute का उपयोग कर सकते हैं, जो एक `dict` लेता है, जैसा कि [Pydantic के docs: Configuration](https://docs.pydantic.dev/latest/api/config/) में बताया गया है। + +आप `"json_schema_extra"` को एक `dict` के साथ set कर सकते हैं जिसमें कोई भी अतिरिक्त data हो जिसे आप generated JSON Schema में दिखाना चाहते हैं, जिसमें `examples` भी शामिल हैं। + +/// tip | सुझाव + +आप इसी technique का उपयोग JSON Schema को extend करने और अपनी custom अतिरिक्त जानकारी जोड़ने के लिए कर सकते हैं। + +उदाहरण के लिए, आप इसका उपयोग frontend user interface आदि के लिए metadata जोड़ने में कर सकते हैं। + +/// + +/// note | नोट + +OpenAPI 3.1.0 (FastAPI 0.99.0 से उपयोग किया गया) ने `examples` के लिए support जोड़ा, जो **JSON Schema** standard का हिस्सा है। + +उससे पहले, यह केवल keyword `example` को एक single example के साथ support करता था। यह अभी भी OpenAPI 3.1.0 द्वारा supported है, लेकिन deprecated है और JSON Schema standard का हिस्सा नहीं है। इसलिए आपको `example` से `examples` पर migrate करने के लिए प्रोत्साहित किया जाता है। 🤓 + +आप इस page के अंत में और पढ़ सकते हैं। + +/// + +## `Field` के अतिरिक्त arguments { #field-additional-arguments } + +Pydantic models के साथ `Field()` का उपयोग करते समय, आप अतिरिक्त `examples` भी घोषित कर सकते हैं: + +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} + +## JSON Schema - OpenAPI में `examples` { #examples-in-json-schema-openapi } + +इनमें से किसी का भी उपयोग करते समय: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +आप अतिरिक्त जानकारी के साथ `examples` का एक group भी घोषित कर सकते हैं, जिसे **OpenAPI** के अंदर उनके **JSON Schemas** में जोड़ा जाएगा। + +### `examples` के साथ `Body` { #body-with-examples } + +यहाँ हम `Body()` में अपेक्षित data के एक example वाला `examples` pass करते हैं: + +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} + +### docs UI में Example { #example-in-the-docs-ui } + +ऊपर दिए गए किसी भी method के साथ यह `/docs` में इस तरह दिखेगा: + + + +### कई `examples` के साथ `Body` { #body-with-multiple-examples } + +बेशक आप कई `examples` भी pass कर सकते हैं: + +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} + +जब आप ऐसा करते हैं, तो examples उस body data के internal **JSON Schema** का हिस्सा होंगे। + +फिर भी, यह लिखते समय, Swagger UI, वह tool जो docs UI दिखाने के लिए जिम्मेदार है, **JSON Schema** में data के लिए कई examples दिखाने को support नहीं करता। लेकिन workaround के लिए नीचे पढ़ें। + +### OpenAPI-specific `examples` { #openapi-specific-examples } + +**JSON Schema** द्वारा `examples` support किए जाने से पहले से ही, OpenAPI में एक अलग field के लिए support था जिसे `examples` भी कहा जाता था। + +यह **OpenAPI-specific** `examples` OpenAPI specification में किसी अन्य section में जाता है। यह प्रत्येक JSON Schema के अंदर नहीं, बल्कि **प्रत्येक *path operation* के details** में जाता है। + +और Swagger UI ने इस विशेष `examples` field को कुछ समय से support किया है। इसलिए, आप इसका उपयोग docs UI में अलग-अलग **examples दिखाने** के लिए कर सकते हैं। + +इस OpenAPI-specific field `examples` का आकार एक `dict` है जिसमें **कई examples** होते हैं (`list` के बजाय), और प्रत्येक में अतिरिक्त जानकारी होती है जो **OpenAPI** में भी जोड़ी जाएगी। + +यह OpenAPI में मौजूद प्रत्येक JSON Schema के अंदर नहीं जाता, यह बाहर, सीधे *path operation* में जाता है। + +### `openapi_examples` Parameter का उपयोग { #using-the-openapi-examples-parameter } + +आप FastAPI में OpenAPI-specific `examples` को parameter `openapi_examples` के साथ इनके लिए घोषित कर सकते हैं: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +`dict` की keys प्रत्येक example की पहचान करती हैं, और प्रत्येक value एक और `dict` होती है। + +`examples` में प्रत्येक specific example `dict` में ये हो सकते हैं: + +* `summary`: example के लिए छोटा description। +* `description`: एक लंबा description जिसमें Markdown text हो सकता है। +* `value`: यह दिखाया गया वास्तविक example है, जैसे एक `dict`। +* `externalValue`: `value` का alternative, example की ओर point करने वाला URL। हालांकि यह शायद `value` जितने tools द्वारा supported न हो। + +आप इसे इस तरह use कर सकते हैं: + +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} + +### Docs UI में OpenAPI Examples { #openapi-examples-in-the-docs-ui } + +`Body()` में `openapi_examples` जोड़ने के साथ `/docs` इस तरह दिखेगा: + + + +## तकनीकी विवरण { #technical-details } + +/// tip | सुझाव + +यदि आप पहले से ही **FastAPI** version **0.99.0 या उससे ऊपर** का उपयोग कर रहे हैं, तो आप शायद ये details **skip** कर सकते हैं। + +ये पुराने versions के लिए अधिक relevant हैं, OpenAPI 3.1.0 उपलब्ध होने से पहले। + +आप इसे एक संक्षिप्त OpenAPI और JSON Schema **history lesson** मान सकते हैं। 🤓 + +/// + +/// warning | चेतावनी + +ये standards **JSON Schema** और **OpenAPI** के बारे में बहुत technical details हैं। + +यदि ऊपर दिए गए ideas आपके लिए पहले से ही काम कर रहे हैं, तो वह पर्याप्त हो सकता है, और शायद आपको इन details की जरूरत नहीं है, इन्हें skip करने के लिए स्वतंत्र महसूस करें। + +/// + +OpenAPI 3.1.0 से पहले, OpenAPI ने **JSON Schema** के एक पुराने और modified version का उपयोग किया। + +JSON Schema में `examples` नहीं था, इसलिए OpenAPI ने अपने स्वयं के modified version में अपना `example` field जोड़ा। + +OpenAPI ने specification के अन्य हिस्सों में भी `example` और `examples` fields जोड़े: + +* [`Parameter Object` (specification में)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object) जिसका उपयोग FastAPI के इनसे किया गया: + * `Path()` + * `Query()` + * `Header()` + * `Cookie()` +* [`Request Body Object`, field `content` में, `Media Type Object` पर (specification में)](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#media-type-object) जिसका उपयोग FastAPI के इनसे किया गया: + * `Body()` + * `File()` + * `Form()` + +/// note | नोट + +यह पुराना OpenAPI-specific `examples` parameter अब FastAPI `0.103.0` से `openapi_examples` है। + +/// + +### JSON Schema का `examples` field { #json-schemas-examples-field } + +लेकिन फिर JSON Schema ने specification के एक नए version में एक [`examples`](https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5) field जोड़ा। + +और फिर नया OpenAPI 3.1.0 latest version (JSON Schema 2020-12) पर आधारित था, जिसमें यह नया field `examples` शामिल था। + +और अब यह नया `examples` field पुराने single (और custom) `example` field पर precedence लेता है, जो अब deprecated है। + +JSON Schema में यह नया `examples` field OpenAPI में अन्य जगहों (ऊपर वर्णित) की तरह अतिरिक्त metadata वाला dict नहीं है, यह **सिर्फ एक `list`** है। + +/// note | नोट + +OpenAPI 3.1.0 के JSON Schema के साथ इस नए सरल integration के साथ release होने के बाद भी, कुछ समय तक, Swagger UI, वह tool जो automatic docs प्रदान करता है, OpenAPI 3.1.0 को support नहीं करता था (यह version 5.0.0 से करता है 🎉)। + +इसी वजह से, 0.99.0 से पहले के FastAPI versions अभी भी OpenAPI के 3.1.0 से कम versions का उपयोग करते थे। + +/// + +### Pydantic और FastAPI `examples` { #pydantic-and-fastapi-examples } + +जब आप Pydantic model के अंदर `examples` जोड़ते हैं, `schema_extra` या `Field(examples=["something"])` का उपयोग करके, तो वह example उस Pydantic model के **JSON Schema** में जोड़ा जाता है। + +और उस Pydantic model का **JSON Schema** आपकी API के **OpenAPI** में शामिल होता है, और फिर docs UI में उपयोग किया जाता है। + +FastAPI के 0.99.0 से पहले के versions में (0.99.0 और ऊपर वाले नए OpenAPI 3.1.0 का उपयोग करते हैं), जब आप किसी भी अन्य utilities (`Query()`, `Body()`, आदि) के साथ `example` या `examples` का उपयोग करते थे, तो वे examples उस data का वर्णन करने वाले JSON Schema में नहीं जोड़े जाते थे (OpenAPI के JSON Schema के अपने version में भी नहीं), वे सीधे OpenAPI में *path operation* declaration में जोड़े जाते थे (OpenAPI के उन parts के बाहर जो JSON Schema का उपयोग करते हैं)। + +लेकिन अब जबकि FastAPI 0.99.0 और ऊपर OpenAPI 3.1.0 का उपयोग करता है, जो JSON Schema 2020-12 का उपयोग करता है, और Swagger UI 5.0.0 और ऊपर, सब कुछ अधिक consistent है और examples JSON Schema में शामिल होते हैं। + +### Swagger UI और OpenAPI-specific `examples` { #swagger-ui-and-openapi-specific-examples } + +अब, क्योंकि Swagger UI कई JSON Schema examples को support नहीं करता था (2023-08-26 तक), users के पास docs में कई examples दिखाने का कोई तरीका नहीं था। + +इसे solve करने के लिए, FastAPI `0.103.0` ने नए parameter `openapi_examples` के साथ उसी पुराने **OpenAPI-specific** `examples` field को घोषित करने के लिए **support जोड़ा**। 🤓 + +### Summary { #summary } + +मैं कहा करता था कि मुझे history उतनी पसंद नहीं है... और अब मुझे देखिए, "tech history" lessons दे रहा हूँ। 😅 + +संक्षेप में, **FastAPI 0.99.0 या उससे ऊपर upgrade करें**, और चीजें बहुत अधिक **सरल, consistent, और intuitive** हैं, और आपको ये सारे historical details जानने की जरूरत नहीं है। 😎 diff --git a/docs/hi/docs/tutorial/security/first-steps.md b/docs/hi/docs/tutorial/security/first-steps.md new file mode 100644 index 000000000..a7bf2e700 --- /dev/null +++ b/docs/hi/docs/tutorial/security/first-steps.md @@ -0,0 +1,203 @@ +# सुरक्षा - पहले कदम { #security-first-steps } + +मान लें कि आपका **backend** API किसी domain में है। + +और आपका **frontend** किसी दूसरे domain में है या उसी domain के किसी अलग path में है (या किसी mobile application में)। + +और आप चाहते हैं कि frontend, **username** और **password** का उपयोग करके backend के साथ authenticate कर सके। + +हम इसे **FastAPI** के साथ बनाने के लिए **OAuth2** का उपयोग कर सकते हैं। + +लेकिन आपको केवल वे छोटी-छोटी जानकारियाँ खोजने के लिए पूरी लंबी specification पढ़ने में समय न लगाना पड़े। + +आइए सुरक्षा संभालने के लिए **FastAPI** द्वारा दिए गए tools का उपयोग करें। + +## यह कैसा दिखता है { #how-it-looks } + +आइए पहले बस code का उपयोग करें और देखें कि यह कैसे काम करता है, और फिर हम वापस आकर समझेंगे कि क्या हो रहा है। + +## `main.py` बनाएँ { #create-main-py } + +उदाहरण को एक file `main.py` में copy करें: + +{* ../../docs_src/security/tutorial001_an_py310.py *} + +## इसे चलाएँ { #run-it } + +/// note | नोट + +[`python-multipart`](https://github.com/Kludex/python-multipart) package **FastAPI** के साथ अपने-आप install हो जाता है जब आप `pip install "fastapi[standard]"` command चलाते हैं। + +हालाँकि, अगर आप `pip install fastapi` command का उपयोग करते हैं, तो `python-multipart` package default रूप से शामिल नहीं होता। + +इसे manually install करने के लिए, सुनिश्चित करें कि आप एक [virtual environment](../../virtual-environments.md) बनाएँ, उसे activate करें, और फिर इसे इस तरह install करें: + +```console +$ pip install python-multipart +``` + +ऐसा इसलिए है क्योंकि **OAuth2**, `username` और `password` भेजने के लिए "form data" का उपयोग करता है। + +/// + +उदाहरण को इस तरह चलाएँ: + +
+ +```console +$ fastapi dev + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +## इसे जाँचें { #check-it } + +Interactive docs पर जाएँ: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs). + +आपको कुछ ऐसा दिखाई देगा: + + + +/// tip | Authorize बटन! + +आपके पास पहले से ही एक चमकदार नया "Authorize" बटन है। + +और आपकी *path operation* के ऊपर-दाएँ कोने में एक छोटा-सा lock है जिस पर आप click कर सकते हैं। + +/// + +और अगर आप उस पर click करते हैं, तो आपके पास `username` और `password` (और अन्य optional fields) type करने के लिए एक छोटा authorization form होगा: + + + +/// note | नोट + +आप form में क्या type करते हैं, इससे कोई फर्क नहीं पड़ता, यह अभी काम नहीं करेगा। लेकिन हम वहाँ तक पहुँचेंगे। + +/// + +यह निश्चित रूप से final users के लिए frontend नहीं है, लेकिन यह आपके पूरे API को interactively document करने के लिए एक शानदार automatic tool है। + +इसे frontend team द्वारा उपयोग किया जा सकता है (जो आप खुद भी हो सकते हैं)। + +इसे third party applications और systems द्वारा उपयोग किया जा सकता है। + +और इसे आप खुद भी उसी application को debug, check और test करने के लिए उपयोग कर सकते हैं। + +## `password` flow { #the-password-flow } + +अब थोड़ा पीछे चलते हैं और समझते हैं कि यह सब क्या है। + +`password` "flow", OAuth2 में परिभाषित उन तरीकों ("flows") में से एक है, जिनका उपयोग security और authentication संभालने के लिए किया जाता है। + +OAuth2 को इस तरह design किया गया था कि backend या API उस server से independent हो सके जो user को authenticate करता है। + +लेकिन इस case में, वही **FastAPI** application API और authentication दोनों संभालेगा। + +तो, आइए इसे उस simplified दृष्टिकोण से review करें: + +* User frontend में `username` और `password` type करता है, और `Enter` दबाता है। +* Frontend (जो user के browser में चल रहा है) उस `username` और `password` को हमारे API के एक specific URL पर भेजता है (`tokenUrl="token"` के साथ declare किया गया)। +* API उस `username` और `password` को check करता है, और एक "token" के साथ respond करता है (हमने अभी तक इनमें से कुछ भी implement नहीं किया है)। + * एक "token" बस कुछ content वाली string है जिसका उपयोग हम बाद में इस user को verify करने के लिए कर सकते हैं। + * सामान्यतः, token को कुछ समय बाद expire होने के लिए set किया जाता है। + * इसलिए, user को बाद में किसी समय फिर से log in करना होगा। + * और अगर token चोरी हो जाता है, तो risk कम होता है। यह किसी permanent key जैसा नहीं है जो हमेशा काम करेगी (अधिकांश cases में)। +* Frontend उस token को अस्थायी रूप से कहीं store करता है। +* User frontend web app के किसी दूसरे section में जाने के लिए frontend में click करता है। +* Frontend को API से कुछ और data fetch करने की आवश्यकता होती है। + * लेकिन उस specific endpoint के लिए इसे authentication चाहिए। + * इसलिए, हमारे API के साथ authenticate करने के लिए, यह `Authorization` header भेजता है जिसकी value `Bearer ` plus token होती है। + * अगर token में `foobar` है, तो `Authorization` header का content होगा: `Bearer foobar`. + +## **FastAPI** का `OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer } + +**FastAPI** इन security features को implement करने के लिए abstraction के अलग-अलग levels पर कई tools देता है। + +इस उदाहरण में हम **OAuth2** का उपयोग करने जा रहे हैं, **Password** flow के साथ, **Bearer** token का उपयोग करते हुए। हम यह `OAuth2PasswordBearer` class का उपयोग करके करते हैं। + +/// note | नोट + +"bearer" token एकमात्र विकल्प नहीं है। + +लेकिन हमारे use case के लिए यह सबसे अच्छा है। + +और यह अधिकांश use cases के लिए सबसे अच्छा हो सकता है, जब तक कि आप OAuth2 expert न हों और ठीक-ठीक न जानते हों कि कोई दूसरा विकल्प आपकी आवश्यकताओं के लिए बेहतर क्यों है। + +उस case में, **FastAPI** आपको इसे बनाने के लिए tools भी देता है। + +/// + +जब हम `OAuth2PasswordBearer` class का instance बनाते हैं तो हम `tokenUrl` parameter pass करते हैं। इस parameter में वह URL होता है जिसका उपयोग client (user के browser में चल रहा frontend) token पाने के लिए `username` और `password` भेजने में करेगा। + +{* ../../docs_src/security/tutorial001_an_py310.py hl[8] *} + +/// tip | सुझाव + +यहाँ `tokenUrl="token"` एक relative URL `token` को refer करता है जिसे हमने अभी तक बनाया नहीं है। क्योंकि यह relative URL है, यह `./token` के equivalent है। + +क्योंकि हम relative URL का उपयोग कर रहे हैं, अगर आपका API `https://example.com/` पर स्थित था, तो यह `https://example.com/token` को refer करेगा। लेकिन अगर आपका API `https://example.com/api/v1/` पर स्थित था, तो यह `https://example.com/api/v1/token` को refer करेगा। + +Relative URL का उपयोग करना महत्वपूर्ण है ताकि यह सुनिश्चित हो सके कि आपका application [Proxy के पीछे](../../advanced/behind-a-proxy.md) जैसे advanced use case में भी काम करता रहे। + +/// + +यह parameter उस endpoint / *path operation* को create नहीं करता, बल्कि declare करता है कि URL `/token` वही होगा जिसका उपयोग client को token पाने के लिए करना चाहिए। उस जानकारी का उपयोग OpenAPI में किया जाता है, और फिर interactive API documentation systems में। + +हम जल्द ही वास्तविक path operation भी बनाएँगे। + +/// note | नोट + +अगर आप बहुत strict "Pythonista" हैं, तो आपको parameter name `tokenUrl` की style `token_url` के बजाय पसंद न आए। + +ऐसा इसलिए है क्योंकि यह OpenAPI spec जैसा ही name उपयोग कर रहा है। ताकि अगर आपको इनमें से किसी भी security scheme के बारे में और अधिक जाँच करनी हो, तो आप बस इसे copy और paste करके इसके बारे में और जानकारी खोज सकें। + +/// + +`oauth2_scheme` variable `OAuth2PasswordBearer` का instance है, लेकिन यह एक "callable" भी है। + +इसे इस तरह call किया जा सकता है: + +```Python +oauth2_scheme(some, parameters) +``` + +तो, इसे `Depends` के साथ उपयोग किया जा सकता है। + +### इसका उपयोग करें { #use-it } + +अब आप उस `oauth2_scheme` को `Depends` के साथ dependency में pass कर सकते हैं। + +{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *} + +यह dependency एक `str` प्रदान करेगी जिसे *path operation function* के parameter `token` को assign किया जाता है। + +**FastAPI** जान जाएगा कि यह OpenAPI schema (और automatic API docs) में "security scheme" define करने के लिए इस dependency का उपयोग कर सकता है। + +/// note | तकनीकी विवरण + +**FastAPI** जान जाएगा कि यह OpenAPI में security scheme define करने के लिए `OAuth2PasswordBearer` class (जो dependency में declare की गई है) का उपयोग कर सकता है क्योंकि यह `fastapi.security.oauth2.OAuth2` से inherit करती है, जो बदले में `fastapi.security.base.SecurityBase` से inherit करती है। + +OpenAPI (और automatic API docs) के साथ integrate होने वाली सभी security utilities `SecurityBase` से inherit करती हैं, इसी तरह **FastAPI** जान सकता है कि उन्हें OpenAPI में कैसे integrate करना है। + +/// + +## यह क्या करता है { #what-it-does } + +यह request में उस `Authorization` header को खोजेगा, check करेगा कि value `Bearer ` plus कोई token है या नहीं, और token को `str` के रूप में return करेगा। + +अगर इसे `Authorization` header नहीं दिखता, या value में `Bearer ` token नहीं है, तो यह सीधे 401 status code error (`UNAUTHORIZED`) के साथ respond करेगा। + +Error return करने के लिए आपको यह भी check करने की आवश्यकता नहीं है कि token मौजूद है या नहीं। आप निश्चिंत हो सकते हैं कि अगर आपकी function execute होती है, तो उस token में एक `str` होगा। + +आप इसे अभी interactive docs में आज़मा सकते हैं: + + + +हम अभी token की validity verify नहीं कर रहे हैं, लेकिन यह पहले से ही एक शुरुआत है। + +## Recap { #recap } + +तो, केवल 3 या 4 अतिरिक्त lines में, आपके पास पहले से ही security का कुछ primitive form है। diff --git a/docs/hi/docs/tutorial/security/get-current-user.md b/docs/hi/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..403d6e7d5 --- /dev/null +++ b/docs/hi/docs/tutorial/security/get-current-user.md @@ -0,0 +1,105 @@ +# Current User प्राप्त करें { #get-current-user } + +पिछले अध्याय में security system (जो dependency injection system पर आधारित है) *path operation function* को `str` के रूप में एक `token` दे रहा था: + +{* ../../docs_src/security/tutorial001_an_py310.py hl[12] *} + +लेकिन वह अभी भी इतना उपयोगी नहीं है। + +आइए इसे हमें current user देने वाला बनाते हैं। + +## एक user model बनाएँ { #create-a-user-model } + +पहले, एक Pydantic user model बनाते हैं। + +जिस तरह हम bodies declare करने के लिए Pydantic का उपयोग करते हैं, उसी तरह हम इसे कहीं और भी उपयोग कर सकते हैं: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:16] *} + +## एक `get_current_user` dependency बनाएँ { #create-a-get-current-user-dependency } + +आइए एक dependency `get_current_user` बनाएँ। + +याद है कि dependencies की sub-dependencies हो सकती हैं? + +`get_current_user` के पास उसी `oauth2_scheme` के साथ एक dependency होगी जिसे हमने पहले बनाया था। + +ठीक वैसे ही जैसे हम पहले सीधे *path operation* में कर रहे थे, हमारी नई dependency `get_current_user` sub-dependency `oauth2_scheme` से `str` के रूप में एक `token` प्राप्त करेगी: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} + +## user प्राप्त करें { #get-the-user } + +`get_current_user` हमारे द्वारा बनाई गई एक (fake) utility function का उपयोग करेगी, जो token को `str` के रूप में लेती है और हमारा Pydantic `User` model लौटाती है: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} + +## current user inject करें { #inject-the-current-user } + +तो अब हम *path operation* में अपने `get_current_user` के साथ वही `Depends` उपयोग कर सकते हैं: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} + +ध्यान दें कि हम `current_user` का type Pydantic model `User` के रूप में declare करते हैं। + +यह function के अंदर completion और type checks में हमारी मदद करेगा। + +/// tip | टिप + +आपको याद होगा कि request bodies भी Pydantic models के साथ declare की जाती हैं। + +यहाँ **FastAPI** confuse नहीं होगा क्योंकि आप `Depends` का उपयोग कर रहे हैं। + +/// + +/// tip | टिप + +जिस तरह यह dependency system design किया गया है, वह हमें अलग-अलग dependencies (अलग-अलग "dependables") रखने देता है जो सभी एक `User` model लौटाती हैं। + +हम केवल एक dependency तक सीमित नहीं हैं जो उस type का data लौटा सकती है। + +/// + +## अन्य models { #other-models } + +अब आप *path operation functions* में सीधे current user प्राप्त कर सकते हैं और `Depends` का उपयोग करके **Dependency Injection** स्तर पर security mechanisms संभाल सकते हैं। + +और आप security requirements के लिए कोई भी model या data उपयोग कर सकते हैं (इस मामले में, Pydantic model `User`)। + +लेकिन आप किसी विशेष data model, class या type का उपयोग करने तक सीमित नहीं हैं। + +क्या आप अपने model में `id` और `email` रखना चाहते हैं और कोई `username` नहीं रखना चाहते? बिल्कुल। आप इन्हीं tools का उपयोग कर सकते हैं। + +क्या आप केवल एक `str` रखना चाहते हैं? या केवल एक `dict`? या सीधे database class model instance? सब कुछ उसी तरह काम करता है। + +असल में आपके application में login करने वाले users नहीं हैं, बल्कि robots, bots, या अन्य systems हैं, जिनके पास बस एक access token है? फिर भी, सब कुछ उसी तरह काम करता है। + +बस अपने application के लिए जिस भी प्रकार का model, जिस भी प्रकार की class, जिस भी प्रकार का database चाहिए, उसका उपयोग करें। **FastAPI** dependency injection system के साथ आपकी ज़रूरतें पूरी करता है। + +## Code size { #code-size } + +यह example verbose लग सकता है। ध्यान रखें कि हम security, data models, utility functions और *path operations* को उसी file में मिला रहे हैं। + +लेकिन यहाँ मुख्य बात है। + +security और dependency injection से जुड़ी चीज़ें एक बार लिखी जाती हैं। + +और आप इसे जितना चाहें उतना complex बना सकते हैं। फिर भी, यह केवल एक बार, एक ही जगह पर, पूरी flexibility के साथ लिखा जाता है। + +लेकिन आपके पास उसी security system का उपयोग करने वाले हजारों endpoints (*path operations*) हो सकते हैं। + +और वे सभी (या उनका कोई भी हिस्सा जिसे आप चाहें) इन dependencies या आपके द्वारा बनाई गई किसी भी अन्य dependencies को फिर से उपयोग करने का लाभ उठा सकते हैं। + +और ये सभी हजारों *path operations* सिर्फ 3 lines जितने छोटे हो सकते हैं: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} + +## Recap { #recap } + +अब आप अपने *path operation function* में सीधे current user प्राप्त कर सकते हैं। + +हम पहले ही आधे रास्ते तक पहुँच चुके हैं। + +हमें बस user/client के लिए एक *path operation* जोड़ना है ताकि वह वास्तव में `username` और `password` भेज सके। + +वह आगे आता है। diff --git a/docs/hi/docs/tutorial/security/index.md b/docs/hi/docs/tutorial/security/index.md new file mode 100644 index 000000000..43fbd0a9b --- /dev/null +++ b/docs/hi/docs/tutorial/security/index.md @@ -0,0 +1,105 @@ +# Security { #security } + +security, authentication और authorization को handle करने के कई तरीके हैं। + +और यह सामान्यतः एक जटिल और "कठिन" विषय होता है। + +कई frameworks और systems में केवल security और authentication को handle करने में ही बहुत अधिक effort और code लग जाता है (कई मामलों में यह लिखे गए पूरे code का 50% या उससे अधिक हो सकता है)। + +**FastAPI** आपको **Security** से आसानी से, तेज़ी से, standard तरीके से निपटने में मदद करने के लिए कई tools प्रदान करता है, बिना सभी security specifications को पढ़ने और सीखने की ज़रूरत के। + +लेकिन पहले, आइए कुछ छोटे concepts देखते हैं। + +## जल्दी में हैं? { #in-a-hurry } + +अगर आपको इन terms की परवाह नहीं है और आपको बस username और password पर आधारित authentication के साथ security *अभी* जोड़नी है, तो अगले chapters पर जाएँ। + +## OAuth2 { #oauth2 } + +OAuth2 एक specification है जो authentication और authorization को handle करने के कई तरीके define करती है। + +यह काफ़ी विस्तृत specification है और कई जटिल use cases को cover करती है। + +इसमें "third party" का उपयोग करके authenticate करने के तरीके शामिल हैं। + +यही चीज़ अंदर से उन सभी systems में इस्तेमाल होती है जिनमें "login with Facebook, Google, X (Twitter), GitHub" होता है। + +### OAuth 1 { #oauth-1 } + +OAuth 1 भी था, जो OAuth2 से बहुत अलग और अधिक जटिल था, क्योंकि इसमें communication को encrypt करने के तरीके पर direct specifications शामिल थीं। + +आजकल यह बहुत लोकप्रिय या इस्तेमाल में नहीं है। + +OAuth2 यह specify नहीं करता कि communication को कैसे encrypt करना है, यह अपेक्षा करता है कि आपकी application HTTPS के साथ serve की जा रही हो। + +/// tip | सुझाव + +**deployment** वाले section में आप देखेंगे कि Traefik और Let's Encrypt का उपयोग करके HTTPS को मुफ्त में कैसे setup किया जाता है। + +/// + +## OpenID Connect { #openid-connect } + +OpenID Connect एक और specification है, जो **OAuth2** पर आधारित है। + +यह OAuth2 को बस extend करता है और कुछ ऐसी चीज़ें specify करता है जो OAuth2 में तुलनात्मक रूप से ambiguous हैं, ताकि इसे अधिक interoperable बनाया जा सके। + +उदाहरण के लिए, Google login OpenID Connect का उपयोग करता है (जो अंदर से OAuth2 का उपयोग करता है)। + +लेकिन Facebook login OpenID Connect को support नहीं करता। उसका अपना OAuth2 flavor है। + +### OpenID ("OpenID Connect" नहीं) { #openid-not-openid-connect } + +एक "OpenID" specification भी थी। उसने वही समस्या हल करने की कोशिश की जो **OpenID Connect** करता है, लेकिन वह OAuth2 पर आधारित नहीं थी। + +इसलिए, वह एक पूरा अतिरिक्त system था। + +आजकल यह बहुत लोकप्रिय या इस्तेमाल में नहीं है। + +## OpenAPI { #openapi } + +OpenAPI (पहले Swagger के नाम से जाना जाता था) APIs बनाने के लिए open specification है (अब Linux Foundation का हिस्सा)। + +**FastAPI** **OpenAPI** पर आधारित है। + +इसी वजह से कई automatic interactive documentation interfaces, code generation, आदि होना संभव होता है। + +OpenAPI कई security "schemes" define करने का तरीका देता है। + +इनका उपयोग करके, आप इन सभी standard-based tools का लाभ उठा सकते हैं, जिनमें ये interactive documentation systems भी शामिल हैं। + +OpenAPI निम्नलिखित security schemes define करता है: + +* `apiKey`: एक application-specific key जो यहाँ से आ सकती है: + * एक query parameter. + * एक header. + * एक cookie. +* `http`: standard HTTP authentication systems, जिनमें शामिल हैं: + * `bearer`: एक header `Authorization` जिसमें `Bearer ` plus एक token का value होता है। यह OAuth2 से inherited है। + * HTTP Basic authentication. + * HTTP Digest, आदि। +* `oauth2`: security handle करने के सभी OAuth2 तरीके (जिन्हें "flows" कहा जाता है)। + * इनमें से कई flows OAuth 2.0 authentication provider बनाने के लिए उपयुक्त हैं (जैसे Google, Facebook, X (Twitter), GitHub, आदि): + * `implicit` + * `clientCredentials` + * `authorizationCode` + * लेकिन एक specific "flow" है जिसे उसी application में सीधे authentication handle करने के लिए पूरी तरह इस्तेमाल किया जा सकता है: + * `password`: कुछ अगले chapters इसके examples cover करेंगे। +* `openIdConnect`: इसमें OAuth2 authentication data को automatically discover करने का तरीका होता है। + * यह automatic discovery वही है जो OpenID Connect specification में define की गई है। + +/// tip | सुझाव + +Google, Facebook, X (Twitter), GitHub, आदि जैसे अन्य authentication/authorization providers को integrate करना भी संभव और तुलनात्मक रूप से आसान है। + +सबसे जटिल समस्या उन जैसे authentication/authorization provider बनाना है, लेकिन **FastAPI** आपको इसे आसानी से करने के लिए tools देता है, और आपके लिए heavy lifting करता है। + +/// + +## **FastAPI** utilities { #fastapi-utilities } + +FastAPI इन security schemes में से प्रत्येक के लिए `fastapi.security` module में कई tools प्रदान करता है, जो इन security mechanisms का उपयोग आसान बनाते हैं। + +अगले chapters में आप देखेंगे कि **FastAPI** द्वारा प्रदान किए गए उन tools का उपयोग करके अपनी API में security कैसे जोड़ें। + +और आप यह भी देखेंगे कि यह interactive documentation system में automatically कैसे integrate हो जाता है। diff --git a/docs/hi/docs/tutorial/security/oauth2-jwt.md b/docs/hi/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..2066d8f5a --- /dev/null +++ b/docs/hi/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,277 @@ +# Password के साथ OAuth2 (और hashing), JWT tokens के साथ Bearer { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } + +अब जब हमारे पास पूरा security flow है, तो आइए JWT tokens और secure password hashing का उपयोग करके application को वास्तव में secure बनाते हैं। + +यह code ऐसा है जिसे आप अपनी application में सच में उपयोग कर सकते हैं, password hashes को अपने database में save कर सकते हैं, आदि। + +हम पिछले chapter में जहाँ छोड़ा था, वहीं से शुरू करेंगे और उसे आगे बढ़ाएँगे। + +## JWT के बारे में { #about-jwt } + +JWT का मतलब है "JSON Web Tokens"। + +यह एक JSON object को बिना spaces वाली लंबी dense string में codify करने का standard है। यह ऐसा दिखता है: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +यह encrypted नहीं है, इसलिए कोई भी contents से जानकारी वापस प्राप्त कर सकता है। + +लेकिन यह signed है। इसलिए, जब आपको कोई token मिलता है जिसे आपने issue किया था, तो आप verify कर सकते हैं कि उसे आपने ही issue किया था। + +इस तरह, आप एक token बना सकते हैं जिसकी expiration, मान लीजिए, 1 week हो। और फिर जब user अगले दिन token के साथ वापस आता है, तो आपको पता होता है कि वह user अभी भी आपके system में logged in है। + +एक week के बाद, token expired हो जाएगा और user authorized नहीं होगा और नया token पाने के लिए उसे फिर से sign in करना होगा। और अगर user (या कोई third party) expiration बदलने के लिए token को modify करने की कोशिश करे, तो आप इसे पता लगा पाएँगे, क्योंकि signatures match नहीं होंगे। + +अगर आप JWT tokens के साथ प्रयोग करना चाहते हैं और देखना चाहते हैं कि वे कैसे काम करते हैं, तो [https://jwt.io](https://jwt.io/) देखें। + +## `PyJWT` install करें { #install-pyjwt } + +Python में JWT tokens generate और verify करने के लिए हमें `PyJWT` install करना होगा। + +सुनिश्चित करें कि आप एक [virtual environment](../../virtual-environments.md) बनाएँ, उसे activate करें, और फिर `pyjwt` install करें: + +
+ +```console +$ pip install pyjwt + +---> 100% +``` + +
+ +/// note | नोट + +अगर आप RSA या ECDSA जैसे digital signature algorithms का उपयोग करने की योजना बना रहे हैं, तो आपको cryptography library dependency `pyjwt[crypto]` install करनी चाहिए। + +आप इसके बारे में [PyJWT Installation docs](https://pyjwt.readthedocs.io/en/latest/installation.html) में और पढ़ सकते हैं। + +/// + +## Password hashing { #password-hashing } + +"Hashing" का मतलब है किसी content (इस मामले में password) को bytes के sequence (बस एक string) में बदलना, जो बेकार/असमझ text जैसा दिखता है। + +जब भी आप बिल्कुल वही content (बिल्कुल वही password) pass करते हैं, आपको बिल्कुल वही gibberish मिलता है। + +लेकिन आप उस gibberish से वापस password में convert नहीं कर सकते। + +### Password hashing क्यों उपयोग करें { #why-use-password-hashing } + +अगर आपका database चोरी हो जाता है, तो चोर के पास आपके users के plaintext passwords नहीं होंगे, केवल hashes होंगे। + +इसलिए, चोर उस password को किसी दूसरे system में उपयोग करने की कोशिश नहीं कर पाएगा (क्योंकि कई users हर जगह वही password उपयोग करते हैं, यह खतरनाक होगा)। + +## `pwdlib` install करें { #install-pwdlib } + +pwdlib password hashes संभालने के लिए एक शानदार Python package है। + +यह कई secure hashing algorithms और उनके साथ काम करने के लिए utilities support करता है। + +Recommended algorithm "Argon2" है। + +सुनिश्चित करें कि आप एक [virtual environment](../../virtual-environments.md) बनाएँ, उसे activate करें, और फिर Argon2 के साथ pwdlib install करें: + +
+ +```console +$ pip install "pwdlib[argon2]" + +---> 100% +``` + +
+ +/// tip | सुझाव + +`pwdlib` के साथ, आप इसे इस तरह configure भी कर सकते हैं कि यह **Django**, **Flask** security plug-in या कई अन्य द्वारा बनाए गए passwords read कर सके। + +तो, उदाहरण के लिए, आप एक database में Django application का वही data FastAPI application के साथ share कर पाएँगे। या उसी database का उपयोग करते हुए धीरे-धीरे Django application को migrate कर पाएँगे। + +और आपके users एक ही समय में आपकी Django app या आपकी **FastAPI** app से login कर पाएँगे। + +/// + +## Passwords को hash और verify करें { #hash-and-verify-the-passwords } + +`pwdlib` से वे tools import करें जिनकी हमें ज़रूरत है। + +Recommended settings के साथ एक PasswordHash instance बनाएँ - इसका उपयोग passwords को hash और verify करने के लिए किया जाएगा। + +/// tip | सुझाव + +pwdlib bcrypt hashing algorithm को भी support करता है लेकिन legacy algorithms शामिल नहीं करता - outdated hashes के साथ काम करने के लिए passlib library का उपयोग करना recommended है। + +उदाहरण के लिए, आप इसका उपयोग किसी दूसरे system (जैसे Django) द्वारा generate किए गए passwords read और verify करने के लिए कर सकते हैं, लेकिन किसी भी नए passwords को Argon2 या Bcrypt जैसे अलग algorithm से hash कर सकते हैं। + +और एक ही समय में उन सभी के साथ compatible रह सकते हैं। + +/// + +User से आने वाले password को hash करने के लिए एक utility function बनाएँ। + +और एक और utility बनाएँ जो verify करे कि received password stored hash से match करता है या नहीं। + +और एक और utility बनाएँ जो authenticate करे और user return करे। + +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,51,58:59,62:63,72:79] *} + +जब `authenticate_user` को ऐसे username के साथ call किया जाता है जो database में मौजूद नहीं है, तब भी हम dummy hash के against `verify_password` चलाते हैं। + +यह सुनिश्चित करता है कि username valid हो या न हो, endpoint response देने में लगभग समान समय ले, जिससे **timing attacks** रोके जा सकें जिनका उपयोग मौजूदा usernames enumerate करने के लिए किया जा सकता है। + +/// note | नोट + +अगर आप नए (fake) database `fake_users_db` को check करेंगे, तो आप देखेंगे कि hashed password अब कैसा दिखता है: `"$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc"`। + +/// + +## JWT tokens संभालें { #handle-jwt-tokens } + +Installed modules import करें। + +एक random secret key बनाएँ जिसका उपयोग JWT tokens sign करने के लिए किया जाएगा। + +Secure random secret key generate करने के लिए command उपयोग करें: + +
+ +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
+ +और output को variable `SECRET_KEY` में copy करें (example वाला उपयोग न करें)। + +JWT token sign करने के लिए उपयोग किए गए algorithm के साथ एक variable `ALGORITHM` बनाएँ और इसे `"HS256"` पर set करें। + +Token की expiration के लिए एक variable बनाएँ। + +एक Pydantic Model define करें जिसका उपयोग response के लिए token endpoint में किया जाएगा। + +नया access token generate करने के लिए एक utility function बनाएँ। + +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,82:90] *} + +## Dependencies update करें { #update-the-dependencies } + +`get_current_user` को update करें ताकि वह पहले जैसा ही token receive करे, लेकिन इस बार JWT tokens का उपयोग करते हुए। + +Received token को decode करें, verify करें, और current user return करें। + +अगर token invalid है, तो तुरंत HTTP error return करें। + +{* ../../docs_src/security/tutorial004_an_py310.py hl[93:110] *} + +## `/token` *path operation* update करें { #update-the-token-path-operation } + +Token की expiration time के साथ एक `timedelta` बनाएँ। + +एक वास्तविक JWT access token बनाएँ और उसे return करें। + +{* ../../docs_src/security/tutorial004_an_py310.py hl[121:136] *} + +### JWT "subject" `sub` के बारे में technical details { #technical-details-about-the-jwt-subject-sub } + +JWT specification कहता है कि token के subject के साथ एक key `sub` होती है। + +इसका उपयोग करना optional है, लेकिन यही वह जगह है जहाँ आप user की identification रखेंगे, इसलिए हम इसे यहाँ उपयोग कर रहे हैं। + +JWT का उपयोग user की पहचान करने और उन्हें आपकी API पर सीधे operations perform करने की अनुमति देने के अलावा अन्य चीज़ों के लिए भी किया जा सकता है। + +उदाहरण के लिए, आप एक "car" या एक "blog post" की पहचान कर सकते हैं। + +फिर आप उस entity के बारे में permissions जोड़ सकते हैं, जैसे "drive" (car के लिए) या "edit" (blog के लिए)। + +और फिर, आप वह JWT token किसी user (या bot) को दे सकते हैं, और वे उन actions को perform करने के लिए इसका उपयोग कर सकते हैं (car drive करना, या blog post edit करना), बिना account की ज़रूरत के, केवल उस JWT token के साथ जिसे आपकी API ने इसके लिए generate किया है। + +इन ideas का उपयोग करके, JWT का उपयोग कहीं अधिक sophisticated scenarios के लिए किया जा सकता है। + +इन cases में, उन entities में से कई की same ID हो सकती है, मान लीजिए `foo` (एक user `foo`, एक car `foo`, और एक blog post `foo`)। + +इसलिए, ID collisions से बचने के लिए, user के लिए JWT token बनाते समय, आप `sub` key के value के आगे prefix जोड़ सकते हैं, जैसे `username:`। इसलिए, इस example में, `sub` का value हो सकता था: `username:johndoe`। + +ध्यान रखने वाली महत्वपूर्ण बात यह है कि `sub` key के पास पूरी application में unique identifier होना चाहिए, और यह एक string होना चाहिए। + +## इसे check करें { #check-it } + +Server run करें और docs पर जाएँ: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)। + +आप user interface ऐसा देखेंगे: + + + +Application को पहले की तरह ही authorize करें। + +Credentials का उपयोग करते हुए: + +Username: `johndoe` +Password: `secret` + +/// tip | सुझाव + +ध्यान दें कि code में कहीं भी plaintext password "`secret`" नहीं है, हमारे पास केवल hashed version है। + +/// + + + +Endpoint `/users/me/` call करें, आपको response इस तरह मिलेगा: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +अगर आप developer tools खोलते हैं, तो आप देख सकते हैं कि भेजे गए data में केवल token शामिल है, password केवल पहले request में user को authenticate करने और वह access token पाने के लिए भेजा जाता है, लेकिन उसके बाद नहीं: + + + +/// note | नोट + +`Authorization` header पर ध्यान दें, जिसका value `Bearer ` से शुरू होता है। + +/// + +## `scopes` के साथ advanced उपयोग { #advanced-usage-with-scopes } + +OAuth2 में "scopes" की धारणा है। + +आप उनका उपयोग JWT token में permissions का specific set जोड़ने के लिए कर सकते हैं। + +फिर आप यह token सीधे किसी user या third party को दे सकते हैं, ताकि वे restrictions के set के साथ आपकी API से interact कर सकें। + +आप बाद में **Advanced User Guide** में सीख सकते हैं कि उनका उपयोग कैसे करें और वे **FastAPI** में कैसे integrated हैं। + +## Recap { #recap } + +अब तक आपने जो देखा है, उससे आप OAuth2 और JWT जैसे standards का उपयोग करके एक secure **FastAPI** application setup कर सकते हैं। + +लगभग किसी भी framework में security संभालना काफ़ी जल्दी एक जटिल विषय बन जाता है। + +कई packages जो इसे बहुत सरल बनाते हैं, उन्हें data model, database, और available features के साथ कई compromises करने पड़ते हैं। और इनमें से कुछ packages जो चीज़ों को बहुत अधिक सरल बना देते हैं, उनके अंदर वास्तव में security flaws होते हैं। + +--- + +**FastAPI** किसी भी database, data model या tool के साथ कोई compromise नहीं करता। + +यह आपको उन चीज़ों को चुनने की पूरी flexibility देता है जो आपके project के लिए सबसे अच्छी हों। + +और आप सीधे कई well maintained और widely used packages जैसे `pwdlib` और `PyJWT` का उपयोग कर सकते हैं, क्योंकि **FastAPI** external packages integrate करने के लिए किसी complex mechanism की मांग नहीं करता। + +लेकिन यह आपको process को जितना संभव हो उतना सरल बनाने के लिए tools देता है, बिना flexibility, robustness, या security से compromise किए। + +और आप OAuth2 जैसे secure, standard protocols को अपेक्षाकृत simple तरीके से उपयोग और implement कर सकते हैं। + +आप **Advanced User Guide** में और सीख सकते हैं कि अधिक fine-grained permission system के लिए OAuth2 "scopes" का उपयोग कैसे करें, इन्हीं standards का पालन करते हुए। Scopes के साथ OAuth2 वह mechanism है जिसका उपयोग कई बड़े authentication providers, जैसे Facebook, Google, GitHub, Microsoft, X (Twitter), आदि करते हैं, ताकि third party applications को अपने users की ओर से उनकी APIs के साथ interact करने के लिए authorize किया जा सके। diff --git a/docs/hi/docs/tutorial/security/simple-oauth2.md b/docs/hi/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..87c9a4a28 --- /dev/null +++ b/docs/hi/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,289 @@ +# Password और Bearer के साथ सरल OAuth2 { #simple-oauth2-with-password-and-bearer } + +अब पिछले अध्याय से आगे बढ़ते हैं और एक पूरा security flow बनाने के लिए छूटे हुए हिस्से जोड़ते हैं। + +## `username` और `password` प्राप्त करें { #get-the-username-and-password } + +हम `username` और `password` प्राप्त करने के लिए **FastAPI** security utilities का उपयोग करने वाले हैं। + +OAuth2 निर्दिष्ट करता है कि "password flow" (जिसका हम उपयोग कर रहे हैं) का उपयोग करते समय client/user को `username` और `password` fields को form data के रूप में भेजना होगा। + +और spec कहता है कि fields के नाम ऐसे ही होने चाहिए। इसलिए `user-name` या `email` काम नहीं करेगा। + +लेकिन चिंता न करें, frontend में आप इसे अपने अंतिम users को जैसे चाहें दिखा सकते हैं। + +और आपके database models कोई भी दूसरे नाम उपयोग कर सकते हैं जो आप चाहें। + +लेकिन login *path operation* के लिए, हमें spec के साथ compatible होने के लिए इन नामों का उपयोग करना होगा (और उदाहरण के लिए, integrated API documentation system का उपयोग कर पाने के लिए)। + +Spec यह भी बताता है कि `username` और `password` को form data के रूप में भेजा जाना चाहिए (इसलिए, यहाँ कोई JSON नहीं)। + +### `scope` { #scope } + +Spec यह भी कहता है कि client एक और form field "`scope`" भेज सकता है। + +form field का नाम `scope` है (singular में), लेकिन यह वास्तव में spaces से अलग किए गए "scopes" वाली एक लंबी string होती है। + +हर "scope" बस एक string है (बिना spaces के)। + +इनका सामान्यतः विशिष्ट security permissions घोषित करने के लिए उपयोग किया जाता है, उदाहरण के लिए: + +* `users:read` या `users:write` आम उदाहरण हैं। +* `instagram_basic` Facebook / Instagram द्वारा उपयोग किया जाता है। +* `https://www.googleapis.com/auth/drive` Google द्वारा उपयोग किया जाता है। + +/// note | नोट + +OAuth2 में "scope" बस एक string है जो किसी विशिष्ट required permission को घोषित करती है। + +इससे फर्क नहीं पड़ता कि उसमें `:` जैसे अन्य characters हैं या वह URL है। + +वे details implementation specific हैं। + +OAuth2 के लिए वे बस strings हैं। + +/// + +## `username` और `password` प्राप्त करने का Code { #code-to-get-the-username-and-password } + +अब इसे संभालने के लिए **FastAPI** द्वारा प्रदान की गई utilities का उपयोग करते हैं। + +### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform } + +पहले, `OAuth2PasswordRequestForm` import करें, और `/token` के *path operation* में `Depends` के साथ इसे dependency के रूप में उपयोग करें: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} + +`OAuth2PasswordRequestForm` एक class dependency है जो एक form body घोषित करती है जिसमें: + +* `username`। +* `password`। +* एक वैकल्पिक `scope` field, एक बड़ी string के रूप में, जो spaces से अलग की गई strings से बनी होती है। +* एक वैकल्पिक `grant_type`। + +/// tip | टिप + +OAuth2 spec वास्तव में fixed value `password` के साथ एक field `grant_type` *required* करता है, लेकिन `OAuth2PasswordRequestForm` इसे enforce नहीं करता। + +अगर आपको इसे enforce करना है, तो `OAuth2PasswordRequestForm` की जगह `OAuth2PasswordRequestFormStrict` का उपयोग करें। + +/// + +* एक वैकल्पिक `client_id` (हमारे उदाहरण के लिए हमें इसकी आवश्यकता नहीं है)। +* एक वैकल्पिक `client_secret` (हमारे उदाहरण के लिए हमें इसकी आवश्यकता नहीं है)। + +/// note | नोट + +`OAuth2PasswordRequestForm`, **FastAPI** के लिए कोई विशेष class नहीं है जैसे `OAuth2PasswordBearer` है। + +`OAuth2PasswordBearer` **FastAPI** को बताता है कि यह एक security scheme है। इसलिए इसे OpenAPI में इस तरह जोड़ा जाता है। + +लेकिन `OAuth2PasswordRequestForm` बस एक class dependency है जिसे आप खुद भी लिख सकते थे, या आप सीधे `Form` parameters घोषित कर सकते थे। + +लेकिन क्योंकि यह एक सामान्य use case है, इसे आसान बनाने के लिए **FastAPI** द्वारा सीधे प्रदान किया गया है। + +/// + +### form data का उपयोग करें { #use-the-form-data } + +/// tip | टिप + +dependency class `OAuth2PasswordRequestForm` के instance में spaces से अलग की गई लंबी string वाला attribute `scope` नहीं होगा, इसके बजाय, इसमें भेजे गए प्रत्येक scope के लिए actual strings की list वाला `scopes` attribute होगा। + +हम इस उदाहरण में `scopes` का उपयोग नहीं कर रहे हैं, लेकिन यदि आपको इसकी आवश्यकता हो तो functionality उपलब्ध है। + +/// + +अब, form field से `username` का उपयोग करके (fake) database से user data प्राप्त करें। + +यदि ऐसा कोई user नहीं है, तो हम "Incorrect username or password" कहते हुए error लौटाते हैं। + +Error के लिए, हम exception `HTTPException` का उपयोग करते हैं: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} + +### password जाँचें { #check-the-password } + +इस समय हमारे पास database से user data है, लेकिन हमने password नहीं जाँचा है। + +पहले उस data को Pydantic `UserInDB` model में डालते हैं। + +आपको कभी भी plaintext passwords save नहीं करने चाहिए, इसलिए, हम (fake) password hashing system का उपयोग करेंगे। + +यदि passwords match नहीं करते, तो हम वही error लौटाते हैं। + +#### Password hashing { #password-hashing } + +"Hashing" का मतलब है: कुछ content (इस मामले में password) को bytes की sequence (बस एक string) में convert करना जो बेतरतीब दिखती है। + +जब भी आप बिल्कुल वही content (बिल्कुल वही password) पास करते हैं, तो आपको बिल्कुल वही बेतरतीब string मिलती है। + +लेकिन आप उस बेतरतीब string से वापस password में convert नहीं कर सकते। + +##### Password hashing का उपयोग क्यों करें { #why-use-password-hashing } + +अगर आपका database चोरी हो जाता है, तो चोर के पास आपके users के plaintext passwords नहीं होंगे, केवल hashes होंगे। + +इसलिए, चोर उन same passwords को किसी दूसरे system में उपयोग करने की कोशिश नहीं कर पाएगा (क्योंकि कई users हर जगह वही password उपयोग करते हैं, यह खतरनाक होगा)। + +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} + +#### `**user_dict` के बारे में { #about-user-dict } + +`UserInDB(**user_dict)` का मतलब है: + +*`user_dict` की keys और values को सीधे key-value arguments के रूप में पास करें, इसके बराबर:* + +```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"], +) +``` + +/// note | नोट + +`**user_dict` की अधिक पूरी explanation के लिए [**Extra Models** के documentation](../extra-models.md#about-user-in-model-dump) में वापस देखें। + +/// + +## token लौटाएँ { #return-the-token } + +`token` endpoint का response एक JSON object होना चाहिए। + +इसमें `token_type` होना चाहिए। हमारे मामले में, क्योंकि हम "Bearer" tokens का उपयोग कर रहे हैं, token type "`bearer`" होना चाहिए। + +और इसमें `access_token` होना चाहिए, जिसमें हमारे access token वाली एक string हो। + +इस सरल उदाहरण के लिए, हम बस पूरी तरह insecure रहेंगे और token के रूप में वही `username` लौटाएँगे। + +/// tip | टिप + +अगले अध्याय में, आप password hashing और JWT tokens के साथ एक वास्तविक secure implementation देखेंगे। + +लेकिन अभी के लिए, आइए उन specific details पर ध्यान दें जिनकी हमें आवश्यकता है। + +/// + +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} + +/// tip | टिप + +Spec के अनुसार, आपको `access_token` और `token_type` के साथ एक JSON लौटाना चाहिए, बिल्कुल इस उदाहरण की तरह। + +यह कुछ ऐसा है जो आपको अपने code में स्वयं करना होगा, और सुनिश्चित करना होगा कि आप उन JSON keys का उपयोग करें। + +Specifications के compliant होने के लिए, यह लगभग एकमात्र चीज है जिसे आपको सही तरीके से खुद करना याद रखना होगा। + +बाकी सब **FastAPI** आपके लिए संभालता है। + +/// + +## dependencies अपडेट करें { #update-the-dependencies } + +अब हम अपनी dependencies अपडेट करने वाले हैं। + +हम `current_user` को *केवल* तब प्राप्त करना चाहते हैं जब यह user active हो। + +इसलिए, हम एक अतिरिक्त dependency `get_current_active_user` बनाते हैं जो बदले में `get_current_user` को dependency के रूप में उपयोग करती है। + +ये दोनों dependencies बस एक HTTP error लौटाएँगी यदि user मौजूद नहीं है, या inactive है। + +इसलिए, हमारे endpoint में, हमें user केवल तभी मिलेगा जब user मौजूद हो, सही तरीके से authenticated हो, और active हो: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} + +/// note | नोट + +Value `Bearer` के साथ अतिरिक्त header `WWW-Authenticate`, जिसे हम यहाँ लौटा रहे हैं, spec का भी हिस्सा है। + +किसी भी HTTP (error) status code 401 "UNAUTHORIZED" को `WWW-Authenticate` header भी लौटाना चाहिए। + +Bearer tokens (हमारे मामले) में, उस header की value `Bearer` होनी चाहिए। + +आप वास्तव में उस अतिरिक्त header को छोड़ सकते हैं और फिर भी यह काम करेगा। + +लेकिन specifications के compliant होने के लिए इसे यहाँ प्रदान किया गया है। + +साथ ही, ऐसे tools हो सकते हैं जो इसकी अपेक्षा करते हैं और इसका उपयोग करते हैं (अभी या भविष्य में) और यह आपके या आपके users के लिए उपयोगी हो सकता है, अभी या भविष्य में। + +यही standards का लाभ है... + +/// + +## इसे काम करते देखें { #see-it-in-action } + +Interactive docs खोलें: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)। + +### Authenticate करें { #authenticate } + +"Authorize" button पर click करें। + +Credentials का उपयोग करें: + +User: `johndoe` + +Password: `secret` + + + +System में authenticate होने के बाद, आप इसे ऐसे देखेंगे: + + + +### अपना user data प्राप्त करें { #get-your-own-user-data } + +अब path `/users/me` के साथ operation `GET` का उपयोग करें। + +आपको अपने user का data मिलेगा, जैसे: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +यदि आप lock icon पर click करके logout करते हैं, और फिर वही operation दोबारा आज़माते हैं, तो आपको HTTP 401 error मिलेगा: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Inactive user { #inactive-user } + +अब एक inactive user के साथ प्रयास करें, इनके साथ authenticate करें: + +User: `alice` + +Password: `secret2` + +और path `/users/me` के साथ operation `GET` का उपयोग करने का प्रयास करें। + +आपको "Inactive user" error मिलेगा, जैसे: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Recap { #recap } + +अब आपके पास अपनी API के लिए `username` और `password` पर आधारित एक पूरा security system implement करने के tools हैं। + +इन tools का उपयोग करके, आप security system को किसी भी database और किसी भी user या data model के साथ compatible बना सकते हैं। + +एकमात्र detail जो missing है वह यह है कि यह अभी वास्तव में "secure" नहीं है। + +अगले अध्याय में आप देखेंगे कि secure password hashing library और JWT tokens का उपयोग कैसे करें। diff --git a/docs/hi/docs/tutorial/server-sent-events.md b/docs/hi/docs/tutorial/server-sent-events.md new file mode 100644 index 000000000..cb23938df --- /dev/null +++ b/docs/hi/docs/tutorial/server-sent-events.md @@ -0,0 +1,120 @@ +# Server-Sent Events (SSE) { #server-sent-events-sse } + +आप **Server-Sent Events** (SSE) का उपयोग करके client को data stream कर सकते हैं। + +यह [Stream JSON Lines](stream-json-lines.md) जैसा है, लेकिन `text/event-stream` format का उपयोग करता है, जिसे browsers [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) के साथ natively support करते हैं। + +/// note | नोट + +FastAPI 0.135.0 में जोड़ा गया। + +/// + +## Server-Sent Events क्या हैं? { #what-are-server-sent-events } + +SSE, HTTP के माध्यम से server से client तक data stream करने के लिए एक standard है। + +हर event एक छोटा text block होता है जिसमें `data`, `event`, `id`, और `retry` जैसे "fields" होते हैं, जिन्हें खाली lines से अलग किया जाता है। + +यह ऐसा दिखता है: + +``` +data: {"name": "Portal Gun", "price": 999.99} + +data: {"name": "Plumbus", "price": 32.99} + +``` + +SSE का उपयोग आमतौर पर AI chat streaming, live notifications, logs और observability, और अन्य मामलों में किया जाता है जहाँ server client को updates push करता है। + +/// tip | सुझाव + +अगर आप binary data stream करना चाहते हैं, जैसे video या audio, तो advanced guide देखें: [Data Stream करें](../advanced/stream-data.md). + +/// + +## FastAPI के साथ SSE Stream करें { #stream-sse-with-fastapi } + +FastAPI के साथ SSE stream करने के लिए, अपनी *path operation function* में `yield` का उपयोग करें और `response_class=EventSourceResponse` set करें। + +`EventSourceResponse` को `fastapi.sse` से import करें: + +{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[4,22] *} + +हर yielded item को JSON के रूप में encode किया जाता है और SSE event के `data:` field में भेजा जाता है। + +अगर आप return type को `AsyncIterable[Item]` के रूप में declare करते हैं, तो FastAPI इसका उपयोग Pydantic के साथ data को **validate**, **document**, और **serialize** करने के लिए करेगा। + +{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *} + +/// tip | सुझाव + +क्योंकि Pydantic इसे **Rust** side में serialize करेगा, आपको return type declare न करने की तुलना में कहीं बेहतर **performance** मिलेगी। + +/// + +### Non-async *path operation functions* { #non-async-path-operation-functions } + +आप नियमित `def` functions (बिना `async`) का भी उपयोग कर सकते हैं, और उसी तरह `yield` का उपयोग कर सकते हैं। + +FastAPI सुनिश्चित करेगा कि यह सही तरीके से run हो ताकि यह event loop को block न करे। + +क्योंकि इस मामले में function async नहीं है, सही return type `Iterable[Item]` होगा: + +{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[28:31] hl[29] *} + +### कोई Return Type नहीं { #no-return-type } + +आप return type को छोड़ भी सकते हैं। FastAPI data को convert करने और भेजने के लिए [`jsonable_encoder`](./encoder.md) का उपयोग करेगा। + +{* ../../docs_src/server_sent_events/tutorial001_py310.py ln[34:37] hl[35] *} + +## `ServerSentEvent` { #serversentevent } + +अगर आपको `event`, `id`, `retry`, या `comment` जैसे SSE fields set करने की ज़रूरत है, तो आप plain data के बजाय `ServerSentEvent` objects yield कर सकते हैं। + +`ServerSentEvent` को `fastapi.sse` से import करें: + +{* ../../docs_src/server_sent_events/tutorial002_py310.py hl[4,26] *} + +`data` field हमेशा JSON के रूप में encode किया जाता है। आप कोई भी value pass कर सकते हैं जिसे JSON के रूप में serialize किया जा सकता हो, जिसमें Pydantic models भी शामिल हैं। + +## Raw Data { #raw-data } + +अगर आपको JSON encoding के **बिना** data भेजना है, तो `data` के बजाय `raw_data` का उपयोग करें। + +यह pre-formatted text, log lines, या `[DONE]` जैसे विशेष "sentinel" values भेजने के लिए उपयोगी है। + +{* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *} + +/// note | नोट + +`data` और `raw_data` mutually exclusive हैं। आप हर `ServerSentEvent` पर उनमें से केवल एक ही set कर सकते हैं। + +/// + +## `Last-Event-ID` के साथ फिर से शुरू करना { #resuming-with-last-event-id } + +जब कोई browser connection drop होने के बाद reconnect करता है, तो वह अंतिम प्राप्त `id` को `Last-Event-ID` header में भेजता है। + +आप इसे header parameter के रूप में read कर सकते हैं और stream को वहाँ से resume करने के लिए उपयोग कर सकते हैं जहाँ client ने छोड़ा था: + +{* ../../docs_src/server_sent_events/tutorial004_py310.py hl[25,27,31] *} + +## POST के साथ SSE { #sse-with-post } + +SSE **किसी भी HTTP method** के साथ काम करता है, केवल `GET` के साथ नहीं। + +यह [MCP](https://modelcontextprotocol.io) जैसे protocols के लिए उपयोगी है, जो `POST` पर SSE stream करते हैं: + +{* ../../docs_src/server_sent_events/tutorial005_py310.py hl[14] *} + +## तकनीकी विवरण { #technical-details } + +FastAPI कुछ SSE best practices को out of the box implement करता है। + +* जब कोई message नहीं आया हो, तो हर 15 सेकंड में **"keep alive" `ping` comment** भेजें, ताकि कुछ proxies connection को close न कर दें, जैसा कि [HTML specification: Server-Sent Events](https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes) में सुझाया गया है। +* stream की **caching रोकने** के लिए `Cache-Control: no-cache` header set करें। +* Nginx जैसे कुछ proxies में **buffering रोकने** के लिए एक special header `X-Accel-Buffering: no` set करें। + +आपको इसके लिए कुछ भी करने की ज़रूरत नहीं है, यह out of the box काम करता है। 🤓 diff --git a/docs/hi/docs/tutorial/sql-databases.md b/docs/hi/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..041da16e9 --- /dev/null +++ b/docs/hi/docs/tutorial/sql-databases.md @@ -0,0 +1,357 @@ +# SQL (Relational) डेटाबेस { #sql-relational-databases } + +**FastAPI** के लिए SQL (relational) डेटाबेस इस्तेमाल करना required नहीं है। लेकिन आप **कोई भी डेटाबेस** इस्तेमाल कर सकते हैं जो आप चाहें। + +यहाँ हम [SQLModel](https://sqlmodel.tiangolo.com/) का उपयोग करके एक उदाहरण देखेंगे। + +**SQLModel**, [SQLAlchemy](https://www.sqlalchemy.org/) और Pydantic के ऊपर बना है। इसे **FastAPI** के उसी लेखक ने बनाया है ताकि यह उन FastAPI applications के लिए perfect match हो जिन्हें **SQL databases** इस्तेमाल करने की जरूरत होती है। + +/// tip | टिप + +आप अपनी पसंद की कोई भी दूसरी SQL या NoSQL डेटाबेस लाइब्रेरी इस्तेमाल कर सकते हैं (कुछ मामलों में इन्हें "ORMs" कहा जाता है), FastAPI आपको कुछ भी इस्तेमाल करने के लिए मजबूर नहीं करता। 😎 + +/// + +क्योंकि SQLModel, SQLAlchemy पर आधारित है, आप SQLAlchemy द्वारा **supported कोई भी डेटाबेस** आसानी से इस्तेमाल कर सकते हैं (जिससे वे SQLModel द्वारा भी supported हो जाते हैं), जैसे: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server, आदि। + +इस उदाहरण में, हम **SQLite** इस्तेमाल करेंगे, क्योंकि यह एक single file का उपयोग करता है और Python में इसके लिए integrated support है। इसलिए, आप इस उदाहरण को copy कर सकते हैं और जैसा है वैसा ही run कर सकते हैं। + +बाद में, अपनी production application के लिए, आप **PostgreSQL** जैसा database server इस्तेमाल करना चाह सकते हैं। + +/// tip | टिप + +**FastAPI** और **PostgreSQL** के साथ एक official project generator है जिसमें frontend और अधिक tools शामिल हैं: [https://github.com/fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template) + +/// + +यह एक बहुत ही सरल और छोटा tutorial है, अगर आप सामान्य रूप से databases, SQL, या अधिक advanced features के बारे में सीखना चाहते हैं, तो [SQLModel docs](https://sqlmodel.tiangolo.com/) पर जाएँ। + +## `SQLModel` install करें { #install-sqlmodel } + +सबसे पहले, सुनिश्चित करें कि आप अपना [virtual environment](../virtual-environments.md) बनाएँ, उसे activate करें, और फिर `sqlmodel` install करें: + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## Single Model के साथ App बनाएँ { #create-the-app-with-a-single-model } + +हम पहले एक single **SQLModel** model के साथ app का सबसे सरल पहला version बनाएँगे। + +बाद में हम नीचे **multiple models** के साथ security और versatility बढ़ाते हुए इसे बेहतर बनाएँगे। 🤓 + +### Models बनाएँ { #create-models } + +`SQLModel` import करें और एक डेटाबेस model बनाएँ: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +`Hero` class एक Pydantic model से बहुत मिलती-जुलती है (वास्तव में, अंदर से, यह सच में *एक Pydantic model ही है*)। + +कुछ अंतर हैं: + +* `table=True` SQLModel को बताता है कि यह एक *table model* है, इसे SQL डेटाबेस में एक **table** को represent करना चाहिए, यह सिर्फ एक *data model* नहीं है (जैसा कि कोई भी दूसरी regular Pydantic class होती)। + +* `Field(primary_key=True)` SQLModel को बताता है कि `id` SQL डेटाबेस में **primary key** है (आप SQL primary keys के बारे में SQLModel docs में अधिक जान सकते हैं)। + + **ध्यान दें:** हम primary key field के लिए `int | None` का उपयोग करते हैं ताकि Python code में हम *बिना `id` के object बना सकें* (`id=None`), यह मानते हुए कि डेटाबेस *save करते समय इसे generate करेगा*। SQLModel समझता है कि डेटाबेस `id` provide करेगा और डेटाबेस schema में *column को non-null `INTEGER` के रूप में define करता है*। विवरण के लिए [primary keys पर SQLModel docs](https://sqlmodel.tiangolo.com/tutorial/create-db-and-table/#primary-key-id) देखें। + +* `Field(index=True)` SQLModel को बताता है कि उसे इस column के लिए एक **SQL index** बनाना चाहिए, जिससे इस column द्वारा filtered data पढ़ते समय डेटाबेस में तेज़ lookups हो सकें। + + SQLModel जान जाएगा कि `str` के रूप में declared कोई चीज़ `TEXT` type का SQL column होगी (या डेटाबेस के आधार पर `VARCHAR`)। + +### Engine बनाएँ { #create-an-engine } + +SQLModel `engine` (अंदर से यह वास्तव में SQLAlchemy `engine` है) वह है जो डेटाबेस से **connections को hold** करता है। + +आपके सभी code के लिए उसी डेटाबेस से connect करने हेतु **एक single `engine` object** होगा। + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +`check_same_thread=False` का उपयोग FastAPI को अलग-अलग threads में वही SQLite डेटाबेस इस्तेमाल करने देता है। यह necessary है क्योंकि **एक single request** **एक से अधिक thread** का उपयोग कर सकती है (उदाहरण के लिए dependencies में)। + +चिंता न करें, code जिस तरह structured है, उससे हम सुनिश्चित करेंगे कि बाद में हम **प्रति request एक single SQLModel *session*** इस्तेमाल करें, वास्तव में `check_same_thread` यही हासिल करने की कोशिश कर रहा है। + +### Tables बनाएँ { #create-the-tables } + +फिर हम एक function जोड़ते हैं जो सभी *table models* के लिए **tables बनाने** हेतु `SQLModel.metadata.create_all(engine)` का उपयोग करता है। + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### Session Dependency बनाएँ { #create-a-session-dependency } + +**`Session`** वह है जो **objects को memory में store** करता है और data में required किसी भी बदलाव का track रखता है, फिर यह डेटाबेस से communicate करने के लिए **`engine` का उपयोग करता है**। + +हम `yield` के साथ एक FastAPI **dependency** बनाएँगे जो हर request के लिए एक नया `Session` provide करेगी। यही सुनिश्चित करता है कि हम प्रति request एक single session इस्तेमाल करें। 🤓 + +फिर हम इस dependency का उपयोग करने वाले बाकी code को आसान बनाने के लिए एक `Annotated` dependency `SessionDep` बनाते हैं। + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### Startup पर Database Tables बनाएँ { #create-database-tables-on-startup } + +हम application शुरू होने पर database tables बनाएँगे। + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +यहाँ हम application startup event पर tables बनाते हैं। + +production के लिए आप शायद एक migration script इस्तेमाल करेंगे जो आपका app शुरू करने से पहले run होती है। 🤓 + +/// tip | टिप + +SQLModel में Alembic को wrap करने वाली migration utilities होंगी, लेकिन अभी के लिए, आप सीधे [Alembic](https://alembic.sqlalchemy.org/en/latest/) इस्तेमाल कर सकते हैं। + +/// + +### Hero बनाएँ { #create-a-hero } + +क्योंकि हर SQLModel model एक Pydantic model भी है, आप इसे उसी **type annotations** में इस्तेमाल कर सकते हैं जिनमें आप Pydantic models इस्तेमाल करते। + +उदाहरण के लिए, अगर आप `Hero` type का parameter declare करते हैं, तो यह **JSON body** से read किया जाएगा। + +उसी तरह, आप इसे function के **return type** के रूप में declare कर सकते हैं, और फिर data का shape automatic API docs UI में दिखाई देगा। + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + +यहाँ हम `SessionDep` dependency (एक `Session`) का उपयोग करके नए `Hero` को `Session` instance में add करते हैं, changes को डेटाबेस में commit करते हैं, `hero` में data refresh करते हैं, और फिर उसे return करते हैं। + +### Heroes पढ़ें { #read-heroes } + +हम `select()` का उपयोग करके डेटाबेस से `Hero`s **read** कर सकते हैं। results को paginate करने के लिए हम `limit` और `offset` include कर सकते हैं। + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### एक Hero पढ़ें { #read-one-hero } + +हम एक single `Hero` **read** कर सकते हैं। + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### Hero Delete करें { #delete-a-hero } + +हम एक `Hero` को **delete** भी कर सकते हैं। + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### App Run करें { #run-the-app } + +आप app run कर सकते हैं: + +
+ +```console +$ fastapi dev + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +फिर `/docs` UI पर जाएँ, आप देखेंगे कि **FastAPI** API को **document** करने के लिए इन **models** का उपयोग कर रहा है, और यह data को **serialize** और **validate** करने के लिए भी इनका उपयोग करेगा। + +
+ +
+ +## Multiple Models के साथ App Update करें { #update-the-app-with-multiple-models } + +अब आइए **security** और **versatility** बढ़ाने के लिए इस app को थोड़ा **refactor** करें। + +अगर आप previous app देखें, तो UI में आप देख सकते हैं कि अभी तक यह client को बनने वाले `Hero` का `id` तय करने देता है। 😱 + +हमें ऐसा नहीं होने देना चाहिए, वे DB में पहले से assigned किसी `id` को overwrite कर सकते हैं। `id` तय करना **backend** या **database** द्वारा किया जाना चाहिए, **client द्वारा नहीं**। + +इसके अलावा, हम hero के लिए `secret_name` बनाते हैं, लेकिन अब तक, हम इसे हर जगह return कर रहे हैं, यह बहुत **secret** नहीं है... 😅 + +हम कुछ **extra models** जोड़कर इन चीज़ों को ठीक करेंगे। यहीं SQLModel चमकेगा। ✨ + +### Multiple Models बनाएँ { #create-multiple-models } + +**SQLModel** में, कोई भी model class जिसमें `table=True` है, एक **table model** है। + +और कोई भी model class जिसमें `table=True` नहीं है, एक **data model** है, ये वास्तव में सिर्फ Pydantic models हैं (कुछ छोटे extra features के साथ)। 🤓 + +SQLModel के साथ, हम सभी मामलों में सभी fields को **duplicate करने से बचने** के लिए **inheritance** का उपयोग कर सकते हैं। + +#### `HeroBase` - base class { #herobase-the-base-class } + +आइए एक `HeroBase` model से शुरू करें जिसमें सभी models द्वारा **shared fields** हों: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### `Hero` - *table model* { #hero-the-table-model } + +फिर आइए `Hero` बनाएँ, वास्तविक *table model*, जिसमें वे **extra fields** हों जो हमेशा दूसरे models में नहीं होते: + +* `id` +* `secret_name` + +क्योंकि `Hero`, `HeroBase` से inherit करता है, इसमें `HeroBase` में declared **fields** भी हैं, इसलिए `Hero` के लिए सभी fields हैं: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### `HeroPublic` - public *data model* { #heropublic-the-public-data-model } + +इसके बाद, हम एक `HeroPublic` model बनाते हैं, यही वह है जो API के clients को **return** किया जाएगा। + +इसमें `HeroBase` जैसे ही fields हैं, इसलिए इसमें `secret_name` शामिल नहीं होगा। + +आख़िरकार, हमारे heroes की identity protected है! 🥷 + +यह `id: int` को फिर से declare भी करता है। ऐसा करके, हम API clients के साथ एक **contract** बना रहे हैं, ताकि वे हमेशा expect कर सकें कि `id` मौजूद होगा और `int` होगा (यह कभी `None` नहीं होगा)। + +/// tip | टिप + +return model से यह सुनिश्चित करवाना कि कोई value हमेशा available है और हमेशा `int` है (`None` नहीं), API clients के लिए बहुत उपयोगी है, वे इस certainty के साथ बहुत सरल code लिख सकते हैं। + +साथ ही, **automatically generated clients** में सरल interfaces होंगे, ताकि आपकी API से communicate करने वाले developers आपकी API के साथ काम करते समय बहुत बेहतर अनुभव पा सकें। 😎 + +/// + +`HeroPublic` में सभी fields `HeroBase` जैसे ही हैं, जिसमें `id` को `int` (`None` नहीं) के रूप में declared किया गया है: + +* `id` +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### `HeroCreate` - hero बनाने के लिए *data model* { #herocreate-the-data-model-to-create-a-hero } + +अब हम एक `HeroCreate` model बनाते हैं, यही वह है जो clients से आने वाले data को **validate** करेगा। + +इसमें `HeroBase` जैसे ही fields हैं, और इसमें `secret_name` भी है। + +अब, जब clients **एक नया hero create** करेंगे, वे `secret_name` भेजेंगे, यह डेटाबेस में store होगा, लेकिन वे secret names API में clients को return नहीं किए जाएँगे। + +/// tip | टिप + +आप **passwords** को ऐसे handle करेंगे। उन्हें receive करें, लेकिन API में return न करें। + +आप passwords की values को store करने से पहले **hash** भी करेंगे, **उन्हें plain text में कभी store न करें**। + +/// + +`HeroCreate` के fields हैं: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### `HeroUpdate` - hero update करने के लिए *data model* { #heroupdate-the-data-model-to-update-a-hero } + +app के previous version में हमारे पास **hero update करने** का तरीका नहीं था, लेकिन अब **multiple models** के साथ, हम ऐसा कर सकते हैं। 🎉 + +`HeroUpdate` *data model* थोड़ा special है, इसमें **वे सभी same fields** हैं जिनकी एक नया hero create करने के लिए जरूरत होगी, लेकिन सभी fields **optional** हैं (उन सभी की default value है)। इस तरह, जब आप hero update करते हैं, तो आप सिर्फ वे fields भेज सकते हैं जिन्हें आप update करना चाहते हैं। + +क्योंकि सभी **fields वास्तव में change होते हैं** (type में अब `None` शामिल है और अब उनकी default value `None` है), हमें उन्हें **re-declare** करना होगा। + +हमें वास्तव में `HeroBase` से inherit करने की जरूरत नहीं है क्योंकि हम सभी fields को re-declare कर रहे हैं। मैं consistency के लिए इसे inherit करता हुआ छोड़ूँगा, लेकिन यह necessary नहीं है। यह personal taste का मामला अधिक है। 🤷 + +`HeroUpdate` के fields हैं: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### `HeroCreate` के साथ create करें और `HeroPublic` return करें { #create-with-herocreate-and-return-a-heropublic } + +अब जब हमारे पास **multiple models** हैं, हम app के उन parts को update कर सकते हैं जो उनका उपयोग करते हैं। + +हम request में एक `HeroCreate` *data model* receive करते हैं, और उससे, हम एक `Hero` *table model* बनाते हैं। + +इस नए *table model* `Hero` में client द्वारा भेजे गए fields होंगे, और इसमें डेटाबेस द्वारा generated एक `id` भी होगा। + +फिर हम उसी *table model* `Hero` को function से जैसा है वैसा ही return करते हैं। लेकिन क्योंकि हम `response_model` को `HeroPublic` *data model* के साथ declare करते हैं, **FastAPI** data को validate और serialize करने के लिए `HeroPublic` का उपयोग करेगा। + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip | टिप + +अब हम **return type annotation** `-> HeroPublic` के बजाय `response_model=HeroPublic` इस्तेमाल करते हैं क्योंकि जो value हम return कर रहे हैं वह वास्तव में `HeroPublic` *नहीं* है। + +अगर हमने `-> HeroPublic` declare किया होता, तो आपका editor और linter complain करते (और सही करते) कि आप `HeroPublic` के बजाय `Hero` return कर रहे हैं। + +इसे `response_model` में declare करके हम **FastAPI** को अपना काम करने के लिए कह रहे हैं, बिना type annotations और आपके editor व अन्य tools से मिलने वाली help में interfere किए। + +/// + +### `HeroPublic` के साथ Heroes पढ़ें { #read-heroes-with-heropublic } + +हम `Hero`s को **read** करने के लिए पहले जैसा ही कर सकते हैं, फिर से, हम यह सुनिश्चित करने के लिए `response_model=list[HeroPublic]` का उपयोग करते हैं कि data सही तरीके से validate और serialize हो। + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### `HeroPublic` के साथ एक Hero पढ़ें { #read-one-hero-with-heropublic } + +हम एक single hero **read** कर सकते हैं: + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### `HeroUpdate` के साथ Hero Update करें { #update-a-hero-with-heroupdate } + +हम **hero update** कर सकते हैं। इसके लिए हम HTTP `PATCH` operation इस्तेमाल करते हैं। + +और code में, हमें client द्वारा भेजे गए सभी data के साथ एक `dict` मिलता है, **सिर्फ client द्वारा भेजा गया data**, उन किसी भी values को exclude करते हुए जो सिर्फ default values होने के कारण वहाँ होतीं। ऐसा करने के लिए हम `exclude_unset=True` इस्तेमाल करते हैं। यही main trick है। 🪄 + +फिर हम `hero_data` के data के साथ `hero_db` को update करने के लिए `hero_db.sqlmodel_update(hero_data)` इस्तेमाल करते हैं। + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### फिर से Hero Delete करें { #delete-a-hero-again } + +hero को **delete करना** लगभग पहले जैसा ही रहता है। + +हम इसमें सब कुछ refactor करने की इच्छा पूरी नहीं करेंगे। 😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### App फिर से Run करें { #run-the-app-again } + +आप app फिर से run कर सकते हैं: + +
+ +```console +$ fastapi dev + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +अगर आप `/docs` API UI पर जाते हैं, तो आप देखेंगे कि यह अब updated है, और hero create करते समय यह client से `id` receive करने की expect नहीं करेगा, आदि। + +
+ +
+ +## Recap { #recap } + +आप SQL डेटाबेस के साथ interact करने और code को *data models* और *table models* के साथ सरल बनाने के लिए [**SQLModel**](https://sqlmodel.tiangolo.com/) का उपयोग कर सकते हैं। + +आप **SQLModel** docs में बहुत कुछ और सीख सकते हैं, वहाँ **FastAPI** के साथ SQLModel इस्तेमाल करने पर एक लंबा mini [tutorial](https://sqlmodel.tiangolo.com/tutorial/fastapi/) है। 🚀 diff --git a/docs/hi/docs/tutorial/static-files.md b/docs/hi/docs/tutorial/static-files.md new file mode 100644 index 000000000..6a41c900a --- /dev/null +++ b/docs/hi/docs/tutorial/static-files.md @@ -0,0 +1,48 @@ +# Static Files { #static-files } + +आप `StaticFiles` का उपयोग करके किसी directory से static files को अपने-आप serve कर सकते हैं। + +/// tip | सुझाव + +अगर आपको frontend host करना है, तो इसके बजाय `app.frontend()` का उपयोग करें, इसके बारे में [Frontend](frontend.md) में पढ़ें। + +`app.frontend()` अंदरूनी तौर पर `StaticFiles` का उपयोग करता है, जिसमें frontends के लिए कई अतिरिक्त फायदे होते हैं, जैसे client-side routing को handle करना। + +/// + +## `StaticFiles` का उपयोग करें { #use-staticfiles } + +* `StaticFiles` import करें। +* किसी विशिष्ट path में `StaticFiles()` instance को "Mount" करें। + +{* ../../docs_src/static_files/tutorial001_py310.py hl[2,6] *} + +/// note | तकनीकी विवरण + +आप `from starlette.staticfiles import StaticFiles` भी उपयोग कर सकते हैं। + +**FastAPI** आपकी, developer की, सुविधा के लिए वही `starlette.staticfiles` `fastapi.staticfiles` के रूप में प्रदान करता है। लेकिन यह वास्तव में सीधे Starlette से आता है। + +/// + +### "Mounting" क्या है { #what-is-mounting } + +"Mounting" का मतलब है किसी विशिष्ट path में एक पूरी "independent" application जोड़ना, जो फिर सभी sub-paths को handle करने का काम करती है। + +यह `APIRouter` का उपयोग करने से अलग है, क्योंकि mounted application पूरी तरह independent होती है। आपकी main application की OpenAPI और docs में mounted application से कुछ भी शामिल नहीं होगा, आदि। + +आप इसके बारे में [Advanced User Guide](../advanced/index.md) में और पढ़ सकते हैं। + +## विवरण { #details } + +पहला `"/static"` उस sub-path को संदर्भित करता है जिस पर यह "sub-application" "mount" की जाएगी। इसलिए, `"/static"` से शुरू होने वाला कोई भी path इसके द्वारा handle किया जाएगा। + +`directory="static"` उस directory के नाम को संदर्भित करता है जिसमें आपकी static files होती हैं। + +`name="static"` इसे एक नाम देता है, जिसे **FastAPI** द्वारा internally उपयोग किया जा सकता है। + +ये सभी parameters "`static`" से अलग हो सकते हैं, इन्हें अपनी application की जरूरतों और विशिष्ट विवरणों के अनुसार adjust करें। + +## अधिक जानकारी { #more-info } + +अधिक विवरण और options के लिए [Static Files के बारे में Starlette की docs](https://www.starlette.dev/staticfiles/) देखें। diff --git a/docs/hi/docs/tutorial/stream-json-lines.md b/docs/hi/docs/tutorial/stream-json-lines.md new file mode 100644 index 000000000..9d0645fc5 --- /dev/null +++ b/docs/hi/docs/tutorial/stream-json-lines.md @@ -0,0 +1,111 @@ +# JSON Lines को Stream करें { #stream-json-lines } + +आपके पास data की एक sequence हो सकती है जिसे आप "**stream**" में भेजना चाहें, आप इसे **JSON Lines** के साथ कर सकते हैं। + +/// note | टिप्पणी + +FastAPI 0.134.0 में जोड़ा गया। + +/// + +## Stream क्या है? { #what-is-a-stream } + +"**Streaming**" data का मतलब है कि आपका app items की पूरी sequence के तैयार होने का इंतज़ार किए बिना client को data items भेजना शुरू कर देगा। + +तो, यह पहला item भेजेगा, client उसे receive करके process करना शुरू कर देगा, और आप अभी भी अगला item produce कर रहे हो सकते हैं। + +```mermaid +sequenceDiagram + participant App + participant Client + + App->>App: Produce Item 1 + App->>Client: Send Item 1 + App->>App: Produce Item 2 + Client->>Client: Process Item 1 + App->>Client: Send Item 2 + App->>App: Produce Item 3 + Client->>Client: Process Item 2 + App->>Client: Send Item 3 + Client->>Client: Process Item 3 + Note over App: Keeps producing... + Note over Client: Keeps consuming... +``` + +यह एक infinite stream भी हो सकती है, जहाँ आप लगातार data भेजते रहते हैं। + +## JSON Lines { #json-lines } + +इन मामलों में, "**JSON Lines**" भेजना आम है, जो एक ऐसा format है जहाँ आप हर line में एक JSON object भेजते हैं। + +एक response का content type `application/jsonl` होगा (`application/json` के बजाय) और body कुछ इस तरह होगी: + +```json +{"name": "Plumbus", "description": "A multi-purpose household device."} +{"name": "Portal Gun", "description": "A portal opening device."} +{"name": "Meeseeks Box", "description": "A box that summons a Meeseeks."} +``` + +यह JSON array (Python list के equivalent) से बहुत मिलता-जुलता है, लेकिन `[]` में wrap होने और items के बीच `,` होने के बजाय, इसमें **हर line में एक JSON object** होता है, वे एक new line character से अलग होते हैं। + +/// note | टिप्पणी + +महत्वपूर्ण बात यह है कि आपका app हर line को बारी-बारी से produce कर पाएगा, जबकि client पिछली lines को consume करता रहेगा। + +/// + +/// note | तकनीकी विवरण + +क्योंकि हर JSON object एक new line से अलग होगा, उनके content में literal new line characters नहीं हो सकते, लेकिन उनमें escaped new lines (`\n`) हो सकती हैं, जो JSON standard का हिस्सा है। + +लेकिन आमतौर पर आपको इसके बारे में चिंता करने की ज़रूरत नहीं होगी, यह अपने आप हो जाता है, आगे पढ़ते रहें। 🤓 + +/// + +## उपयोग के मामले { #use-cases } + +आप इसका उपयोग **AI LLM** service से, **logs** या **telemetry** से, या अन्य प्रकार के data से data stream करने के लिए कर सकते हैं जिन्हें **JSON** items में structure किया जा सकता है। + +/// tip | सुझाव + +अगर आप binary data stream करना चाहते हैं, उदाहरण के लिए video या audio, तो advanced guide देखें: [Data Stream करें](../advanced/stream-data.md)। + +/// + +## FastAPI के साथ JSON Lines Stream करें { #stream-json-lines-with-fastapi } + +FastAPI के साथ JSON Lines stream करने के लिए, आप अपनी *path operation function* में `return` का उपयोग करने के बजाय, हर item को बारी-बारी से produce करने के लिए `yield` का उपयोग कर सकते हैं। + +{* ../../docs_src/stream_json_lines/tutorial001_py310.py ln[1:24] hl[24] *} + +अगर हर JSON item जिसे आप वापस भेजना चाहते हैं, type `Item` (एक Pydantic model) का है और यह एक async function है, तो आप return type को `AsyncIterable[Item]` के रूप में declare कर सकते हैं: + +{* ../../docs_src/stream_json_lines/tutorial001_py310.py ln[1:24] hl[9:11,22] *} + +अगर आप return type declare करते हैं, तो FastAPI इसका उपयोग data को **validate** करने, OpenAPI में इसे **document** करने, इसे **filter** करने, और Pydantic का उपयोग करके इसे **serialize** करने के लिए करेगा। + +/// tip | सुझाव + +क्योंकि Pydantic इसे **Rust** side में serialize करेगा, आपको return type declare न करने की तुलना में बहुत अधिक **performance** मिलेगी। + +/// + +### Non-async *path operation functions* { #non-async-path-operation-functions } + +आप regular `def` functions (बिना `async` के) भी उपयोग कर सकते हैं, और उसी तरह `yield` का उपयोग कर सकते हैं। + +FastAPI यह सुनिश्चित करेगा कि यह सही तरीके से चले ताकि यह event loop को block न करे। + +क्योंकि इस मामले में function async नहीं है, सही return type `Iterable[Item]` होगा: + +{* ../../docs_src/stream_json_lines/tutorial001_py310.py ln[27:30] hl[28] *} + +### कोई Return Type नहीं { #no-return-type } + +आप return type को omit भी कर सकते हैं। FastAPI फिर data को ऐसी चीज़ में convert करने के लिए [`jsonable_encoder`](./encoder.md) का उपयोग करेगा जिसे JSON में serialize किया जा सके और फिर उसे JSON Lines के रूप में भेजेगा। + +{* ../../docs_src/stream_json_lines/tutorial001_py310.py ln[33:36] hl[34] *} + +## Server-Sent Events (SSE) { #server-sent-events-sse } + +FastAPI में Server-Sent Events (SSE) के लिए भी first-class support है, जो काफी समान हैं लेकिन कुछ extra details के साथ। आप इनके बारे में अगले chapter में जान सकते हैं: [Server-Sent Events (SSE)](server-sent-events.md)। 🤓 diff --git a/docs/hi/docs/tutorial/testing.md b/docs/hi/docs/tutorial/testing.md new file mode 100644 index 000000000..3a05e7917 --- /dev/null +++ b/docs/hi/docs/tutorial/testing.md @@ -0,0 +1,193 @@ +# Testing { #testing } + +[Starlette](https://www.starlette.dev/testclient/) की बदौलत, **FastAPI** applications की testing आसान और आनंददायक है। + +यह [HTTPX](https://www.python-httpx.org) पर आधारित है, जो बदले में Requests के आधार पर design किया गया है, इसलिए यह बहुत परिचित और intuitive है। + +इसके साथ, आप **FastAPI** के साथ सीधे [pytest](https://docs.pytest.org/) का उपयोग कर सकते हैं। + +## `TestClient` का उपयोग करना { #using-testclient } + +/// note | नोट + +`TestClient` का उपयोग करने के लिए, पहले [`httpx`](https://www.python-httpx.org) install करें। + +सुनिश्चित करें कि आप एक [virtual environment](../virtual-environments.md) बनाते हैं, उसे activate करते हैं, और फिर इसे install करते हैं, उदाहरण के लिए: + +```console +$ pip install httpx +``` + +/// + +`TestClient` import करें। + +अपनी **FastAPI** application को इसमें pass करके एक `TestClient` बनाएँ। + +ऐसी functions बनाएँ जिनका नाम `test_` से शुरू होता हो (यह एक standard `pytest` convention है)। + +`TestClient` object का उपयोग उसी तरह करें जैसे आप `httpx` के साथ करते हैं। + +जिन चीज़ों की आपको जाँच करनी है उनके लिए standard Python expressions के साथ सरल `assert` statements लिखें (फिर से, standard `pytest`)। + +{* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *} + +/// tip | टिप + +ध्यान दें कि testing functions सामान्य `def` हैं, `async def` नहीं। + +और client को की जाने वाली calls भी सामान्य calls हैं, `await` का उपयोग नहीं करतीं। + +यह आपको बिना जटिलताओं के सीधे `pytest` का उपयोग करने देता है। + +/// + +/// note | तकनीकी विवरण + +आप `from starlette.testclient import TestClient` का भी उपयोग कर सकते हैं। + +**FastAPI** आपकी सुविधा के लिए, developer के रूप में, उसी `starlette.testclient` को `fastapi.testclient` के रूप में प्रदान करता है। लेकिन यह सीधे Starlette से आता है। + +/// + +/// tip | टिप + +अगर आप अपनी FastAPI application को requests भेजने के अलावा अपने tests में `async` functions call करना चाहते हैं (जैसे asynchronous database functions), तो advanced tutorial में [Async Tests](../advanced/async-tests.md) देखें। + +/// + +## Tests को अलग करना { #separating-tests } + +एक वास्तविक application में, आपके tests शायद किसी अलग file में होंगे। + +और आपकी **FastAPI** application भी कई files/modules आदि से मिलकर बनी हो सकती है। + +### **FastAPI** app file { #fastapi-app-file } + +मान लीजिए आपके पास [Bigger Applications](bigger-applications.md) में बताए गए अनुसार एक file structure है: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +`main.py` file में आपकी **FastAPI** app है: + + +{* ../../docs_src/app_testing/app_a_py310/main.py *} + +### Testing file { #testing-file } + +फिर आपके पास अपने tests के साथ एक file `test_main.py` हो सकती है। यह उसी Python package में हो सकती है (वही directory जिसमें `__init__.py` file है): + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +क्योंकि यह file उसी package में है, आप `main` module (`main.py`) से object `app` को import करने के लिए relative imports का उपयोग कर सकते हैं: + +{* ../../docs_src/app_testing/app_a_py310/test_main.py hl[3] *} + + +...और tests के लिए code पहले जैसा ही रख सकते हैं। + +## Testing: विस्तृत उदाहरण { #testing-extended-example } + +अब इस उदाहरण को आगे बढ़ाते हैं और अलग-अलग हिस्सों की testing कैसे करनी है यह देखने के लिए और विवरण जोड़ते हैं। + +### विस्तारित **FastAPI** app file { #extended-fastapi-app-file } + +आइए पहले जैसी ही file structure के साथ जारी रखें: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +मान लीजिए अब आपकी **FastAPI** app वाली file `main.py` में कुछ अन्य **path operations** हैं। + +इसमें एक `GET` operation है जो error return कर सकता है। + +इसमें एक `POST` operation है जो कई errors return कर सकता है। + +दोनों *path operations* को `X-Token` header required है। + +{* ../../docs_src/app_testing/app_b_an_py310/main.py *} + +### विस्तारित testing file { #extended-testing-file } + +फिर आप विस्तारित tests के साथ `test_main.py` को update कर सकते हैं: + +{* ../../docs_src/app_testing/app_b_an_py310/test_main.py *} + + +जब भी आपको client से request में जानकारी pass करवानी हो और आपको पता न हो कि कैसे, तो आप खोज (Google) सकते हैं कि इसे `httpx` में कैसे करें, या यहाँ तक कि `requests` के साथ कैसे करें, क्योंकि HTTPX का design Requests के design पर आधारित है। + +फिर आप अपने tests में वही करते हैं। + +उदाहरण के लिए: + +* *path* या *query* parameter pass करने के लिए, इसे URL में ही जोड़ें। +* JSON body pass करने के लिए, `json` parameter में एक Python object (जैसे `dict`) pass करें। +* अगर आपको JSON के बजाय *Form Data* भेजना है, तो इसके बजाय `data` parameter का उपयोग करें। +* *headers* pass करने के लिए, `headers` parameter में एक `dict` का उपयोग करें। +* *cookies* के लिए, `cookies` parameter में एक `dict`। + +backend को data कैसे pass करें (`httpx` या `TestClient` का उपयोग करके) इसके बारे में अधिक जानकारी के लिए [HTTPX documentation](https://www.python-httpx.org) देखें। + +/// note | नोट + +ध्यान दें कि `TestClient` ऐसा data receive करता है जिसे JSON में convert किया जा सकता है, Pydantic models नहीं। + +अगर आपके test में एक Pydantic model है और आप testing के दौरान उसका data application को भेजना चाहते हैं, तो आप [JSON Compatible Encoder](encoder.md) में बताए गए `jsonable_encoder` का उपयोग कर सकते हैं। + +/// + +## इसे चलाएँ { #run-it } + +उसके बाद, आपको बस `pytest` install करना है। + +सुनिश्चित करें कि आप एक [virtual environment](../virtual-environments.md) बनाते हैं, उसे activate करते हैं, और फिर इसे install करते हैं, उदाहरण के लिए: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +यह files और tests को automatically detect करेगा, उन्हें execute करेगा, और results आपको वापस report करेगा। + +Tests चलाएँ: + +
+ +```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/hi/docs/virtual-environments.md b/docs/hi/docs/virtual-environments.md new file mode 100644 index 000000000..cacadd0df --- /dev/null +++ b/docs/hi/docs/virtual-environments.md @@ -0,0 +1,864 @@ +# Virtual Environments { #virtual-environments } + +जब आप Python projects पर काम करते हैं, तो संभवतः आपको हर project के लिए install किए जाने वाले packages को अलग रखने के लिए एक **virtual environment** (या कोई समान तरीका) इस्तेमाल करना चाहिए। + +/// note | नोट + +अगर आप पहले से virtual environments के बारे में जानते हैं, उन्हें कैसे बनाना और इस्तेमाल करना है जानते हैं, तो आप इस section को छोड़ना चाह सकते हैं। 🤓 + +/// + +/// tip | सुझाव + +एक **virtual environment**, एक **environment variable** से अलग होता है। + +एक **environment variable** system में एक variable होता है जिसे programs इस्तेमाल कर सकते हैं। + +एक **virtual environment** एक directory होती है जिसमें कुछ files होती हैं। + +/// + +/// note | नोट + +यह पेज आपको **virtual environments** का उपयोग करना और वे कैसे काम करते हैं, सिखाएगा। + +अगर आप अपने लिए **सब कुछ manage करने वाला tool** अपनाने के लिए तैयार हैं (जिसमें Python install करना भी शामिल है), तो [uv](https://github.com/astral-sh/uv) आज़माएँ। + +/// + +## Project बनाएँ { #create-a-project } + +सबसे पहले, अपने project के लिए एक directory बनाएँ। + +मैं सामान्यतः अपनी home/user directory के अंदर `code` नाम की एक directory बनाता हूँ। + +और उसके अंदर हर project के लिए एक directory बनाता हूँ। + +
+ +```console +// home directory में जाएँ +$ cd +// अपने सभी code projects के लिए एक directory बनाएँ +$ mkdir code +// उस code directory में जाएँ +$ cd code +// इस project के लिए एक directory बनाएँ +$ mkdir awesome-project +// उस project directory में जाएँ +$ cd awesome-project +``` + +
+ +## Virtual Environment बनाएँ { #create-a-virtual-environment } + +जब आप किसी Python project पर **पहली बार** काम शुरू करते हैं, तो एक virtual environment **अपने project के अंदर** बनाएँ। + +/// tip | सुझाव + +आपको यह **हर project के लिए केवल एक बार** करना होता है, हर बार काम करते समय नहीं। + +/// + +//// tab | `venv` + +Virtual environment बनाने के लिए, आप Python के साथ आने वाले `venv` module का उपयोग कर सकते हैं। + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | उस command का क्या अर्थ है + +* `python`: `python` नाम के program का उपयोग करें +* `-m`: किसी module को script की तरह call करें, अगला हम उसे बताएँगे कि कौन-सा module +* `venv`: `venv` नाम के module का उपयोग करें जो सामान्यतः Python के साथ install आता है +* `.venv`: नई directory `.venv` में virtual environment बनाएँ + +/// + +//// + +//// tab | `uv` + +अगर आपके पास [`uv`](https://github.com/astral-sh/uv) install है, तो आप इसका उपयोग virtual environment बनाने के लिए कर सकते हैं। + +
+ +```console +$ uv venv +``` + +
+ +/// tip | सुझाव + +Default रूप से, `uv` `.venv` नाम की directory में virtual environment बनाएगा। + +लेकिन आप directory नाम के साथ एक अतिरिक्त argument देकर इसे customize कर सकते हैं। + +/// + +//// + +वह command `.venv` नाम की directory में एक नया virtual environment बनाता है। + +/// details | `.venv` या कोई दूसरा नाम + +आप virtual environment को किसी दूसरी directory में बना सकते हैं, लेकिन इसे `.venv` कहने की एक convention है। + +/// + +## Virtual Environment activate करें { #activate-the-virtual-environment } + +नए virtual environment को activate करें ताकि आप जो भी Python command चलाएँ या जो package install करें, वह इसका उपयोग करे। + +/// tip | सुझाव + +Project पर काम करने के लिए **हर बार** जब आप एक **नया terminal session** शुरू करें, तो यह करें। + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +या अगर आप Windows के लिए Bash का उपयोग करते हैं (जैसे [Git Bash](https://gitforwindows.org/)): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip | सुझाव + +हर बार जब आप उस environment में कोई **नया package** install करें, तो environment को फिर से **activate** करें। + +यह सुनिश्चित करता है कि अगर आप उस package द्वारा install किया गया कोई **terminal (CLI) program** इस्तेमाल करते हैं, तो आप अपने virtual environment वाला ही उपयोग करें, कोई और नहीं जो global रूप से install हो सकता है, शायद आपकी ज़रूरत से अलग version के साथ। + +/// + +## जाँचें कि Virtual Environment Active है { #check-the-virtual-environment-is-active } + +जाँचें कि virtual environment active है (पिछली command ने काम किया)। + +/// tip | सुझाव + +यह **वैकल्पिक** है, लेकिन यह **जाँचने** का एक अच्छा तरीका है कि सब कुछ अपेक्षा के अनुसार काम कर रहा है और आप वही virtual environment इस्तेमाल कर रहे हैं जिसका आपने इरादा किया था। + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +अगर यह `.venv/bin/python` पर `python` binary दिखाता है, आपके project के अंदर (इस मामले में `awesome-project`), तो यह काम कर गया। 🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +अगर यह `.venv\Scripts\python` पर `python` binary दिखाता है, आपके project के अंदर (इस मामले में `awesome-project`), तो यह काम कर गया। 🎉 + +//// + +## `pip` Upgrade करें { #upgrade-pip } + +/// tip | सुझाव + +अगर आप [`uv`](https://github.com/astral-sh/uv) का उपयोग करते हैं, तो आप चीजें install करने के लिए `pip` की बजाय उसी का उपयोग करेंगे, इसलिए आपको `pip` upgrade करने की ज़रूरत नहीं है। 😎 + +/// + +अगर आप packages install करने के लिए `pip` का उपयोग कर रहे हैं (यह Python के साथ default रूप से आता है), तो आपको इसे latest version में **upgrade** करना चाहिए। + +किसी package को install करते समय कई अजीब errors केवल पहले `pip` upgrade करने से हल हो जाते हैं। + +/// tip | सुझाव + +आप सामान्यतः यह **एक बार** करेंगे, virtual environment बनाने के ठीक बाद। + +/// + +सुनिश्चित करें कि virtual environment active है (ऊपर वाली command से) और फिर चलाएँ: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +/// tip | सुझाव + +कभी-कभी, pip upgrade करने की कोशिश करते समय आपको **`No module named pip`** error मिल सकता है। + +अगर ऐसा होता है, तो नीचे दी गई command का उपयोग करके pip install और upgrade करें: + +
+ +```console +$ python -m ensurepip --upgrade + +---> 100% +``` + +
+ +यह command pip को install करेगी अगर वह पहले से install नहीं है और यह भी सुनिश्चित करेगी कि install किया गया pip का version कम से कम `ensurepip` में उपलब्ध version जितना नया हो। + +/// + +## `.gitignore` जोड़ें { #add-gitignore } + +अगर आप **Git** का उपयोग कर रहे हैं (आपको करना चाहिए), तो अपनी `.venv` की हर चीज़ को Git से exclude करने के लिए एक `.gitignore` file जोड़ें। + +/// tip | सुझाव + +अगर आपने virtual environment बनाने के लिए [`uv`](https://github.com/astral-sh/uv) का उपयोग किया है, तो यह आपके लिए पहले ही कर चुका है, आप यह step छोड़ सकते हैं। 😎 + +/// + +/// tip | सुझाव + +यह **एक बार** करें, virtual environment बनाने के ठीक बाद। + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | उस command का क्या अर्थ है + +* `echo "*"`: terminal में text `*` को "print" करेगा (अगला हिस्सा इसे थोड़ा बदल देता है) +* `>`: `>` के बाईं ओर वाली command द्वारा terminal में print की गई कोई भी चीज़ print नहीं होनी चाहिए, बल्कि `>` के दाईं ओर वाली file में लिखी जानी चाहिए +* `.gitignore`: उस file का नाम जहाँ text लिखा जाना चाहिए + +और Git के लिए `*` का मतलब "सब कुछ" होता है। इसलिए, यह `.venv` directory में सब कुछ ignore करेगा। + +वह command `.gitignore` file बनाएगी, इस content के साथ: + +```gitignore +* +``` + +/// + +## Packages install करें { #install-packages } + +Environment activate करने के बाद, आप उसमें packages install कर सकते हैं। + +/// tip | सुझाव + +जब आप अपने project के लिए required packages install या upgrade कर रहे हों, तो यह **एक बार** करें। + +अगर आपको किसी version को upgrade करना हो या कोई नया package जोड़ना हो, तो आप **यह फिर से करेंगे**। + +/// + +### सीधे Packages install करें { #install-packages-directly } + +अगर आप जल्दी में हैं और अपने project की package requirements declare करने के लिए कोई file इस्तेमाल नहीं करना चाहते, तो आप उन्हें सीधे install कर सकते हैं। + +/// tip | सुझाव + +आपके program को जिन packages और versions की ज़रूरत है, उन्हें एक file में रखना (बहुत) अच्छा विचार है (उदाहरण के लिए `requirements.txt` या `pyproject.toml`)। + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +अगर आपके पास [`uv`](https://github.com/astral-sh/uv) है: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### `requirements.txt` से install करें { #install-from-requirements-txt } + +अगर आपके पास `requirements.txt` है, तो अब आप इसके packages install करने के लिए इसका उपयोग कर सकते हैं। + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +अगर आपके पास [`uv`](https://github.com/astral-sh/uv) है: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +कुछ packages वाला `requirements.txt` ऐसा दिख सकता है: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## अपना Program चलाएँ { #run-your-program } + +Virtual environment activate करने के बाद, आप अपना program चला सकते हैं, और यह आपके virtual environment के अंदर मौजूद Python का उपयोग करेगा, उन packages के साथ जिन्हें आपने वहाँ install किया है। + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## अपना Editor Configure करें { #configure-your-editor } + +आप शायद एक editor का उपयोग करेंगे, सुनिश्चित करें कि आप इसे उसी virtual environment का उपयोग करने के लिए configure करें जिसे आपने बनाया है (यह शायद इसे autodetect कर लेगा), ताकि आपको autocompletion और inline errors मिल सकें। + +उदाहरण के लिए: + +* [VS Code](https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment) +* [PyCharm](https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html) + +/// tip | सुझाव + +आपको सामान्यतः यह केवल **एक बार** करना होता है, जब आप virtual environment बनाते हैं। + +/// + +## Virtual Environment deactivate करें { #deactivate-the-virtual-environment } + +जब आप अपने project पर काम कर लें, तो आप virtual environment को **deactivate** कर सकते हैं। + +
+ +```console +$ deactivate +``` + +
+ +इस तरह, जब आप `python` चलाएँगे, तो यह वहाँ install packages वाले उस virtual environment से इसे चलाने की कोशिश नहीं करेगा। + +## काम करने के लिए तैयार { #ready-to-work } + +अब आप अपने project पर काम शुरू करने के लिए तैयार हैं। + + + +/// tip | सुझाव + +क्या आप समझना चाहते हैं कि ऊपर की सारी चीज़ें क्या हैं? + +आगे पढ़ते रहें। 👇🤓 + +/// + +## Virtual Environments क्यों { #why-virtual-environments } + +FastAPI के साथ काम करने के लिए आपको [Python](https://www.python.org/) install करना होगा। + +उसके बाद, आपको FastAPI और कोई भी अन्य **packages** जिन्हें आप इस्तेमाल करना चाहते हैं, **install** करने होंगे। + +Packages install करने के लिए आप सामान्यतः Python के साथ आने वाली `pip` command (या समान alternatives) का उपयोग करेंगे। + +फिर भी, अगर आप सीधे `pip` का उपयोग करते हैं, तो packages आपके **global Python environment** (Python की global installation) में install हो जाएँगे। + +### समस्या { #the-problem } + +तो, global Python environment में packages install करने में समस्या क्या है? + +किसी समय, आप शायद कई अलग-अलग programs लिखेंगे जो **अलग-अलग packages** पर निर्भर करते हैं। और जिन projects पर आप काम करेंगे उनमें से कुछ उसी package के **अलग-अलग versions** पर निर्भर होंगे। 😱 + +उदाहरण के लिए, आप `philosophers-stone` नाम का एक project बना सकते हैं, यह program **`harry`, version `1`** नाम के किसी दूसरे package पर निर्भर करता है। इसलिए, आपको `harry` install करना होगा। + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +फिर, कुछ समय बाद, आप `prisoner-of-azkaban` नाम का दूसरा project बनाते हैं, और यह project भी `harry` पर निर्भर करता है, लेकिन इस project को **`harry` version `3`** चाहिए। + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +लेकिन अब समस्या यह है कि अगर आप packages को local **virtual environment** में install करने के बजाय globally (global environment में) install करते हैं, तो आपको चुनना होगा कि `harry` का कौन-सा version install करना है। + +अगर आप `philosophers-stone` चलाना चाहते हैं, तो आपको पहले `harry` version `1` install करना होगा, उदाहरण के लिए: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +और फिर आपके global Python environment में `harry` version `1` install हो जाएगा। + +```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 +``` + +लेकिन फिर अगर आप `prisoner-of-azkaban` चलाना चाहते हैं, तो आपको `harry` version `1` uninstall करके `harry` version `3` install करना होगा (या सिर्फ version `3` install करने से version `1` automatically uninstall हो जाएगा)। + +
+ +```console +$ pip install "harry==3" +``` + +
+ +और फिर आपके global Python environment में `harry` version `3` install हो जाएगा। + +और अगर आप `philosophers-stone` फिर से चलाने की कोशिश करते हैं, तो संभावना है कि यह **काम न करे** क्योंकि इसे `harry` version `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 | सुझाव + +Python packages में **नए versions** में **breaking changes से बचने** की पूरी कोशिश करना बहुत आम है, लेकिन सुरक्षित रहना बेहतर है, और नए versions को जानबूझकर तथा तब install करना बेहतर है जब आप tests चलाकर जाँच सकें कि सब कुछ सही तरीके से काम कर रहा है। + +/// + +अब, यही चीज़ उन **कई** अन्य **packages** के साथ कल्पना करें जिन पर आपके सभी **projects निर्भर करते हैं**। इसे manage करना बहुत कठिन है। और संभवतः आप कुछ projects को packages के कुछ **incompatible versions** के साथ चला देंगे, और यह नहीं जान पाएँगे कि कुछ काम क्यों नहीं कर रहा। + +साथ ही, आपके operating system (जैसे Linux, Windows, macOS) के आधार पर, उसमें Python पहले से install आया हो सकता है। और उस मामले में संभवतः कुछ packages कुछ specific versions के साथ pre-installed होंगे जो **आपके system के लिए required** हैं। अगर आप global Python environment में packages install करते हैं, तो आप अपने operating system के साथ आए कुछ programs को **break** कर सकते हैं। + +## Packages कहाँ install होते हैं { #where-are-packages-installed } + +जब आप Python install करते हैं, तो यह आपके computer पर कुछ files वाली कुछ directories बनाता है। + +इनमें से कुछ directories वे होती हैं जो आपके द्वारा install किए गए सभी packages को रखने की जिम्मेदार होती हैं। + +जब आप चलाते हैं: + +
+ +```console +// इसे अभी न चलाएँ, यह केवल एक उदाहरण है 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +तो यह FastAPI code वाली एक compressed file download करेगा, सामान्यतः [PyPI](https://pypi.org/project/fastapi/) से। + +यह उन अन्य packages की files भी **download** करेगा जिन पर FastAPI निर्भर करता है। + +फिर यह उन सभी files को **extract** करेगा और उन्हें आपके computer की एक directory में रखेगा। + +Default रूप से, यह उन downloaded और extracted files को उस directory में रखेगा जो आपकी Python installation के साथ आती है, वही **global environment** है। + +## Virtual Environments क्या हैं { #what-are-virtual-environments } + +सभी packages को global environment में रखने की समस्याओं का समाधान है कि आप जिस भी project पर काम करते हैं उसके लिए **एक virtual environment** उपयोग करें। + +एक virtual environment एक **directory** है, global वाली के बहुत समान, जहाँ आप किसी project के लिए packages install कर सकते हैं। + +इस तरह, हर project का अपना virtual environment (`.venv` directory) होगा, अपने packages के साथ। + +```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 +``` + +## Virtual Environment activate करने का क्या मतलब है { #what-does-activating-a-virtual-environment-mean } + +जब आप किसी virtual environment को activate करते हैं, उदाहरण के लिए: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +या अगर आप Windows के लिए Bash का उपयोग करते हैं (जैसे [Git Bash](https://gitforwindows.org/)): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +वह command कुछ [environment variables](environment-variables.md) बनाएगी या modify करेगी, जो अगली commands के लिए उपलब्ध होंगे। + +उन variables में से एक `PATH` variable है। + +/// tip | सुझाव + +आप [Environment Variables](environment-variables.md#path-environment-variable) section में `PATH` environment variable के बारे में और जान सकते हैं। + +/// + +Virtual environment activate करने से उसका path `.venv/bin` (Linux और macOS पर) या `.venv\Scripts` (Windows पर) `PATH` environment variable में जुड़ जाता है। + +मान लीजिए कि environment activate करने से पहले, `PATH` variable ऐसा दिखता था: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +इसका मतलब है कि system programs को इनमें खोजता: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +इसका मतलब है कि system programs को इसमें खोजता: + +* `C:\Windows\System32` + +//// + +Virtual environment activate करने के बाद, `PATH` variable कुछ ऐसा दिखेगा: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +इसका मतलब है कि system अब सबसे पहले programs को यहाँ खोजना शुरू करेगा: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +बाकी directories में देखने से पहले। + +तो, जब आप terminal में `python` type करते हैं, तो system Python program को यहाँ पाएगा + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +और उसी का उपयोग करेगा। + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +इसका मतलब है कि system अब सबसे पहले programs को यहाँ खोजना शुरू करेगा: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +बाकी directories में देखने से पहले। + +तो, जब आप terminal में `python` type करते हैं, तो system Python program को यहाँ पाएगा + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +और उसी का उपयोग करेगा। + +//// + +एक महत्वपूर्ण detail यह है कि यह virtual environment path को `PATH` variable की **शुरुआत** में रखेगा। System इसे किसी भी अन्य उपलब्ध Python से **पहले** पाएगा। इस तरह, जब आप `python` चलाते हैं, तो यह किसी अन्य `python` (उदाहरण के लिए, global environment वाला `python`) के बजाय **virtual environment से** Python का उपयोग करेगा। + +Virtual environment activate करने से कुछ और चीजें भी बदलती हैं, लेकिन यह उसके द्वारा की जाने वाली सबसे महत्वपूर्ण चीज़ों में से एक है। + +## Virtual Environment की जाँच करना { #checking-a-virtual-environment } + +जब आप जाँचते हैं कि virtual environment active है या नहीं, उदाहरण के लिए: + +//// 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` program उपयोग किया जाएगा, वह **virtual environment में** मौजूद है। + +आप Linux और macOS में `which` और Windows PowerShell में `Get-Command` का उपयोग करते हैं। + +वह command जिस तरह काम करती है, वह यह है कि यह `PATH` environment variable में जाकर **हर path को क्रम से** check करेगी, `python` नाम के program को खोजते हुए। एक बार जब यह उसे ढूँढ लेती है, तो यह आपको उस program का **path दिखाएगी**। + +सबसे महत्वपूर्ण हिस्सा यह है कि जब आप `python` call करते हैं, तो वही exact "`python`" execute होगा। + +तो, आप confirm कर सकते हैं कि आप सही virtual environment में हैं या नहीं। + +/// tip | सुझाव + +एक virtual environment activate करना, एक Python पाना, और फिर **दूसरे project में चले जाना** आसान है। + +और दूसरा project **काम नहीं करेगा** क्योंकि आप **गलत Python** का उपयोग कर रहे हैं, जो किसी दूसरे project के virtual environment से है। + +यह check कर पाना उपयोगी है कि कौन-सा `python` उपयोग हो रहा है। 🤓 + +/// + +## Virtual Environment deactivate क्यों करें { #why-deactivate-a-virtual-environment } + +उदाहरण के लिए, आप `philosophers-stone` project पर काम कर रहे हो सकते हैं, **उस virtual environment को activate** करके, packages install करके और उस environment के साथ काम करके। + +और फिर आप **किसी दूसरे project** `prisoner-of-azkaban` पर काम करना चाहते हैं। + +आप उस project में जाते हैं: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +अगर आप `philosophers-stone` के लिए virtual environment को deactivate नहीं करते, तो जब आप terminal में `python` चलाएँगे, यह `philosophers-stone` से Python का उपयोग करने की कोशिश करेगा। + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// sirius import करने में error, यह install नहीं है 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +लेकिन अगर आप virtual environment deactivate करके `prisoner-of-azkaban` के लिए नया वाला activate करते हैं, तो जब आप `python` चलाएँगे, यह `prisoner-of-azkaban` में मौजूद virtual environment से Python का उपयोग करेगा। + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// deactivate करने के लिए आपको पुरानी directory में होने की ज़रूरत नहीं है, आप जहाँ भी हों वहाँ से कर सकते हैं, दूसरे project में जाने के बाद भी 😎 +$ deactivate + +// prisoner-of-azkaban/.venv में virtual environment activate करें 🚀 +$ source .venv/bin/activate + +// अब जब आप python चलाएँगे, तो यह इस virtual environment में install package sirius को पाएगा ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
+ +## Alternatives { #alternatives } + +यह आपको शुरू करने और यह सिखाने के लिए एक सरल guide है कि सब कुछ **अंदर से** कैसे काम करता है। + +Virtual environments, package dependencies (requirements), projects को manage करने के कई **alternatives** हैं। + +जब आप तैयार हों और **पूरे project को manage** करने के लिए कोई tool उपयोग करना चाहें, package dependencies, virtual environments आदि सहित, तो मैं सुझाव दूँगा कि आप [uv](https://github.com/astral-sh/uv) आज़माएँ। + +`uv` बहुत सारी चीज़ें कर सकता है, यह कर सकता है: + +* आपके लिए **Python install** करना, अलग-अलग versions सहित +* आपके projects के लिए **virtual environment** manage करना +* **Packages** install करना +* आपके project के लिए package **dependencies और versions** manage करना +* सुनिश्चित करना कि आपके पास install करने के लिए packages और versions का **exact** set हो, उनकी dependencies सहित, ताकि आप सुनिश्चित हो सकें कि आप अपने project को production में ठीक उसी तरह चला सकते हैं जैसे development के दौरान अपने computer पर चलाते हैं, इसे **locking** कहा जाता है +* और कई अन्य चीज़ें + +## निष्कर्ष { #conclusion } + +अगर आपने यह सब पढ़ा और समझा है, तो अब **आप virtual environments के बारे में** वहाँ मौजूद कई developers से कहीं ज़्यादा जानते हैं। 🤓 + +इन details को जानना भविष्य में उस समय बहुत संभवतः उपयोगी होगा जब आप किसी ऐसी चीज़ को debug कर रहे होंगे जो complex लगती है, लेकिन आपको पता होगा कि **यह सब अंदर से कैसे काम करता है**। 😎 diff --git a/docs/hi/llm-prompt.md b/docs/hi/llm-prompt.md new file mode 100644 index 000000000..b626ea586 --- /dev/null +++ b/docs/hi/llm-prompt.md @@ -0,0 +1,58 @@ +### Target language + +Translate to Hindi (हिन्दी). + +Language code: hi. + +For the following terms, use these specific choices: + +* path (URL path): path (do not transliterate as "पाथ") +* path parameter / path operation: keep in English +* query / query parameter: keep in English (do not transliterate as "क्वेरी") +* parameter: parameter (do not transliterate as "पैरामीटर") +* header / headers (HTTP): keep in English (do not translate as "हेडर" / "शीर्षक") +* cookie / cookies: keep in English (do not transliterate as "कुकी") +* form / form data: keep in English (do not transliterate as "फ़ॉर्म" / "फ़ॉर्म डेटा") +* field / fields: keep in English (do not transliterate as "फ़ील्ड्स") +* body / request body / response body: keep in English (do not transliterate as "बॉडी" / "रिक्वेस्ट बॉडी") +* request / response: keep in English (do not translate as "अनुरोध" / "प्रतिक्रिया") +* required: required (do not translate as "आवश्यक") +* route / router / endpoint: keep in English +* framework: framework +* middleware: middleware (do not transliterate as "मिडलवेयर") +* lifespan: lifespan (do not translate as "जीवनकाल") +* context manager: keep in English +* CORS: keep in English +* function: function (do not transliterate as "फ़ंक्शन") +* variable: variable (do not transliterate as "वेरिएबल") +* model / Pydantic model: keep in English (do not transliterate as "मॉडल") +* value: value (do not translate as "मान") +* spec / specification: keep in English (do not translate as "स्पेक" / "विनिर्देश") +* Enum / enumeration: keep in English +* data: data (do not transliterate as "डेटा") +* parsing: parsing (do not transliterate as "पार्सिंग") +* conversion: conversion (do not translate as "रूपांतरण") +* virtual environment: virtual environment (do not transliterate as "वर्चुअल एनवायरनमेंट") +* environment variable: environment variable (do not transliterate as "एनवायरनमेंट वेरिएबल") +* directory: directory (do not transliterate as "डायरेक्टरी") +* package: package (do not transliterate as "पैकेज") +* file / files: keep in English (do not transliterate as "फ़ाइल") +* install / installation: keep in English (do not transliterate as "इंस्टॉल") +* setup: setup (do not transliterate as "सेटअप") +* section: section (do not transliterate as "सेक्शन") +* editor / editor support: keep in English (do not transliterate as "एडिटर सपोर्ट") +* application discovery: keep in English +* event / events: event (do not transliterate as "इवेंट्स") +* startup / shutdown: keep in English (do not transliterate as "स्टार्टअप") +* worker / worker process: keep in English (do not translate as "वर्कर" / "श्रमिक") +* activate / deactivate: keep in English (do not translate as "सक्रिय करें" / "निष्क्रिय करें") +* development: development (do not transliterate as "डेवलपमेंट") +* production: production (do not transliterate as "प्रोडक्शन") +* feature: feature (do not transliterate as "फीचर") +* tool: tool (do not transliterate as "टूल") +* project: project (do not transliterate as "प्रोजेक्ट") +* developer / team: keep in English +* default: default (do not transliterate as "डिफ़ॉल्ट") +* standard: standard (do not translate as "मानक") +* asynchronous: asynchronous (do not transliterate as "असिंक्रोनस") +* Recap (section heading): keep in English (do not translate as "पुनरावलोकन") diff --git a/docs/de/mkdocs.yml b/docs/hi/mkdocs.yml similarity index 100% rename from docs/de/mkdocs.yml rename to docs/hi/mkdocs.yml diff --git a/docs/ja/docs/_llm-test.md b/docs/ja/docs/_llm-test.md index 4c84a7c04..91eeffd0c 100644 --- a/docs/ja/docs/_llm-test.md +++ b/docs/ja/docs/_llm-test.md @@ -1,5 +1,6 @@ # LLM テストファイル { #llm-test-file } + このドキュメントは、ドキュメントを翻訳する LLM が、`scripts/translate.py` の `general_prompt` と、`docs/{language code}/llm-prompt.md` の言語固有プロンプトを理解しているかをテストします。言語固有プロンプトは `general_prompt` の末尾に追加されます。 ここに追加したテストは、すべての言語固有プロンプトの設計者が参照します。 @@ -124,10 +125,6 @@ works(foo="bar") # これは動作します 🎉 //// tab | テスト -/// info | 情報 -いくつかのテキスト -/// - /// note | 備考 いくつかのテキスト /// @@ -136,10 +133,6 @@ works(foo="bar") # これは動作します 🎉 いくつかのテキスト /// -/// check | 確認 -いくつかのテキスト -/// - /// tip | 豆知識 いくつかのテキスト /// diff --git a/docs/ja/docs/advanced/additional-responses.md b/docs/ja/docs/advanced/additional-responses.md index 1d7c2f80e..ad0b1d4c9 100644 --- a/docs/ja/docs/advanced/additional-responses.md +++ b/docs/ja/docs/advanced/additional-responses.md @@ -34,7 +34,7 @@ FastAPI はそのモデルから JSON Schema を生成し、OpenAPI の適切な /// -/// info | 情報 +/// note | 備考 `model` キーは OpenAPI の一部ではありません。 @@ -183,7 +183,7 @@ FastAPI はそこから Pydantic モデルを取得して JSON Schema を生成 /// -/// info | 情報 +/// note | 備考 `responses` パラメータで明示的に別のメディアタイプを指定しない限り、FastAPI はレスポンスがメインのレスポンスクラスと同じメディアタイプ(デフォルトは `application/json`)であるとみなします。 diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md index ad9bd57dc..0c19abd49 100644 --- a/docs/ja/docs/advanced/additional-status-codes.md +++ b/docs/ja/docs/advanced/additional-status-codes.md @@ -16,7 +16,7 @@ {* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} -/// warning +/// warning | 注意 上の例のように `Response` を直接返すと、それはそのまま返されます。 diff --git a/docs/ja/docs/advanced/advanced-dependencies.md b/docs/ja/docs/advanced/advanced-dependencies.md index 5181e39d8..e06ca4721 100644 --- a/docs/ja/docs/advanced/advanced-dependencies.md +++ b/docs/ja/docs/advanced/advanced-dependencies.md @@ -10,9 +10,9 @@ ただし、その固定の内容はパラメータ化できるようにしたいです。 -## "callable" なインスタンス { #a-callable-instance } +## 「callable」なインスタンス { #a-callable-instance } -Python には、クラスのインスタンスを "callable" にする方法があります。 +Python には、クラスのインスタンスを「callable」にする方法があります。 クラス自体(これはすでに callable です)ではなく、そのクラスのインスタンスです。 @@ -98,7 +98,7 @@ FastAPI 0.118.0 より前では、`yield` を使う依存関係を使用する この挙動は 0.118.0 で元に戻され、`yield` の後の終了コードはレスポンス送信後に実行されるようになりました。 -/// info | 情報 +/// note | 備考 以下で見るように、これはバージョン 0.106.0 より前の挙動ととても似ていますが、いくつかのコーナーケースに対する改良とバグ修正が含まれています。 @@ -146,7 +146,7 @@ FastAPI 0.110.0 より前では、`yield` を持つ依存関係を使い、そ FastAPI 0.106.0 より前では、`yield` の後で例外を送出することはできませんでした。`yield` を持つ依存関係の終了コードはレスポンス送信「後」に実行されるため、[例外ハンドラ](../tutorial/handling-errors.md#install-custom-exception-handlers)はすでに実行済みでした。 -これは主に、依存関係が "yield" した同じオブジェクトをバックグラウンドタスク内で利用できるようにするための設計でした。終了コードはバックグラウンドタスク完了後に実行されるからです。 +これは主に、依存関係が「yield」した同じオブジェクトをバックグラウンドタスク内で利用できるようにするための設計でした。終了コードはバックグラウンドタスク完了後に実行されるからです。 これは、レスポンスがネットワーク上を移動するのを待っている間にリソースを保持しないようにする意図で、FastAPI 0.106.0 で変更されました。 diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md index e66b1f494..34178a50e 100644 --- a/docs/ja/docs/advanced/custom-response.md +++ b/docs/ja/docs/advanced/custom-response.md @@ -41,7 +41,7 @@ FastAPI はデフォルトでJSONレスポンスを返します。 {* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *} -/// info | 情報 +/// note | 備考 パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するためにも使用されます。 @@ -65,7 +65,7 @@ FastAPI はデフォルトでJSONレスポンスを返します。 /// -/// info | 情報 +/// note | 備考 もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返した `Response` オブジェクトに由来します。 diff --git a/docs/ja/docs/advanced/dataclasses.md b/docs/ja/docs/advanced/dataclasses.md index e3ad7afb6..2cfe8e905 100644 --- a/docs/ja/docs/advanced/dataclasses.md +++ b/docs/ja/docs/advanced/dataclasses.md @@ -18,7 +18,7 @@ FastAPI は **Pydantic** の上に構築されており、これまでにリク これは Pydantic モデルの場合と同じように動作します。内部的にも同様に Pydantic を使って実現されています。 -/// info | 情報 +/// note | 備考 dataclasses は、Pydantic モデルができることをすべては行えない点に留意してください。 @@ -74,7 +74,7 @@ dataclass は自動的に Pydantic の dataclass に変換されます。 いつもどおり、FastAPI では必要に応じて `def` と `async def` を組み合わせられます。 - どちらをいつ使うかの復習が必要な場合は、[`async` と `await`](../async.md#in-a-hurry) に関するドキュメントの _"In a hurry?"_ セクションを参照してください。 + どちらをいつ使うかの復習が必要な場合は、[`async` と `await`](../async.md#in-a-hurry) に関するドキュメントの _「急いでいますか?」_ セクションを参照してください。 9. この *path operation 関数* は(可能ではありますが)dataclass 自体は返さず、内部データを持つ辞書のリストを返しています。 @@ -82,7 +82,7 @@ dataclass は自動的に Pydantic の dataclass に変換されます。 `dataclasses` は他の型注釈と多様な組み合わせが可能で、複雑なデータ構造を構成できます。 -上記のコード内コメントのヒントを参照して、より具体的な詳細を確認してください。 +上記のコード内の注釈のヒントを参照して、より具体的な詳細を確認してください。 ## さらに学ぶ { #learn-more } diff --git a/docs/ja/docs/advanced/events.md b/docs/ja/docs/advanced/events.md index e2cbe2eb0..12064f948 100644 --- a/docs/ja/docs/advanced/events.md +++ b/docs/ja/docs/advanced/events.md @@ -120,7 +120,7 @@ async with lifespan(app): ここでは、`shutdown` のイベントハンドラ関数が、テキスト行 `"Application shutdown"` をファイル `log.txt` に書き込みます。 -/// info | 情報 +/// note | 備考 `open()` 関数の `mode="a"` は「追加」(append)を意味します。つまり、そのファイルに既にある内容を上書きせず、行が後ろに追記されます。 @@ -140,7 +140,7 @@ async with lifespan(app): ### `startup` と `shutdown` をまとめて { #startup-and-shutdown-together } -起動時とシャットダウン時のロジックは関連していることが多いです。何かを開始してから終了したい、リソースを獲得してから解放したい、などです. +起動時とシャットダウン時のロジックは関連していることが多いです。何かを開始してから終了したい、リソースを獲得してから解放したい、などです。 共有するロジックや変数のない別々の関数でそれを行うのは難しく、グローバル変数などに値を保存する必要が出てきます。 @@ -152,7 +152,7 @@ async with lifespan(app): 内部的には、ASGI の技術仕様において、これは [Lifespan プロトコル](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) の一部であり、`startup` と `shutdown` というイベントが定義されています。 -/// info | 情報 +/// note | 備考 Starlette の `lifespan` ハンドラについては、[Starlette の Lifespan ドキュメント](https://www.starlette.dev/lifespan/)で詳しく読むことができます。 diff --git a/docs/ja/docs/advanced/generate-clients.md b/docs/ja/docs/advanced/generate-clients.md index b3472880e..196ec5280 100644 --- a/docs/ja/docs/advanced/generate-clients.md +++ b/docs/ja/docs/advanced/generate-clients.md @@ -20,22 +20,6 @@ FastAPI は自動的に **OpenAPI 3.1** の仕様を生成します。したが /// -## FastAPI スポンサーによる SDK ジェネレータ { #sdk-generators-from-fastapi-sponsors } - -このセクションでは、FastAPI をスポンサーしている企業による、**ベンチャー支援**および**企業支援**のソリューションを紹介します。これらの製品は、高品質な生成 SDK に加えて、**追加機能**や**統合**を提供します。 - -✨ [**FastAPI をスポンサーする**](../help-fastapi.md#sponsor-the-author) ✨ ことで、これらの企業はフレームワークとその**エコシステム**の健全性と**持続可能性**を支援しています。 - -この支援は、FastAPI の**コミュニティ**(皆さん)への強いコミットメントの表明でもあり、**優れたサービス**の提供だけでなく、堅牢で発展するフレームワーク FastAPI を支える姿勢を示しています。🙇 - -例えば、次のようなものがあります: - -* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship) -* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral) -* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi) - -これらのソリューションの中にはオープンソースや無料枠を提供するものもあり、金銭的コミットメントなしで試すことができます。他の商用 SDK ジェネレータも存在し、オンラインで見つけられます。🤓 - ## TypeScript SDK を作成する { #create-a-typescript-sdk } まずは簡単な FastAPI アプリから始めます: diff --git a/docs/ja/docs/advanced/json-base64-bytes.md b/docs/ja/docs/advanced/json-base64-bytes.md index c3c361a96..214ce14c6 100644 --- a/docs/ja/docs/advanced/json-base64-bytes.md +++ b/docs/ja/docs/advanced/json-base64-bytes.md @@ -4,7 +4,7 @@ ## Base64 とファイル { #base64-vs-files } -バイナリデータのアップロードにはまず、JSON にエンコードする代わりに [Request Files](../tutorial/request-files.md) を、バイナリデータの送信には [カスタムレスポンス - FileResponse](./custom-response.md#fileresponse--fileresponse-) を使えるか検討してください。 +バイナリデータのアップロードにはまず、JSON にエンコードする代わりに [リクエストファイル](../tutorial/request-files.md) を、バイナリデータの送信には [カスタムレスポンス - FileResponse](./custom-response.md#fileresponse) を使えるか検討してください。 JSON は UTF-8 でエンコードされた文字列のみを含められるため、生のバイト列は含められません。 diff --git a/docs/ja/docs/advanced/openapi-callbacks.md b/docs/ja/docs/advanced/openapi-callbacks.md index 31d17e270..e3ddeab98 100644 --- a/docs/ja/docs/advanced/openapi-callbacks.md +++ b/docs/ja/docs/advanced/openapi-callbacks.md @@ -23,7 +23,7 @@ * API 利用者(外部開発者)に通知を送り返します。 * これは(あなたの API から)外部開発者が提供する *外部 API* に POST リクエストを送ることで行われます(これが「コールバック」です)。 -## 通常の FastAPI アプリ { #the-normal-fastapi-app } +## 通常の **FastAPI** アプリ { #the-normal-fastapi-app } まず、コールバックを追加する前の通常の API アプリがどうなるか見てみましょう。 @@ -76,7 +76,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) しかし、あなたはすでに **FastAPI** で API の自動ドキュメントを簡単に作る方法を知っています。 -その知識を使って、*外部 API* がどうあるべきかをドキュメント化します……つまり、外部 API が実装すべき *path operation(s)*(あなたの API が呼び出すもの)を作成します。 +その知識を使って、*外部 API* がどうあるべきかをドキュメント化します... つまり、外部 API が実装すべき *path operation(s)*(あなたの API が呼び出すもの)を作成します。 /// tip | 豆知識 @@ -86,13 +86,13 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) /// -### コールバック用 APIRouter を作成 { #create-a-callback-apirouter } +### コールバック用 `APIRouter` を作成 { #create-a-callback-apirouter } まず、1 つ以上のコールバックを含む新しい `APIRouter` を作成します。 {* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[1,23] *} -### コールバックの path operation を作成 { #create-the-callback-path-operation } +### コールバックの *path operation* を作成 { #create-the-callback-path-operation } 上で作成したのと同じ `APIRouter` を使って、コールバックの *path operation* を作成します。 @@ -167,13 +167,13 @@ JSON ボディは次のような内容です: これで、上で作成したコールバック用ルーター内に、必要なコールバックの *path operation(s)*(*外部開発者* が *外部 API* に実装すべきもの)が用意できました。 -次に、*あなたの API の path operation デコレータ*の `callbacks` パラメータに、そのコールバック用ルーターの属性 `.routes`(実体はルート/*path operations* の `list`)を渡します: +次に、*あなたの API の path operation デコレータ*の `callbacks` パラメータに、そのコールバック用ルーターの属性 `.routes` を渡します: {* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *} /// tip | 豆知識 -`callback=` に渡すのはルーター本体(`invoices_callback_router`)ではなく、属性 `.routes`(`invoices_callback_router.routes`)である点に注意してください。 +`callbacks=` に渡すのはルーター本体(`invoices_callback_router`)ではなく、属性 `.routes`(`invoices_callback_router.routes`)である点に注意してください。FastAPI はそれらのルートを使ってコールバックの OpenAPI ドキュメントを生成します。 /// diff --git a/docs/ja/docs/advanced/openapi-webhooks.md b/docs/ja/docs/advanced/openapi-webhooks.md index 7f7a72680..f559de13b 100644 --- a/docs/ja/docs/advanced/openapi-webhooks.md +++ b/docs/ja/docs/advanced/openapi-webhooks.md @@ -22,7 +22,7 @@ Webhook の URL を登録する方法や実際にリクエストを送るコー これにより、ユーザーがあなたの **Webhook** リクエストを受け取るための**API を実装**するのが大幅に簡単になります。場合によっては、ユーザーが自分たちの API コードを自動生成できるかもしれません。 -/// info | 情報 +/// note | 備考 Webhook は OpenAPI 3.1.0 以上で利用可能で、FastAPI `0.99.0` 以上が対応しています。 @@ -36,7 +36,7 @@ Webhook は OpenAPI 3.1.0 以上で利用可能で、FastAPI `0.99.0` 以上が 定義した webhook は **OpenAPI** スキーマおよび自動生成される **ドキュメント UI** に反映されます。 -/// info | 情報 +/// note | 備考 `app.webhooks` オブジェクトは実際には単なる `APIRouter` で、複数ファイルでアプリを構成する際に使うものと同じ型です。 diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md index 65b56dba4..bc08092f8 100644 --- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md @@ -16,17 +16,11 @@ OpenAPIの「エキスパート」でなければ、これはおそらく必要 ### *path operation関数* の名前をoperationIdとして使用する { #using-the-path-operation-function-name-as-the-operationid } -APIの関数名を `operationId` として利用したい場合、すべてのAPI関数をイテレーションし、各 *path operation* の `operation_id` を `APIRoute.name` で上書きすれば可能です。 +API の関数名を `operationId` として使いたい場合は、`FastAPI` にカスタムの `generate_unique_id_function` を渡せます。 -すべての *path operation* を追加した後に行うべきです。 +この関数は各 `APIRoute` を受け取り、その *path operation* で使う `operationId` を返します。 -{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *} - -/// tip | 豆知識 - -`app.openapi()` を手動で呼び出す場合、その前に `operationId` を更新するべきです。 - -/// +{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2,5:6,9] *} /// warning | 注意 diff --git a/docs/ja/docs/advanced/response-change-status-code.md b/docs/ja/docs/advanced/response-change-status-code.md index 22f5f3701..35fcc5bbd 100644 --- a/docs/ja/docs/advanced/response-change-status-code.md +++ b/docs/ja/docs/advanced/response-change-status-code.md @@ -1,5 +1,6 @@ # レスポンス - ステータスコードの変更 { #response-change-status-code } + すでに、デフォルトの[レスポンスのステータスコード](../tutorial/response-status-code.md)を設定できることをご存知かもしれません。 しかし場合によっては、デフォルトとは異なるステータスコードを返す必要があります。 diff --git a/docs/ja/docs/advanced/response-cookies.md b/docs/ja/docs/advanced/response-cookies.md index c395b09c6..912181554 100644 --- a/docs/ja/docs/advanced/response-cookies.md +++ b/docs/ja/docs/advanced/response-cookies.md @@ -1,5 +1,6 @@ # レスポンスの Cookie { #response-cookies } + ## `Response` パラメータを使う { #use-a-response-parameter } *path operation 関数*で `Response` 型のパラメータを宣言できます。 diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md index b5c9fc5cb..366eed2b9 100644 --- a/docs/ja/docs/advanced/response-directly.md +++ b/docs/ja/docs/advanced/response-directly.md @@ -18,7 +18,7 @@ 実際は、`Response` やそのサブクラスを返すことができます。 -/// info +/// note `JSONResponse` それ自体は、`Response` のサブクラスです。 diff --git a/docs/ja/docs/advanced/response-headers.md b/docs/ja/docs/advanced/response-headers.md index 3a61f5742..d5f6f31a3 100644 --- a/docs/ja/docs/advanced/response-headers.md +++ b/docs/ja/docs/advanced/response-headers.md @@ -1,5 +1,6 @@ # レスポンスヘッダー { #response-headers } + ## `Response` パラメータを使う { #use-a-response-parameter } (Cookie と同様に)*path operation 関数*で `Response` 型のパラメータを宣言できます。 diff --git a/docs/ja/docs/advanced/security/oauth2-scopes.md b/docs/ja/docs/advanced/security/oauth2-scopes.md index 3afc26e3a..b01bd01ca 100644 --- a/docs/ja/docs/advanced/security/oauth2-scopes.md +++ b/docs/ja/docs/advanced/security/oauth2-scopes.md @@ -1,5 +1,6 @@ # OAuth2 のスコープ { #oauth2-scopes } + OAuth2 のスコープは **FastAPI** で直接利用でき、シームレスに統合されています。 これにより、OAuth2 標準に従った、よりきめ細かな権限システムを、OpenAPI 対応アプリケーション(および API ドキュメント)に統合できます。 @@ -46,7 +47,7 @@ OpenAPI(例: API ドキュメント)では、「セキュリティスキー - `instagram_basic` は Facebook / Instagram で使われています。 - `https://www.googleapis.com/auth/drive` は Google で使われています。 -/// info | 情報 +/// note | 備考 OAuth2 において「スコープ」は、必要な特定の権限を宣言する単なる文字列です。 @@ -126,7 +127,7 @@ OAuth2 にとっては、単に文字列に過ぎません。 {* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *} -/// info | 技術詳細 +/// note | 技術詳細 `Security` は実際には `Depends` のサブクラスで、後述する追加パラメータが 1 つあるだけです。 diff --git a/docs/ja/docs/advanced/settings.md b/docs/ja/docs/advanced/settings.md index e42ec845c..b3fd89a46 100644 --- a/docs/ja/docs/advanced/settings.md +++ b/docs/ja/docs/advanced/settings.md @@ -52,7 +52,7 @@ Pydantic から `BaseSettings` をインポートして、そのサブクラス Pydantic モデルと同様に、型アノテーションと(必要なら)デフォルト値を持つクラス属性を宣言します。 -`Field()` による追加バリデーションなど、Pydantic モデルで使えるのと同じバリデーション機能をすべて利用できます。 +異なるデータ型や `Field()` による追加バリデーションなど、Pydantic モデルで使えるのと同じバリデーション機能とツールをすべて利用できます。 {* ../../docs_src/settings/tutorial001_py310.py hl[2,5:8,11] *} diff --git a/docs/ja/docs/advanced/stream-data.md b/docs/ja/docs/advanced/stream-data.md index 52bbfd3fd..6360cdab5 100644 --- a/docs/ja/docs/advanced/stream-data.md +++ b/docs/ja/docs/advanced/stream-data.md @@ -2,9 +2,9 @@ JSON として構造化できるデータをストリームしたい場合は、[JSON Lines をストリームする](../tutorial/stream-json-lines.md) を参照してください。 -しかし、純粋なバイナリデータや文字列をストリームしたい場合は、次のようにできます。 +しかし、**純粋なバイナリデータ**や文字列をストリームしたい場合は、次のようにできます。 -/// info | 情報 +/// note | 備考 FastAPI 0.134.0 で追加されました。 @@ -12,21 +12,21 @@ FastAPI 0.134.0 で追加されました。 ## ユースケース { #use-cases } -例えば、AI LLM サービスの出力をそのまま、純粋な文字列としてストリームしたい場合に使えます。 +例えば、**AI LLM** サービスの出力をそのまま、純粋な文字列としてストリームしたい場合に使えます。 -メモリに一度に全て読み込むことなく、読み込みながらチャンクごとに送ることで、巨大なバイナリファイルをストリームすることにも使えます。 +メモリに一度に全て読み込むことなく、読み込みながらチャンクごとに送ることで、**巨大なバイナリファイル**をストリームすることにも使えます。 -同様に、動画や音声をストリームすることもできます。処理しながら生成し、そのまま送信することも可能です。 +同様に、**動画**や**音声**をストリームすることもできます。処理しながら生成し、そのまま送信することも可能です。 ## `yield` を使った `StreamingResponse` { #a-streamingresponse-with-yield } -path operation 関数で `response_class=StreamingResponse` を宣言すると、`yield` を使ってデータをチャンクごとに順次送信できます。 +*path operation 関数*で `response_class=StreamingResponse` を宣言すると、`yield` を使ってデータをチャンクごとに順次送信できます。 {* ../../docs_src/stream_data/tutorial001_py310.py ln[1:23] hl[20,23] *} FastAPI は各データチャンクをそのまま `StreamingResponse` に渡し、JSON などに変換しようとはしません。 -### 非 async な path operation 関数 { #non-async-path-operation-functions } +### 非 async な *path operation 関数* { #non-async-path-operation-functions } `async` なしの通常の `def` 関数でも同様に `yield` を使えます。 @@ -40,7 +40,7 @@ FastAPI は各データチャンクをそのまま `StreamingResponse` に渡し {* ../../docs_src/stream_data/tutorial001_py310.py ln[32:35] hl[33] *} -つまり、`StreamingResponse` では型アノテーションに依存せず、送信したい形式に合わせてバイト列を生成・エンコードする「自由」と「責任」があなたにあります。 🤓 +つまり、`StreamingResponse` では型アノテーションに依存せず、送信したい形式に合わせてバイト列を生成・エンコードする**自由**と**責任**があなたにあります。 🤓 ### バイト列をストリームする { #stream-bytes } @@ -58,7 +58,7 @@ FastAPI は各データチャンクをそのまま `StreamingResponse` に渡し {* ../../docs_src/stream_data/tutorial002_py310.py ln[6,19:20] hl[20] *} -その後、path operation 関数で `response_class=PNGStreamingResponse` としてこの新しいクラスを使用できます: +その後、*path operation 関数*で `response_class=PNGStreamingResponse` としてこの新しいクラスを使用できます: {* ../../docs_src/stream_data/tutorial002_py310.py ln[23:27] hl[23] *} @@ -90,7 +90,7 @@ FastAPI は各データチャンクをそのまま `StreamingResponse` に渡し また、多くの場合、ディスクやネットワークから読み出すため、読み取りはブロッキング(イベントループをブロックし得る)処理になります。 -/// info | 情報 +/// note | 備考 上記の例は例外で、`io.BytesIO` は既にメモリ上にあるため、読み取りが何かをブロックすることはありません。 @@ -98,7 +98,7 @@ FastAPI は各データチャンクをそのまま `StreamingResponse` に渡し /// -イベントループのブロッキングを避けるには、path operation 関数を `async def` ではなく通常の `def` で宣言してください。そうすると FastAPI はその関数をスレッドプールワーカー上で実行し、メインループのブロッキングを避けます。 +イベントループのブロッキングを避けるには、*path operation 関数*を `async def` ではなく通常の `def` で宣言してください。そうすると FastAPI はその関数をスレッドプールワーカー上で実行し、メインループのブロッキングを避けます。 {* ../../docs_src/stream_data/tutorial002_py310.py ln[30:34] hl[31] *} diff --git a/docs/ja/docs/advanced/strict-content-type.md b/docs/ja/docs/advanced/strict-content-type.md index 994cb8672..a21832fec 100644 --- a/docs/ja/docs/advanced/strict-content-type.md +++ b/docs/ja/docs/advanced/strict-content-type.md @@ -81,7 +81,7 @@ http://localhost:8000/v1/agents/multivac この設定では、`Content-Type` ヘッダーがないリクエストでもボディが JSON として解析されます。これは古いバージョンの FastAPI と同じ挙動です。 -/// info | 情報 +/// note | 備考 この挙動と設定は FastAPI 0.132.0 で追加されました。 diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md index 802110b58..b310adfe9 100644 --- a/docs/ja/docs/advanced/websockets.md +++ b/docs/ja/docs/advanced/websockets.md @@ -111,7 +111,7 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート {* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *} -/// info | 情報 +/// note | 備考 これはWebSocketであるため、`HTTPException` を発生させることはあまり意味がありません。代わりに `WebSocketException` を発生させます。 diff --git a/docs/ja/docs/advanced/wsgi.md b/docs/ja/docs/advanced/wsgi.md index 6895eb658..40511398d 100644 --- a/docs/ja/docs/advanced/wsgi.md +++ b/docs/ja/docs/advanced/wsgi.md @@ -1,12 +1,13 @@ # WSGI の組み込み - Flask、Django など { #including-wsgi-flask-django-others } + [サブアプリケーション - マウント](sub-applications.md)、[プロキシの背後](behind-a-proxy.md) で見たように、WSGI アプリケーションをマウントできます。 そのために `WSGIMiddleware` を使用して、Flask や Django などの WSGI アプリをラップできます。 ## `WSGIMiddleware` の使用 { #using-wsgimiddleware } -/// info | 情報 +/// note | 備考 これには `a2wsgi` のインストールが必要です。例: `pip install a2wsgi`。 diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md index 34017b00e..3b3140ed8 100644 --- a/docs/ja/docs/alternatives.md +++ b/docs/ja/docs/alternatives.md @@ -36,7 +36,7 @@ Django REST Framework は Tom Christie によって作成されました。Starl /// -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション 自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 @@ -56,7 +56,7 @@ Flask は「マイクロフレームワーク」であり、データベース Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。 -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 @@ -88,7 +88,7 @@ Requestsは非常にシンプルかつ直感的なデザインで使いやすく response = requests.get("http://example.com/some/url") ``` -対応するFastAPIのAPIのpath operationはこのようになります: +対応するFastAPI側のAPI *path operation* はこのようになります: ```Python hl_lines="1" @app.get("/some/url") @@ -96,12 +96,12 @@ def read_url(): return {"message": "Hello World"} ``` - `requests.get(...)` と`@app.get(...)` には類似点が見受けられます。 +`requests.get(...)` と`@app.get(...)` には類似点が見受けられます。 -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション * シンプルで直感的なAPIを持っている点。 -* HTTPメソッド名を直接利用し、単純で直感的である。 +* HTTPメソッド名 (operation) を直接利用し、単純で直感的である。 * 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。 /// @@ -118,7 +118,7 @@ def read_url(): そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。 -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 @@ -147,7 +147,7 @@ APIが必要とするもう一つの大きな機能はデータのバリデー しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。 -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 @@ -163,13 +163,13 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上 素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。 -/// info | 情報 +/// note | 備考 Webargsは、Marshmallowと同じ開発者により作られました。 /// -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション 受信したデータに対する自動的なバリデーションを持っている点。 @@ -193,13 +193,13 @@ Flask, Starlette, Responderなどにおいてはそのように動作します エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。 -/// info | 情報 +/// note | 備考 APISpecは、Marshmallowと同じ開発者により作成されました。 /// -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション OpenAPIという、APIについてのオープンな標準をサポートしている点。 @@ -223,15 +223,15 @@ Flask、Flask-apispec、Marshmallow、Webargsの組み合わせは、**FastAPI** * [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase) * [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb) -そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md)の元となっていました。 +そして、これらのフルスタックジェネレーターは、[**FastAPI** プロジェクトジェネレーター](project-generation.md)の元となっていました。 -/// info | 情報 +/// note | 備考 Flask-apispecはMarshmallowと同じ開発者により作成されました。 /// -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 @@ -247,11 +247,11 @@ Angular 2にインスピレーションを受けた、統合された依存性 パラメータはTypeScriptの型で記述されるので (Pythonの型ヒントに似ています) 、エディタのサポートはとても良いです。 -しかし、TypeScriptのデータはJavaScriptへのコンパイル後には残されないため、バリデーション、シリアライゼーション、ドキュメント化を同時に定義するのに型に頼ることはできません。そのため、バリデーション、シリアライゼーション、スキーマの自動生成を行うためには、多くの場所でデコレータを追加する必要があり、非常に冗長になります。 +しかし、TypeScriptのデータはJavaScriptへのコンパイル後には残されないため、バリデーション、シリアライゼーション、ドキュメント化を同時に定義するのに型に頼ることはできません。このことといくつかの設計上の判断により、バリデーション、シリアライゼーション、スキーマの自動生成を行うためには、多くの場所でデコレータを追加する必要があり、非常に冗長になります。 入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。 -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 @@ -271,7 +271,7 @@ Pythonの`asyncio`ループの代わりに、[`uvloop`](https://github.com/Magic /// -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション 物凄い性能を出す方法を見つけた点。 @@ -287,7 +287,7 @@ Falconはもう一つの高性能Pythonフレームワークで、ミニマム そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。 -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション 素晴らしい性能を得るための方法を見つけた点。 @@ -313,11 +313,11 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。 -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 -同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。) +同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピレーションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。) /// @@ -333,15 +333,15 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 同じフレームワークを使ってAPIとCLIを作成できる、面白く珍しい機能を持っています。 -以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。 +以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、WebSocketなどは扱えませんが、それでも高性能です。 -/// info | 情報 +/// note | 備考 -HugはTimothy Crosleyにより作成されました。彼は[`isort`](https://github.com/timothycrosley/isort)など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 +HugはTimothy Crosleyにより作成されました。彼は[`isort`](https://github.com/timothycrosley/isort)など、Pythonのファイル内のインポートの並び替えを自動的に行う素晴らしいツールの開発者です。 /// -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**にインスピレーションを与えたアイデア HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 @@ -375,7 +375,7 @@ Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数 今ではAPIStarはOpenAPI仕様を検証するためのツールセットであり、ウェブフレームワークではありません。 -/// info | 情報 +/// note | 備考 APIStarはTom Christieにより開発されました。以下の開発者でもあります: @@ -385,7 +385,7 @@ APIStarはTom Christieにより開発されました。以下の開発者でも /// -/// check | **FastAPI**へ与えたインスピレーション +/// tip | **FastAPI**へ与えたインスピレーション 存在そのもの。 @@ -409,7 +409,7 @@ Pydanticは、Pythonの型ヒントを元にデータのバリデーション、 Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。 -/// check | **FastAPI**での使用用途 +/// tip | **FastAPI**での使用用途 データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 @@ -430,7 +430,7 @@ Starletteは、軽量な -/// info | 情報 +/// note | 備考 美しいイラストは [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot) によるものです。🎨 @@ -205,7 +205,7 @@ def results(): ほとんどの時間をカウンター前で待つ 🕙 のに費やしたため、あまり話したり、いちゃついたりできませんでした。😞 -/// info | 情報 +/// note | 備考 美しいイラストは [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot) によるものです。🎨 @@ -215,7 +215,7 @@ def results(): この「並列ハンバーガー」のシナリオでは、あなたは 2 つのプロセッサ (あなたと好きな人) を持つコンピュータ/プログラム 🤖 で、どちらも長い間 🕙「カウンターでの待機」に注意 ⏯ を専念しています。 -ファストフード店には 8 個のプロセッサ (レジ係/料理人) があります。一方、並行ハンバーガーの店には (レジ係 1、人、料理人 1 人の) 2 個しかなかったかもしれません。 +ファストフード店には 8 個のプロセッサ (レジ係/料理人) があります。一方、並行ハンバーガーの店には (レジ係 1 人、料理人 1 人の) 2 個しかなかったかもしれません。 それでも、最終的な体験は最良とは言えません。😞 diff --git a/docs/ja/docs/deployment/cloud.md b/docs/ja/docs/deployment/cloud.md index 8357464fb..5d02cacf2 100644 --- a/docs/ja/docs/deployment/cloud.md +++ b/docs/ja/docs/deployment/cloud.md @@ -6,7 +6,7 @@ FastAPI アプリケーションは、実質的にどのようなクラウドプ ## FastAPI Cloud { #fastapi-cloud } -**[FastAPI Cloud](https://fastapicloud.com)** は、**FastAPI** の作者と同じチームによって作られています。 +**[FastAPI Cloud](https://fastapicloud.com)** は、**FastAPI** の作者および同じチームによって作られています。 API の**構築**、**デプロイ**、**アクセス**までのプロセスを、最小限の手間で効率化します。 @@ -16,7 +16,7 @@ FastAPI Cloud は、*FastAPI and friends* オープンソースプロジェク ## クラウドプロバイダ - スポンサー { #cloud-providers-sponsors } -他にもいくつかのクラウドプロバイダが ✨ [**FastAPI をスポンサーしています**](../help-fastapi.md#sponsor-the-author) ✨。🙇 +他にもいくつかのクラウドプロバイダが ✨ [**FastAPI をスポンサーしています**](https://github.com/sponsors/tiangolo) ✨。🙇 それらのガイドを参考にし、サービスを試してみるのもよいでしょう: diff --git a/docs/ja/docs/deployment/concepts.md b/docs/ja/docs/deployment/concepts.md index 9a23e8e91..58f0f75ba 100644 --- a/docs/ja/docs/deployment/concepts.md +++ b/docs/ja/docs/deployment/concepts.md @@ -1,8 +1,6 @@ # デプロイメントのコンセプト { #deployments-concepts } -**FastAPI**を用いたアプリケーションをデプロイするとき、もしくはどのようなタイプのWeb APIであっても、おそらく気になるコンセプトがいくつかあります。 - -それらを活用することでアプリケーションを**デプロイするための最適な方法**を見つけることができます。 +**FastAPI**を用いたアプリケーションをデプロイするとき、もしくはどのようなタイプのWeb APIであっても、おそらく気になるコンセプトがいくつかあり、それらを活用することでアプリケーションを**デプロイするための最適な方法**を見つけることができます。 重要なコンセプトのいくつかを紹介します: @@ -17,9 +15,7 @@ 最終的な目的は、**安全な方法で**APIクライアントに**サービスを提供**し、**中断を回避**するだけでなく、**計算リソース**(例えばリモートサーバー/仮想マシン)を可能な限り効率的に使用することです。 🚀 -この章では前述した**コンセプト**についてそれぞれ説明します。 - -この説明を通して、普段とは非常に異なる環境や存在しないであろう**将来の**環境に対し、デプロイの方法を決める上で必要な**直感**を与えてくれることを願っています。 +ここではこれらの**コンセプト**についてもう少し説明します。それによって、普段とは非常に異なる環境や存在しないであろう**将来の**環境に対し、APIのデプロイ方法を決める上で必要な**直感**を与えてくれることを願っています。 これらのコンセプトを意識することにより、**あなた自身のAPI**をデプロイするための最適な方法を**評価**し、**設計**することができるようになるでしょう。 @@ -31,11 +27,12 @@ [前チャプターのHTTPSについて](https.md)では、HTTPSがどのようにAPIを暗号化するのかについて学びました。 -通常、アプリケーションサーバにとって**外部の**コンポーネントである**TLS Termination Proxy**によって提供されることが一般的です。このプロキシは通信の暗号化を担当します。 +また、HTTPSは通常、アプリケーションサーバにとって**外部の**コンポーネントである**TLS Termination Proxy**によって提供されることも確認しました。 -さらに、HTTPS証明書の更新を担当するものが必要で、同じコンポーネントが担当することもあれば、別のコンポーネントが担当することもあります。 +さらに、**HTTPS証明書の更新**を担当するものが必要で、同じコンポーネントが担当することもあれば、別のコンポーネントが担当することもあります。 ### HTTPS 用ツールの例 { #example-tools-for-https } + TLS Termination Proxyとして使用できるツールには以下のようなものがあります: * Traefik @@ -148,17 +145,17 @@ FastAPIでWeb APIを構築する際に、コードにエラーがある場合、 しかしながら、**アプリケーション全体をクラッシュさせるようなコードを書いて**UvicornとPythonをクラッシュさせるようなケースもあるかもしれません。💥 -それでも、ある箇所でエラーが発生したからといって、アプリケーションを停止させたままにしたくないでしょう。 少なくとも壊れていない*path operation*については、**実行し続けたい**はずです。 +それでも、ある箇所でエラーが発生したからといって、アプリケーションを停止させたままにしたくないでしょう。 少なくとも壊れていない*path operations*については、**実行し続けたい**はずです。 ### クラッシュ後の再起動 { #restart-after-crash } -しかし、実行中の**プロセス**をクラッシュさせるような本当にひどいエラーの場合、少なくとも2〜3回ほどプロセスを**再起動**させる外部コンポーネントが必要でしょう。 +しかし、実行中の**プロセス**をクラッシュさせるような本当にひどいエラーの場合、少なくとも2〜3回ほどプロセスを**再起動**させる外部コンポーネントが必要でしょう... /// tip | 豆知識 ...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。 -そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 +そこで、**将来**特定のケースで完全にクラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 /// @@ -207,9 +204,7 @@ FastAPI アプリケーションでは、Uvicorn を実行する `fastapi` コ ### サーバーメモリ { #server-memory } -例えば、あなたのコードが **1GBのサイズの機械学習モデル**をロードする場合、APIで1つのプロセスを実行すると、少なくとも1GBのRAMを消費します。 - -また、**4つのプロセス**(4つのワーカー)を起動すると、それぞれが1GBのRAMを消費します。つまり、合計でAPIは**4GBのRAM**を消費することになります。 +例えば、あなたのコードが **1GBのサイズの機械学習モデル**をロードする場合、APIで1つのプロセスを実行すると、少なくとも1GBのRAMを消費します。また、**4つのプロセス**(4つのワーカー)を起動すると、それぞれが1GBのRAMを消費します。つまり、合計でAPIは**4GBのRAM**を消費することになります。 リモートサーバーや仮想マシンのRAMが3GBしかない場合、4GB以上のRAMをロードしようとすると問題が発生します。🚨 @@ -233,9 +228,7 @@ FastAPI アプリケーションでは、Uvicorn を実行する `fastapi` コ これを実現するにはいくつかのアプローチがありますが、具体的な戦略については次の章(Dockerやコンテナの章など)で詳しく説明します。 -考慮すべき主な制約は、**パブリックIP**の**ポート**を処理する**単一の**コンポーネントが存在しなければならないということです。 - -そして、レプリケートされた**プロセス/ワーカー**に通信を**送信**する方法を持つ必要があります。 +考慮すべき主な制約は、**パブリックIP**の**ポート**を処理する**単一の**コンポーネントが存在しなければならないということです。そして、レプリケートされた**プロセス/ワーカー**に通信を**送信**する方法を持つ必要があります。 考えられる組み合わせと戦略をいくつか紹介します: @@ -243,7 +236,7 @@ FastAPI アプリケーションでは、Uvicorn を実行する `fastapi` コ * 1つのUvicornの**プロセスマネージャー**が**IP**と**ポート**をリッスンし、**複数のUvicornワーカー・プロセス**を起動する。 * **Kubernetes**やその他の分散**コンテナ・システム** * **Kubernetes**レイヤーの何かが**IP**と**ポート**をリッスンする。レプリケーションは、**複数のコンテナ**にそれぞれ**1つのUvicornプロセス**を実行させることで行われる。 -* **クラウド・サービス**によるレプリケーション +* これを代わりに処理する**クラウド・サービス** * クラウド・サービスはおそらく**あなたのためにレプリケーションを処理**します。**実行するプロセス**や使用する**コンテナイメージ**を定義できるかもしれませんが、いずれにせよ、それはおそらく**単一のUvicornプロセス**であり、クラウドサービスはそのレプリケーションを担当するでしょう。 /// tip | 豆知識 @@ -264,9 +257,7 @@ FastAPI アプリケーションでは、Uvicorn を実行する `fastapi` コ そのため、アプリケーションを開始する前の**事前のステップ**を実行する**単一のプロセス**を用意したいと思われます。 -そして、それらの事前のステップを実行しているのが単一のプロセスであることを確認する必要があります。このことはその後アプリケーション自体のために**複数のプロセス**(複数のワーカー)を起動した場合も同様です。 - -これらのステップが**複数のプロセス**によって実行された場合、**並列**に実行されることによって作業が**重複**することになります。そして、もしそのステップがデータベースのマイグレーションのような繊細なものであった場合、互いに競合を引き起こす可能性があります。 +そして、それらの事前のステップを実行しているのが単一のプロセスであることを確認する必要があります。これはその後アプリケーション自体のために**複数のプロセス**(複数のワーカー)を起動した場合も同様です。これらのステップが**複数のプロセス**によって実行された場合、**並列**に実行されることによって作業が**重複**することになります。そして、もしそのステップがデータベースのマイグレーションのような繊細なものであった場合、互いに競合を引き起こす可能性があります。 もちろん、事前のステップを何度も実行しても問題がない場合もあり、その際は対処がかなり楽になります。 @@ -284,7 +275,7 @@ FastAPI アプリケーションでは、Uvicorn を実行する `fastapi` コ 考えられるアイデアをいくつか挙げてみます: -* アプリコンテナの前に実行されるKubernetesのInitコンテナ +* アプリコンテナの前に実行されるKubernetesの「Init Container」 * 事前のステップを実行し、アプリケーションを起動するbashスクリプト * 利用するbashスクリプトを起動/再起動したり、エラーを検出したりする方法は以前として必要になるでしょう。 @@ -296,7 +287,7 @@ FastAPI アプリケーションでは、Uvicorn を実行する `fastapi` コ ## リソースの利用 { #resource-utilization } -あなたのサーバーは**リソース**であり、プログラムを実行しCPUの計算時間や利用可能なRAMメモリを消費または**利用**することができます。 +あなたのサーバーは(複数の場合も)**リソース**であり、プログラムを実行しCPUの計算時間や利用可能なRAMメモリを消費または**利用**することができます。 システムリソースをどれくらい消費/利用したいですか? 「少ない方が良い」と考えるのは簡単かもしれないですが、実際には、**クラッシュせずに可能な限り**最大限に活用したいでしょう。 @@ -309,11 +300,9 @@ FastAPI アプリケーションでは、Uvicorn を実行する `fastapi` コ この場合、**1つ余分なサーバー**を用意し、その上でいくつかのプロセスを実行し、すべてのサーバーが**十分なRAMとCPU時間を持つようにする**のがよいでしょう。 -また、何らかの理由でAPIの利用が急増する可能性もあります。もしかしたらそれが流行ったのかもしれないし、他のサービスやボットが使い始めたのかもしれないです。そのような場合に備えて、余分なリソースを用意しておくと安心でしょう。 - -例えば、リソース使用率の**50%から90%の範囲**で**任意の数字**をターゲットとすることができます。 +また、何らかの理由でAPIの利用が**急増**する可能性もあります。もしかしたらそれが流行ったのかもしれないし、他のサービスやボットが使い始めたのかもしれないです。そのような場合に備えて、余分なリソースを用意しておくと安心でしょう。 -重要なのは、デプロイメントを微調整するためにターゲットを設定し測定することが、おそらく使用したい主要な要素であることです。 +例えば、リソース使用率の**50%から90%の範囲**で**任意の数字**をターゲットとすることができます。重要なのは、デプロイメントを微調整するために測定して使用したい主要な要素は、おそらくそれらであるということです。 `htop`のような単純なツールを使って、サーバーで使用されているCPUやRAM、あるいは各プロセスで使用されている量を見ることができます。あるいは、より複雑な監視ツールを使って、サーバに分散して使用することもできます。 diff --git a/docs/ja/docs/deployment/docker.md b/docs/ja/docs/deployment/docker.md index 6248e69b7..26e9d5647 100644 --- a/docs/ja/docs/deployment/docker.md +++ b/docs/ja/docs/deployment/docker.md @@ -11,7 +11,7 @@ Linuxコンテナの使用には、**セキュリティ**、**反復可能性( ///
-Dockerfile Preview 👀 +Dockerfile プレビュー 👀 ```Dockerfile FROM python:3.14 @@ -26,7 +26,7 @@ COPY ./app /code/app CMD ["fastapi", "run", "app/main.py", "--port", "80"] -# If running behind a proxy like Nginx or Traefik add --proxy-headers +# Nginx や Traefik のようなプロキシの背後で実行する場合は --proxy-headers を追加します # CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"] ``` @@ -132,7 +132,7 @@ Successfully installed fastapi pydantic -/// info | 情報 +/// note | 備考 パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。 @@ -243,14 +243,14 @@ Docker命令 [`CMD`](https://docs.docker.com/reference/dockerfile/#cmd) は2つ ✅ **Exec** 形式: ```Dockerfile -# ✅ Do this +# ✅ こうしてください CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` ⛔️ **Shell** 形式: ```Dockerfile -# ⛔️ Don't do this +# ⛔️ こうしないでください CMD fastapi run app/main.py --port 80 ``` @@ -340,7 +340,7 @@ $ docker build -t myimage . /// -### Dockerコンテナの起動する { #start-the-docker-container } +### Dockerコンテナを起動する { #start-the-docker-container } * イメージに基づいてコンテナを実行します: @@ -417,7 +417,7 @@ CMD ["fastapi", "run", "main.py", "--port", "80"] コンテナという観点から、[デプロイのコンセプト](concepts.md)に共通するいくつかについて、もう一度説明しましょう。 -コンテナは主に、アプリケーションの**ビルドとデプロイ**のプロセスを簡素化するためのツールですが、これらの**デプロイのコンセプト**を扱うための特定のアプローチを強制するものではなく、いくつかの戦略があります。 +コンテナは主に、アプリケーションの**ビルドとデプロイ**のプロセスを簡素化するための工具ですが、これらの**デプロイのコンセプト**を扱うための特定のアプローチを強制するものではなく、いくつかの戦略があります。 **良いニュース**は、それぞれの異なる戦略には、すべてのデプロイメントのコンセプトをカバーする方法があるということです。🎉 @@ -562,7 +562,7 @@ Docker Composeで**単一サーバ**(クラスタではない)にデプロ 複数の**コンテナ**があり、おそらくそれぞれが**単一のプロセス**を実行している場合(例えば、**Kubernetes**クラスタなど)、レプリケートされたワーカーコンテナを実行する**前に**、単一のコンテナで**事前のステップ**の作業を行う**別のコンテナ**を持ちたいと思うでしょう。 -/// info | 情報 +/// note | 備考 もしKubernetesを使用している場合, これはおそらく[Init Container](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/)でしょう。 diff --git a/docs/ja/docs/deployment/fastapicloud.md b/docs/ja/docs/deployment/fastapicloud.md index 3dd5685a2..d8c1cb2ec 100644 --- a/docs/ja/docs/deployment/fastapicloud.md +++ b/docs/ja/docs/deployment/fastapicloud.md @@ -1,26 +1,6 @@ # FastAPI Cloud { #fastapi-cloud } -[FastAPI Cloud](https://fastapicloud.com) に **コマンド1つ** でデプロイできます。まだならウェイティングリストにご登録ください。🚀 - -## ログイン { #login } - -すでに **FastAPI Cloud** アカウントをお持ちであることを確認してください(ウェイティングリストからご招待しています 😉)。 - -次にログインします: - -
- -```console -$ fastapi login - -You are logged in to FastAPI Cloud 🚀 -``` - -
- -## デプロイ { #deploy } - -では、**コマンド1つ** でアプリをデプロイします: +[FastAPI Cloud](https://fastapicloud.com) に **コマンド1つ** で FastAPI アプリをデプロイできます。🚀
@@ -36,6 +16,8 @@ Deploying to FastAPI Cloud...
+CLI は FastAPI アプリケーションを自動検出してクラウドにデプロイします。ログインしていない場合は、認証を完了するためにブラウザが開きます。 + 以上です!その URL からアプリにアクセスできます。✨ ## FastAPI Cloud について { #about-fastapi-cloud } diff --git a/docs/ja/docs/deployment/https.md b/docs/ja/docs/deployment/https.md index 37ad7072c..fc4ca9b67 100644 --- a/docs/ja/docs/deployment/https.md +++ b/docs/ja/docs/deployment/https.md @@ -43,7 +43,6 @@ TLS Termination Proxyとして使えるオプションには、以下のよう * Nginx * HAProxy - ## Let's Encrypt { #lets-encrypt } Let's Encrypt以前は、これらの**HTTPS証明書**は信頼できる第三者によって販売されていました。 @@ -100,11 +99,9 @@ TLS接続を確立するためのクライアントとサーバー間のこの ### SNI拡張機能付きのTLS { #tls-with-sni-extension } -サーバー内の**1つのプロセス**だけが、特定の**IPアドレス**の特定の**ポート**で待ち受けることができます。 - -同じIPアドレスの他のポートで他のプロセスがリッスンしている可能性もありますが、IPアドレスとポートの組み合わせごとに1つだけです。 +サーバー内の**1つのプロセス**だけが、特定の**IPアドレス**の特定の**ポート**で待ち受けることができます。同じIPアドレスの他のポートで他のプロセスがリッスンしている可能性もありますが、IPアドレスとポートの組み合わせごとに1つだけです。 -TLS(HTTPS)はデフォルトで`443`という特定のポートを使用する。つまり、これが必要なポートです。 +TLS(HTTPS)はデフォルトで`443`という特定のポートを使用します。つまり、これが必要なポートです。 このポートをリクエストできるのは1つのプロセスだけなので、これを実行するプロセスは**TLS Termination Proxy**となります。 @@ -120,9 +117,9 @@ TLS Termination Proxyは、1つ以上の**TLS証明書**(HTTPS証明書)に 次に証明書を使用して、クライアントとTLS Termination Proxy は、 **TCP通信**の残りを**どのように暗号化するかを決定**します。これで**TLSハンドシェイク**の部分が完了します。 -この後、クライアントとサーバーは**暗号化されたTCP接続**を持ちます。そして、その接続を使って実際の**HTTP通信**を開始することができます。 +この後、クライアントとサーバーは**暗号化されたTCP接続**を持ちます。これがTLSの提供するものです。そして、その接続を使って実際の**HTTP通信**を開始することができます。 -これが**HTTPS**であり、純粋な(暗号化されていない)TCP接続ではなく、**セキュアなTLS接続**の中に**HTTP**があるだけです。 +これが**HTTPS**であり、純粋な(暗号化されていない)TCP接続ではなく、**セキュアなTLS接続**の中に単なる**HTTP**があるだけです。 /// tip | 豆知識 @@ -152,7 +149,7 @@ TLS Termination Proxy は、合意が取れている暗号化を使用して、* ### HTTPS レスポンス { #https-response } -TLS Termination Proxyは次に、事前に合意が取れている暗号(`someapp.example.com`の証明書から始まる)を使って**レスポンスを暗号化し**、ブラウザに送り返す。 +TLS Termination Proxyは次に、事前に合意が取れている暗号(`someapp.example.com`の証明書から始まる)を使って**レスポンスを暗号化し**、ブラウザに送り返します。 その後ブラウザでは、レスポンスが有効で正しい暗号キーで暗号化されていることなどを検証します。そして、ブラウザはレスポンスを**復号化**して処理します。 @@ -191,7 +188,6 @@ TLS Termination Proxyは次に、事前に合意が取れている暗号(`someap * これは、同じTLS Termination Proxyが証明書の更新処理も行う場合に非常に便利な理由の1つです。 * そうでなければ、TLS Termination Proxyを一時的に停止し、証明書を取得するために更新プログラムを起動し、TLS Termination Proxyで証明書を設定し、TLS Termination Proxyを再起動しなければならないかもしれません。TLS Termination Proxyが停止している間はアプリが利用できなくなるため、これは理想的ではありません。 - アプリを提供しながらこのような更新処理を行うことは、アプリケーション・サーバー(Uvicornなど)でTLS証明書を直接使用するのではなく、TLS Termination Proxyを使用して**HTTPSを処理する別のシステム**を用意したくなる主な理由の1つです。 ## プロキシ転送ヘッダー { #proxy-forwarded-headers } diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md index 1c0d59a71..98cd48575 100644 --- a/docs/ja/docs/deployment/manually.md +++ b/docs/ja/docs/deployment/manually.md @@ -1,6 +1,6 @@ # サーバーを手動で実行する { #run-a-server-manually } -## fastapi run コマンドを使う { #use-the-fastapi-run-command } +## `fastapi run` コマンドを使う { #use-the-fastapi-run-command } 結論として、FastAPI アプリケーションを提供するには `fastapi run` を使います: @@ -56,7 +56,6 @@ FastAPI は、Python の Web フレームワークとサーバーのための標 * [Hypercorn](https://hypercorn.readthedocs.io/): HTTP/2 や Trio に対応する ASGI サーバーなど。 * [Daphne](https://github.com/django/daphne): Django Channels のために作られた ASGI サーバー。 * [Granian](https://github.com/emmett-framework/granian): Python アプリケーション向けの Rust 製 HTTP サーバー。 -* [NGINX Unit](https://unit.nginx.org/howto/fastapi/): 軽量で多用途な Web アプリケーションランタイム。 ## サーバーマシンとサーバープログラム { #server-machine-and-server-program } diff --git a/docs/ja/docs/deployment/server-workers.md b/docs/ja/docs/deployment/server-workers.md index c4c6e9355..55cf2d247 100644 --- a/docs/ja/docs/deployment/server-workers.md +++ b/docs/ja/docs/deployment/server-workers.md @@ -17,7 +17,7 @@ ここでは、`fastapi` コマンド、または `uvicorn` コマンドを直接使って、**ワーカープロセス**付きの **Uvicorn** を使う方法を紹介します。 -/// info | 情報 +/// note DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md)。 diff --git a/docs/ja/docs/editor-support.md b/docs/ja/docs/editor-support.md index d82e970f9..b0e5466d6 100644 --- a/docs/ja/docs/editor-support.md +++ b/docs/ja/docs/editor-support.md @@ -20,4 +20,4 @@ - **FastAPI Cloud へデプロイ** - [FastAPI Cloud](https://fastapicloud.com/) にワンクリックでアプリをデプロイできます。 - **アプリケーションログのストリーミング** - FastAPI Cloud にデプロイしたアプリから、レベルフィルタやテキスト検索付きでリアルタイムにログをストリーミングできます。 -拡張機能の機能に慣れるには、コマンドパレット(Ctrl + Shift + P、macOS: Cmd + Shift + P)を開き、"Welcome: Open walkthrough..." を選択してから、"Get started with FastAPI" のウォークスルーを選んでください。 +拡張機能の機能に慣れるには、コマンドパレット(Ctrl + Shift + P、macOS: Cmd + Shift + P)を開き、「Welcome: Open walkthrough...」を選択してから、「Get started with FastAPI」のウォークスルーを選んでください。 diff --git a/docs/ja/docs/environment-variables.md b/docs/ja/docs/environment-variables.md index 846f32846..eb20d3a58 100644 --- a/docs/ja/docs/environment-variables.md +++ b/docs/ja/docs/environment-variables.md @@ -163,7 +163,7 @@ Hello World from Python つまり、環境変数からPythonで読み取る**あらゆる値**は **`str`になり**、他の型への変換やバリデーションはコード内で行う必要があります。 -環境変数を使って**アプリケーション設定**を扱う方法については、[高度なユーザーガイド - Settings and Environment Variables](./advanced/settings.md)で詳しく学べます。 +環境変数を使って**アプリケーション設定**を扱う方法については、[高度なユーザーガイド - 設定と環境変数](./advanced/settings.md)で詳しく学べます。 ## `PATH`環境変数 { #path-environment-variable } @@ -285,7 +285,7 @@ $ C:\opt\custompython\bin\python //// -この情報は、[Virtual Environments](virtual-environments.md)について学ぶ際にも役立ちます。 +この情報は、[仮想環境](virtual-environments.md)について学ぶ際にも役立ちます。 ## まとめ { #conclusion } @@ -295,4 +295,4 @@ $ C:\opt\custompython\bin\python 多くの場合、環境変数がどのように役立ち、すぐに適用できるのかはあまり明確ではありません。しかし、開発中のさまざまなシナリオで何度も登場するため、知っておくとよいでしょう。 -例えば、次のセクションの[Virtual Environments](virtual-environments.md)でこの情報が必要になります。 +例えば、次のセクションの[仮想環境](virtual-environments.md)でこの情報が必要になります。 diff --git a/docs/ja/docs/fastapi-cli.md b/docs/ja/docs/fastapi-cli.md index 298ed9141..70bef6cd8 100644 --- a/docs/ja/docs/fastapi-cli.md +++ b/docs/ja/docs/fastapi-cli.md @@ -95,7 +95,7 @@ entrypoint = "backend.main:app" from backend.main import app ``` -### パス指定での `fastapi dev` { #fastapi-dev-with-path } +### パス指定または `--entrypoint` オプション付きの `fastapi dev` { #fastapi-dev-with-path-or-with-entrypoint-cli-option } `fastapi dev` コマンドにファイルパスを渡すこともでき、使用する FastAPI アプリオブジェクトを推測します: @@ -103,7 +103,13 @@ from backend.main import app $ fastapi dev main.py ``` -ただし、そのたびに `fastapi` コマンドを呼び出す際に正しいパスを渡す必要があります。 +または、`fastapi dev` コマンドに `--entrypoint` オプションを渡すこともできます: + +```console +$ fastapi dev --entrypoint main:app +``` + +ただし、そのたびに `fastapi` コマンドを呼び出す際に正しいパスや entrypoint を渡す必要があります。 さらに、[VS Code 拡張機能](editor-support.md) や [FastAPI Cloud](https://fastapicloud.com) など、ほかのツールがそれを見つけられない場合があります。そのため、`pyproject.toml` の `entrypoint` を使用することを推奨します。 diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index cfde6592d..930988428 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -36,13 +36,13 @@ from datetime import date from pydantic import BaseModel -# Declare a variable as a str -# and get editor support inside the function +# 変数を str として宣言 +# 関数内でエディタの支援を受ける def main(user_id: str): return user_id -# A Pydantic model +# Pydantic モデル class User(BaseModel): id: int name: str @@ -63,7 +63,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info +/// note | 備考 `**second_user_data` は次の意味です: @@ -99,7 +99,7 @@ Python 開発者調査では、[最もよく使われる機能の 1 つが「オ すべてに妥当な **デフォルト** があり、どこでもオプションで構成できます。必要に応じてすべてのパラメータを微調整して、求める API を定義できます。 -しかしデフォルトのままでも、すべて **うまく動きます**。 +しかしデフォルトのままでも、すべて **「うまく動きます」**。 ### 検証 { #validation } @@ -140,7 +140,7 @@ FastAPI には、非常に使いやすく、かつ非常に強力な @@ -44,28 +49,37 @@ FastAPI は、Python の標準である型ヒントに基づいて Python で AP * **簡単**: 簡単に利用・習得できるようにデザインされています。ドキュメントを読む時間を削減します。 * **短い**: コードの重複を最小限にします。各パラメータ宣言から複数の機能を得られます。バグも減ります。 * **堅牢性**: 自動対話型ドキュメントにより、本番環境向けのコードが得られます。 -* **Standards-based**: API のオープンスタンダードに基づいており(そして完全に互換性があります)、[OpenAPI](https://github.com/OAI/OpenAPI-Specification)(以前は Swagger として知られていました)や [JSON Schema](https://json-schema.org/) をサポートします。 +* **標準準拠**: API のオープンスタンダードに基づいており(そして完全に互換性があります)、[OpenAPI](https://github.com/OAI/OpenAPI-Specification)(以前は Swagger として知られていました)や [JSON Schema](https://json-schema.org/) をサポートします。 * 本番アプリケーションを構築している社内開発チームのテストに基づく見積もりです。 -## Sponsors { #sponsors } +## スポンサー { #sponsors } -### Keystone Sponsor { #keystone-sponsor } +### Keystone スポンサー { #keystone-sponsor } +
{% for sponsor in sponsors.keystone -%} - +{{ sponsor.title }} {% endfor -%} +
-### Gold and Silver Sponsors { #gold-and-silver-sponsors } +### Gold スポンサー { #gold-sponsors } +
{% for sponsor in sponsors.gold -%} - +{{ sponsor.title }} {% endfor -%} -{%- for sponsor in sponsors.silver -%} - +
+ +### Silver スポンサー { #silver-sponsors } + +
+{% for sponsor in sponsors.silver -%} +{{ sponsor.title }} {% endfor %} +
@@ -73,7 +87,45 @@ FastAPI は、Python の標準である型ヒントに基づいて Python で AP ## 評価 { #opinions } -"_[...] 最近 **FastAPI** を使っています。 [...] 実際に私のチームの全ての **Microsoft の機械学習サービス** で使用する予定です。 そのうちのいくつかのコアな **Windows** 製品と **Office** 製品に統合されつつあります。_" + +
+
+ + + + +
+ +
+
「最近は **FastAPI** をたくさん使っています。実際、私のチームの **Microsoft の ML サービス** 全てで使用する予定です。そのいくつかはコアな **Windows** 製品や **Office** 製品に統合されつつあります。」
+
— Kabir Khan, Microsoft (ref)
+
+ + + +
+ + +
+ +"_[...] 最近 **FastAPI** をたくさん使っています。 [...] 実際に私のチームの全ての **Microsoft の機械学習サービス** で使用する予定です。 そのうちのいくつかのコアな **Windows** 製品と **Office** 製品に統合されつつあります。_"
Kabir Khan - Microsoft (ref)
@@ -91,37 +143,25 @@ FastAPI は、Python の標準である型ヒントに基づいて Python で AP --- -"_私は **FastAPI** にワクワクしています。 めちゃくちゃ楽しいです!_" - -
Brian Okken - [Python Bytes](https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855) podcast host (ref)
- ---- - -"_正直、あなたが作ったものは超堅実で洗練されているように見えます。いろんな意味で、それは私が **Hug** にそうなってほしかったものです。誰かがそれを作るのを見るのは本当に刺激的です。_" +"_本番運用の Python API を構築したい方には、**FastAPI** を強くおすすめします。**美しく設計**されており、**使いやすく**、**高いスケーラビリティ**があります。私たちの API ファースト開発戦略の **主要コンポーネント** となり、Virtual TAC Engineer などの多くの自動化やサービスを推進しています。_" -
Timothy Crosley - [Hug](https://github.com/hugapi/hug) creator (ref)
+
Deon Pillsbury - Cisco (ref)
--- -"_REST API を構築するための **モダンなフレームワーク** を学びたい方は、**FastAPI** [...] をチェックしてみてください。 [...] 高速で、使用・習得が簡単です [...]_" - -"_私たちの **API** は **FastAPI** に切り替えました [...] きっと気に入ると思います [...]_" - -
Ines Montani - Matthew Honnibal - [Explosion AI](https://explosion.ai) founders - [spaCy](https://spacy.io) creators (ref) - (ref)
- ---- +
-"_本番運用の Python API を構築したい方には、**FastAPI** を強くおすすめします。**美しく設計**されており、**使いやすく**、**高いスケーラビリティ**があります。私たちの API ファースト開発戦略の **主要コンポーネント** となり、Virtual TAC Engineer などの多くの自動化やサービスを推進しています。_" +## FastAPI Conf { #fastapi-conf } -
Deon Pillsbury - Cisco (ref)
+[**FastAPI Conf '26**](https://fastapiconf.com) は **2026 年 10 月 28 日** に **オランダ・アムステルダム** で開催されます。FastAPI のすべてを、ソースから直接。🎤 ---- +FastAPI Conf '26 - 2026年10月28日 - オランダ・アムステルダム ## FastAPI ミニドキュメンタリー { #fastapi-mini-documentary } 2025 年末に公開された [FastAPI ミニドキュメンタリー](https://www.youtube.com/watch?v=mpR8ngthqiE)があります。オンラインで視聴できます: -FastAPI Mini Documentary +FastAPI Mini Documentary ## **Typer**、CLI 版 FastAPI { #typer-the-fastapi-of-clis } @@ -235,7 +275,7 @@ INFO: Application startup complete.
-fastapi dev コマンドについて +fastapi dev コマンドについて... `fastapi dev` コマンドは `main.py` ファイルを自動的に読み取り、その中の **FastAPI** アプリを検出し、[Uvicorn](https://www.uvicorn.dev) を使用してサーバーを起動します。 @@ -431,11 +471,11 @@ item: Item ...に変更し、エディタが属性を自動補完し、その型を知ることを確認してください。 -![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) +![エディタサポート](https://fastapi.tiangolo.com/img/vscode-completion.png) -より多くの機能を含む、より完全な例については、Tutorial - User Guide を参照してください。 +より多くの機能を含む、より完全な例については、チュートリアル - ユーザーガイド を参照してください。 -**ネタバレ注意**: tutorial - user guide には以下が含まれます。 +**ネタバレ注意**: チュートリアル - ユーザーガイドには以下が含まれます。 * **ヘッダー**、**Cookie**、**フォームフィールド**、**ファイル**など、他のさまざまな場所からの **パラメータ** 宣言。 * `maximum_length` や `regex` のような **検証制約** を設定する方法。 @@ -452,9 +492,7 @@ item: Item ### アプリをデプロイ(任意) { #deploy-your-app-optional } -必要に応じて FastAPI アプリを [FastAPI Cloud](https://fastapicloud.com) にデプロイできます。まだの場合はウェイティングリストに参加してください。 🚀 - -すでに **FastAPI Cloud** アカウント(ウェイティングリストから招待されました 😉)がある場合は、1 コマンドでアプリケーションをデプロイできます。 +1 コマンドで FastAPI アプリを [FastAPI Cloud](https://fastapicloud.com) にデプロイできます。 🚀
@@ -470,6 +508,8 @@ Deploying to FastAPI Cloud...
+CLI は自動的に FastAPI アプリケーションを検出し、クラウドへデプロイします。ログインしていない場合は、認証を完了するためにブラウザが開きます。 + これで完了です!その URL でアプリにアクセスできます。 ✨ #### FastAPI Cloud について { #about-fastapi-cloud } diff --git a/docs/ja/docs/project-generation.md b/docs/ja/docs/project-generation.md index b6550e3ac..829d6a608 100644 --- a/docs/ja/docs/project-generation.md +++ b/docs/ja/docs/project-generation.md @@ -2,7 +2,7 @@ テンプレートは通常、特定のセットアップが含まれていますが、柔軟でカスタマイズできるように設計されています。これにより、プロジェクトの要件に合わせて変更・適応でき、優れた出発点になります。🏁 -このテンプレートを使って開始できます。初期セットアップ、セキュリティ、データベース、いくつかのAPIエンドポイントがすでに用意されています。 +このテンプレートを使って開始できます。初期セットアップの多く、セキュリティ、データベース、いくつかのAPIエンドポイントがすでに用意されています。 GitHubリポジトリ: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template) diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md index 67336c31e..e6ff3c25d 100644 --- a/docs/ja/docs/python-types.md +++ b/docs/ja/docs/python-types.md @@ -151,7 +151,7 @@ def some_function(data: Any): 一部の型は、角括弧内で「型パラメータ」を受け取り、内部の型を定義できます。例えば「文字列のリスト」は `list[str]` として宣言します。 -このように型パラメータを取れる型は **Generic types**(ジェネリクス)と呼ばれます。 +このように型パラメータを取れる型は **Generic types** または **Generics**(ジェネリクス)と呼ばれます。 次の組み込み型をジェネリクスとして(角括弧と内部の型で)使えます: @@ -172,7 +172,7 @@ def some_function(data: Any): {* ../../docs_src/python_types/tutorial006_py310.py hl[1] *} -/// info | 情報 +/// note | 備考 角括弧内の内部の型は「型パラメータ」と呼ばれています。 @@ -283,9 +283,9 @@ Pydantic の公式ドキュメントからの例: {* ../../docs_src/python_types/tutorial011_py310.py *} -/// info | 情報 +/// note | 備考 -[ Pydantic の詳細はドキュメントを参照してください](https://docs.pydantic.dev/)。 +[Pydantic の詳細はドキュメントを参照してください](https://docs.pydantic.dev/)。 /// @@ -341,8 +341,8 @@ Python 自体は、この `Annotated` で何かをするわけではありませ 重要なのは、Python の標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1 つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。 -/// info | 情報 +/// note | 備考 -すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、良いリソースとして [`mypy` の「チートシート`](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html) があります。 +すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、良いリソースとして [`mypy` の「チートシート」](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html) があります。 /// diff --git a/docs/ja/docs/tutorial/bigger-applications.md b/docs/ja/docs/tutorial/bigger-applications.md index 3518eaed3..51ea7be51 100644 --- a/docs/ja/docs/tutorial/bigger-applications.md +++ b/docs/ja/docs/tutorial/bigger-applications.md @@ -4,7 +4,7 @@ **FastAPI** は、柔軟性を保ったままアプリケーションを構造化できる便利なツールを提供します。 -/// info | 情報 +/// note | 備考 Flask 出身であれば、Flask の Blueprint に相当します。 @@ -17,16 +17,16 @@ Flask 出身であれば、Flask の Blueprint に相当します。 ``` . ├── app -│   ├── __init__.py -│   ├── main.py -│   ├── dependencies.py -│   └── routers -│   │ ├── __init__.py -│   │ ├── items.py -│   │ └── users.py -│   └── internal -│   ├── __init__.py -│   └── admin.py +│ ├── __init__.py +│ ├── main.py +│ ├── dependencies.py +│ └── routers +│ │ ├── __init__.py +│ │ ├── items.py +│ │ └── users.py +│ └── internal +│ ├── __init__.py +│ └── admin.py ``` /// tip | 豆知識 @@ -194,7 +194,7 @@ async def read_item(item_id: str): /// -/// check | 確認 +/// tip | 豆知識 `prefix`、`tags`、`responses`、`dependencies` の各パラメータは(ほかの多くのケースと同様に)コード重複を避けるための **FastAPI** の機能です。 @@ -339,7 +339,7 @@ from .routers import items, users from app.routers import items, users ``` -/// info | 情報 +/// note | 備考 最初のバージョンは「相対インポート」です: @@ -382,7 +382,7 @@ from .routers.users import router {* ../../docs_src/bigger_applications/app_an_py310/main.py hl[10:11] title["app/main.py"] *} -/// info | 情報 +/// note | 備考 `users.router` は、ファイル `app/routers/users.py` 内の `APIRouter` を含みます。 @@ -396,17 +396,17 @@ from .routers.users import router /// note | 技術詳細 -実際には、`APIRouter` で宣言された各 *path operation* ごとに内部的に *path operation* が作成されます。 +FastAPI は、ルーターをメインアプリに取り込んだ後も、元の `APIRouter` とその `APIRoute` を有効なまま保持します。 -つまり裏側では、すべてが同じ単一のアプリであるかのように動作します。 +そのため、カスタムの `APIRouter` や `APIRoute` のサブクラスも、取り込み後に引き続き機能します。 /// -/// check | 確認 +/// tip | 豆知識 ルーターを取り込んでもパフォーマンスを心配する必要はありません。 -これは起動時にマイクロ秒で行われます。 +これは軽量に設計され、各リクエストにオーバーヘッドを追加しないようになっています。 したがってパフォーマンスには影響しません。⚡ @@ -451,7 +451,7 @@ from .routers.users import router そして、`app.include_router()` で追加したほかの *path operations* と一緒に正しく動作します。 -/// info | 非常に技術的な詳細 +/// note | 技術詳細 注記: これは非常に技術的な詳細で、**読み飛ばして構いません**。 @@ -461,7 +461,7 @@ from .routers.users import router これは、それらの *path operations* を OpenAPI スキーマやユーザーインターフェースに含めたいからです。 -完全に分離して独立に「マウント」できないため、*path operations* は直接取り込まれるのではなく「クローン(再作成)」されます。 +FastAPI は元のルーターと *path operations* を有効なまま保持し、リクエスト処理や OpenAPI 生成の際に、ルーターの prefix、dependencies、tags、responses、その他のメタデータを組み合わせます。 /// @@ -532,4 +532,16 @@ $ fastapi dev router.include_router(other_router) ``` -`router` を `FastAPI` アプリに取り込む前にこれを実行して、`other_router` の *path operations* も含まれるようにしてください。 +これは、`router` を `FastAPI` アプリに取り込む前でも後でも実行できます。FastAPI は `other_router` の *path operations* をルーティングと OpenAPI に含めます。 + +同様に、後からルーターに追加された *path operations* も、以前の取り込みを通して見えるようになります。 + +/// warning | 注意 + +`router` を取り込んだ後に、`router.routes` を直接ミューテートするのは避けてください。FastAPI はルーターの取り込みをライブとして扱うため、元のルーターとそのルートはルーティングと OpenAPI 生成の一部のままです。 + +ルートやルーターを追加するには、path operation デコレータや `.include_router()` などのドキュメント化された API を使用してください。 + +`router.routes` は、ルート定義や取り込まれたルーターを含みうる低レベルのルートツリーとして扱い、最終的な *path operations* のフラットな一覧として当てにしないでください。 + +/// diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md index 0f81f4c46..1a150d192 100644 --- a/docs/ja/docs/tutorial/body-multiple-params.md +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -110,7 +110,7 @@ q: str | None = None {* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *} -/// info | 情報 +/// note | 備考 `Body`もまた、後述する `Query` や `Path` などと同様に、すべての追加検証パラメータとメタデータパラメータを持っています。 @@ -125,7 +125,7 @@ Pydanticモデル`Item`の単一の`item`ボディパラメータしかないと しかし、追加のボディパラメータを宣言したときのように、キー `item` を持つ JSON と、その中のモデル内容を期待したい場合は、特別な `Body` パラメータ `embed` を使うことができます: ```Python -item: Item = Body(embed=True) +item: Annotated[Item, Body(embed=True)] ``` 以下において: diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index 5187eb14e..d926189ff 100644 --- a/docs/ja/docs/tutorial/body-nested-models.md +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -1,5 +1,6 @@ # ボディ - ネストされたモデル { #body-nested-models } + **FastAPI** を使用すると、深くネストされた任意のモデルを定義、検証、文書化、使用することができます(Pydanticのおかげです)。 ## リストのフィールド { #list-fields } @@ -135,8 +136,7 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する ] } ``` - -/// info | 情報 +/// note | 備考 `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 @@ -148,7 +148,7 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する {* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} -/// info | 情報 +/// note | 備考 `Offer`は`Item`のリストであり、それらがさらにオプションの`Image`のリストを持っていることに注目してください。 diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index 9f100738c..c26198d3b 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -1,5 +1,6 @@ # リクエストボディ { #request-body } + クライアント(例えばブラウザ)からAPIにデータを送信する必要がある場合、**リクエストボディ**として送信します。 **リクエスト**ボディは、クライアントからAPIへ送信されるデータです。**レスポンス**ボディは、APIがクライアントに送信するデータです。 @@ -8,7 +9,7 @@ APIはほとんどの場合 **レスポンス** ボディを送信する必要 **リクエスト**ボディを宣言するには、[Pydantic](https://docs.pydantic.dev/) モデルを使用し、その強力な機能とメリットをすべて利用します。 -/// info | 情報 +/// note | 備考 データを送信するには、`POST`(より一般的)、`PUT`、`DELETE`、`PATCH` のいずれかを使用すべきです。 diff --git a/docs/ja/docs/tutorial/cookie-param-models.md b/docs/ja/docs/tutorial/cookie-param-models.md index 89ae42438..a90ffdbb7 100644 --- a/docs/ja/docs/tutorial/cookie-param-models.md +++ b/docs/ja/docs/tutorial/cookie-param-models.md @@ -32,7 +32,7 @@ -/// info | 情報 +/// note | 備考 **ブラウザがクッキーを処理し**ていますが、特別な方法で内部的に処理を行っているために、**JavaScript**からは簡単に操作**できない**ことに留意してください。 diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 1e5a0d3cf..894eb9edb 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -24,13 +24,13 @@ /// -/// info | 情報 +/// note | 備考 クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 /// -/// info | 情報 +/// note | 備考 **ブラウザがクッキーを**特殊な方法で裏側で扱うため、**JavaScript** から簡単には触れられないことを念頭に置いてください。 diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index 023e988dc..1a02e1933 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -72,7 +72,7 @@ from myapp import app は実行されません。 -/// info | 情報 +/// note | 備考 より詳しい情報は、[公式Pythonドキュメント](https://docs.python.org/3/library/__main__.html)を参照してください。 @@ -99,7 +99,7 @@ from myapp import app --- -Pycharmを使用する場合、次のことが可能です: +PyCharmを使用する場合、次のことが可能です: * 「実行」メニューをオープン。 * オプション「デバッグ...」を選択。 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 573ccc1f9..56eefa3c8 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 @@ -28,11 +28,11 @@ /// -/// info | 情報 +/// note | 備考 この例では、架空のカスタムヘッダー `X-Key` と `X-Token` を使用しています。 -しかし実際のケースでセキュリティを実装する際は、統合された[Security utilities(次の章)](../security/index.md)を使うことで、より多くの利点を得られます。 +しかし実際のケースでセキュリティを実装する際は、統合された[セキュリティユーティリティ(次の章)](../security/index.md)を使うことで、より多くの利点を得られます。 /// @@ -62,7 +62,7 @@ ## *path operation*のグループに対する依存関係 { #dependencies-for-a-group-of-path-operations } -後で、より大きなアプリケーションを(おそらく複数ファイルで)構造化する方法([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md))について読むときに、*path operation*のグループに対して単一の`dependencies`パラメータを宣言する方法を学びます。 +後で、より大きなアプリケーションを(おそらく複数ファイルで)構造化する方法([より大きなアプリケーション - 複数ファイル](../../tutorial/bigger-applications.md))について読むときに、*path operation*のグループに対して単一の`dependencies`パラメータを宣言する方法を学びます。 ## グローバル依存関係 { #global-dependencies } diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index 83e4f8809..b4ddfe7f8 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -170,7 +170,7 @@ participant tasks as Background tasks end ``` -/// info | 情報 +/// note | 備考 **1つのレスポンス** だけがクライアントに送信されます。それはエラーレスポンスの一つかもしれませんし、*path operation*からのレスポンスかもしれません。 @@ -234,6 +234,7 @@ participant operation as Path Operation `yield`を持つ依存関係は、さまざまなユースケースをカバーし、いくつかの問題を修正するために、時間とともに進化してきました。 FastAPIの異なるバージョンで何が変わったのかを知りたい場合は、上級ガイドの[上級の依存関係 - `yield`、`HTTPException`、`except`、バックグラウンドタスクを持つ依存関係](../../advanced/advanced-dependencies.md#dependencies-with-yield-httpexception-except-and-background-tasks)で詳しく読めます。 + ## コンテキストマネージャ { #context-managers } ### 「コンテキストマネージャ」とは { #what-are-context-managers } diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md index a3cf3e26b..9b8b5ad57 100644 --- a/docs/ja/docs/tutorial/dependencies/index.md +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -51,7 +51,7 @@ そして、これらの値を含む`dict`を返します。 -/// info | 情報 +/// note | 備考 FastAPI はバージョン 0.95.0 で `Annotated` のサポートを追加し(そして推奨し始めました)。 @@ -106,7 +106,7 @@ common_parameters --> read_users この方法では、共有されるコードを一度書き、**FastAPI** が*path operation*のための呼び出しを行います。 -/// check | 確認 +/// tip | 豆知識 特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。 diff --git a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md index fa27781f9..5d6533b11 100644 --- a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md @@ -35,7 +35,7 @@ {* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} -/// info | 情報 +/// note | 備考 *path operation 関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。 diff --git a/docs/ja/docs/tutorial/extra-data-types.md b/docs/ja/docs/tutorial/extra-data-types.md index 1bbfeb71e..b63e3fe1a 100644 --- a/docs/ja/docs/tutorial/extra-data-types.md +++ b/docs/ja/docs/tutorial/extra-data-types.md @@ -1,5 +1,6 @@ # 追加データ型 { #extra-data-types } + 今まで、以下のような一般的なデータ型を使用してきました: * `int` diff --git a/docs/ja/docs/tutorial/extra-models.md b/docs/ja/docs/tutorial/extra-models.md index 20883068c..d9548500e 100644 --- a/docs/ja/docs/tutorial/extra-models.md +++ b/docs/ja/docs/tutorial/extra-models.md @@ -208,4 +208,4 @@ some_variable: PlaneItem | CarItem 複数のPydanticモデルを使用し、ケースごとに自由に継承します。 -エンティティが異なる「状態」を持たなければならない場合は、エンティティごとに単一のデータモデルを持つ必要はありません。`password`、`password_hash`、パスワードなしを含む状態を持つユーザー「エンティティ」の場合と同様です。 +エンティティが異なる「状態」を持たなければならない場合は、エンティティごとに単一のデータモデルを持つ必要はありません。`password`、`password_hash`、パスワードなしを含む状態を持つ**ユーザー**「エンティティ」の場合と同様です。 diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md index 26cb49159..ae0556d15 100644 --- a/docs/ja/docs/tutorial/first-steps.md +++ b/docs/ja/docs/tutorial/first-steps.md @@ -78,7 +78,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) 次に、[http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)にアクセスします。 -先ほどとは異なる、自動生成された対話的APIドキュメントが表示されます([ReDoc](https://github.com/Rebilly/ReDoc)によって提供): +代替の自動生成ドキュメントが表示されます([ReDoc](https://github.com/Rebilly/ReDoc)によって提供): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) @@ -104,7 +104,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) #### OpenAPIおよびJSONスキーマ { #openapi-and-json-schema } -OpenAPIはAPIのためのAPIスキーマを定義します。そして、そのスキーマは**JSONデータスキーマ**の標準規格である**JSON Schema**を利用するAPIによって送受されるデータの定義(または「スキーマ」)を含んでいます。 +OpenAPIはAPIのためのAPIスキーマを定義します。そして、そのスキーマには、JSONデータスキーマの標準である**JSON Schema**を使用して、APIによって送受信されるデータの定義(または「スキーマ」)が含まれます。 #### `openapi.json`を確認 { #check-the-openapi-json } @@ -180,7 +180,7 @@ entrypoint = "backend.main:app" from backend.main import app ``` -### パス付きの`fastapi dev` { #fastapi-dev-with-path } +### パス指定の`fastapi dev`または`--entrypoint` CLIオプション { #fastapi-dev-with-path-or-with-entrypoint-cli-option } `fastapi dev`コマンドにファイルパスを渡すこともでき、使用すべきFastAPIのappオブジェクトを推測します: @@ -188,29 +188,19 @@ from backend.main import app $ fastapi dev main.py ``` -ただし、その場合は毎回`fastapi`コマンドを呼ぶたびに正しいパスを渡すことを覚えておく必要があります。 - -さらに、他のツール(たとえば、[VS Code 拡張機能](../editor-support.md)や[FastAPI Cloud](https://fastapicloud.com))が見つけられない場合があります。そのため、`pyproject.toml`の`entrypoint`を使うことを推奨します。 - -### アプリをデプロイ(任意) { #deploy-your-app-optional } - -任意でFastAPIアプリを[FastAPI Cloud](https://fastapicloud.com)にデプロイできます。まだなら、待機リストに登録してください。 🚀 - -すでに**FastAPI Cloud**アカウントがある場合(待機リストから招待済みの場合😉)、1コマンドでアプリケーションをデプロイできます。 - -デプロイする前に、ログインしていることを確認してください: - -
+または、`fastapi dev`コマンドに`--entrypoint`オプションを渡すこともできます: ```console -$ fastapi login - -You are logged in to FastAPI Cloud 🚀 +$ fastapi dev --entrypoint main:app ``` -
+ただし、その場合は毎回`fastapi`コマンドを呼ぶたびに正しいパスや`entrypoint`を渡すことを覚えておく必要があります。 -その後、アプリをデプロイします: +さらに、他のツール(たとえば、[VS Code 拡張機能](../editor-support.md)や[FastAPI Cloud](https://fastapicloud.com))が見つけられない場合があります。そのため、`pyproject.toml`の`entrypoint`を使うことを推奨します。 + +### アプリをデプロイ(任意) { #deploy-your-app-optional } + +任意でFastAPIアプリを[FastAPI Cloud](https://fastapicloud.com)に1コマンドでデプロイできます。 🚀
@@ -226,6 +216,8 @@ Deploying to FastAPI Cloud...
+CLIはFastAPIアプリケーションを自動検出してクラウドにデプロイします。ログインしていない場合、認証を完了するためにブラウザが開きます。 + 以上です!これで、そのURLでアプリにアクセスできます。 ✨ ## ステップ毎の要約 { #recap-step-by-step } @@ -247,6 +239,7 @@ Deploying to FastAPI Cloud... ### Step 2: `FastAPI`の「インスタンス」を生成 { #step-2-create-a-fastapi-instance } {* ../../docs_src/first_steps/tutorial001_py310.py hl[3] *} + ここで、`app`変数が`FastAPI`クラスの「インスタンス」になります。 これが、すべてのAPIを作成するための主要なポイントになります。 @@ -269,7 +262,7 @@ https://example.com/items/foo /items/foo ``` -/// info | 情報 +/// note | 備考 「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。 @@ -321,7 +314,7 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを * パス `/` * get オペレーション -/// info | `@decorator` 情報 +/// note | `@decorator` 情報 Pythonにおける`@something`シンタックスはデコレータと呼ばれます。 diff --git a/docs/ja/docs/tutorial/frontend.md b/docs/ja/docs/tutorial/frontend.md new file mode 100644 index 000000000..eb23d1e9b --- /dev/null +++ b/docs/ja/docs/tutorial/frontend.md @@ -0,0 +1,139 @@ +# フロントエンド { #frontend } + +`app.frontend()`(または `router.frontend()`)で静的なフロントエンドアプリを配信できます。 + +これは、Vite を使った React、TanStack Router、Astro、Vue、Svelte、Angular、Solid など、静的ファイルを生成するフロントエンドツールで役立ちます。 + +これらのツールでは、通常、次のようなコマンドでフロントエンドをビルドするステップがあります。 + +```bash +npm run build +``` + +これにより、フロントエンドファイルを含む `./dist/` のようなディレクトリが生成されます。 + +`app.frontend()` を使うと、これらのフロントエンドフレームワークが必要とする規約に従って、そのディレクトリを配信できます。 + +**FastAPI** は最初に *path operations* をチェックします。通常のルートに一致しなかった場合にのみフロントエンドファイルがチェックされるため、API には影響しません。 + +## フロントエンドの配信 { #serve-a-frontend } + +たとえば `npm run build` でフロントエンドをビルドした後、生成されたファイルを `dist` などのディレクトリに配置します。 + +プロジェクト構成は次のようになります。 + +```text +. +├── pyproject.toml +├── app +│ ├── __init__.py +│ └── main.py +└── dist + ├── index.html + └── assets + └── app.js +``` + +そして `app.frontend()` で配信します。 + +{* ../../docs_src/frontend/tutorial001_py310.py hl[5] *} + +これにより、`/assets/app.js` へのリクエストで `dist/assets/app.js` を配信できます。 + +**FastAPI** の *path operation* もある場合は、*path operation* が優先されます。 + +## クライアントサイドルーティング { #client-side-routing } + +**single-page apps**(SPA)を含む多くのフロントエンドアプリは、クライアントサイドルーティングを使います。`/dashboard/settings` のようなパスは実際のファイルではなく、フレームワークが処理するものかもしれません。 + +そのため、その URL に直接アクセスした場合(アプリ内で遷移するのではなく)、バックエンドは `index.html` からフロントエンドアプリを配信し、フロントエンドフレームワークがクライアントサイドルーティングを処理できるようにする必要があります。 + +そのためには、`fallback="index.html"` を使います。 + +{* ../../docs_src/frontend/tutorial002_py310.py hl[5] *} + +**FastAPI** は、このフォールバックをブラウザのナビゲーションに見える `GET` および `HEAD` リクエストにのみ使用します。JavaScript、CSS、画像などの存在しないファイルは引き続き `404` を返します。 + +`POST` や `PUT` など、他のメソッドのリクエストがフロントエンドのフォールバックにのみ一致するパスへ送られた場合も、`404` を返します。通常の **FastAPI** の *path operations* は、フロントエンドのルートよりも引き続き高い優先順位を持ちます。 + +/// tip | 豆知識 + +デフォルトでは、`fallback` の値は `fallback="auto"` です。ほとんどの場合、`fallback` を指定する必要はありません。詳細は以下を参照してください。 + +/// + +これは、TanStack Router を使った React、Vue、Angular、SvelteKit、Solid など、クライアントサイドルーティングを使う多くのフロントエンドアプリで望まれる動作です。 + +## カスタム 404 ページ { #custom-404-page } + +存在しないフロントエンドパスに対して、静的な `404.html` ページを配信することもできます。 + +{* ../../docs_src/frontend/tutorial003_py310.py hl[5] *} + +そのレスポンスはステータスコード `404` を保持します。 + +この場合、**FastAPI** は存在しないフロントエンドパスに対して `index.html` を配信しません。代わりに `404.html` ファイルを返します。 + +/// tip | 豆知識 + +デフォルトでは、`fallback` の値は `fallback="auto"` です。これにより、`404.html` ファイルが見つかった場合、自動的にフォールバックとして使われます。 + +そのため、通常は `fallback` 引数を省略できます。 + +/// + +これは、Astro のように各ページの静的 HTML ファイルを生成するフロントエンドツールで役立ちます。 + +## 自動フォールバック { #fallback-auto } + +デフォルトでは、`app.frontend()` は `fallback="auto"` を使います。 + +フロントエンドディレクトリに `404.html` ファイルがある場合、存在しないフロントエンドパスはそのファイルをステータスコード `404` で配信します。 + +そうでない場合、`index.html` ファイルがあれば、存在しないブラウザナビゲーションのパスは `index.html` を配信します。これは、クライアントサイドルーティングを使う多くのフロントエンドアプリが期待する動作です。 + +そのため、ほとんどの場合、`fallback` 引数を指定せずに `app.frontend("/", directory="dist")` を使用できます。 + +{* ../../docs_src/frontend/tutorial001_py310.py hl[5] *} + +## フォールバックの無効化 { #disable-fallback } + +存在しないフロントエンドパスに対してフォールバックファイルを配信したくない場合は、`fallback=None` を使います。 + +{* ../../docs_src/frontend/tutorial005_py310.py hl[5] *} + +すると、存在しないフロントエンドパスは通常の `404` を返します。 + +## ディレクトリのチェック { #check-directory } + +デフォルトでは、`app.frontend()` はアプリ作成時にディレクトリが存在することをチェックします。 + +これにより、設定エラーを早期に検出できます。たとえば、フロントエンドのビルド出力ディレクトリが存在しない場合、**FastAPI** は起動時にエラーを発生させます。 + +アプリオブジェクトの作成後に別のビルドステップなどでフロントエンドファイルが作成される場合は、`check_dir=False` を設定します。 + +{* ../../docs_src/frontend/tutorial006_py310.py hl[5] *} + +`check_dir=False` を指定すると、**FastAPI** はアプリ作成時にディレクトリをチェックしません。リクエストが処理される時点で設定されたディレクトリがまだ存在しない場合、**FastAPI** はその時点でエラーを発生させます。 + +## `APIRouter` での使用 { #use-it-with-apirouter } + +フロントエンドファイルを `APIRouter` に追加し、prefix 付きで include することもできます。 + +{* ../../docs_src/frontend/tutorial004_py310.py hl[6,7] *} + +この例では、フロントエンドのパスは `/app` 配下で配信されます。 + +他の router 内のものを含め、アプリ内の通常の *path operations* は引き続き優先されます。 + +## 依存関係とミドルウェア { #dependencies-and-middleware } + +フロントエンドのレスポンスは通常の **FastAPI** アプリケーション内で実行されるため、HTTP ミドルウェアが適用されます。 + +アプリ、`APIRouter`、および `include_router()` からの依存関係もフロントエンドのレスポンスに適用されます。これは、cookie 認証などでフロントエンドを保護する場合に役立ちます。 + +## 静的ビルド出力のみ { #static-build-output-only } + +`app.frontend()` は、フロントエンドのビルドで既に生成されたファイルを配信します。 + +server-side rendering は実行しません。これは静的ファイルを生成するフロントエンドフレームワーク向けであり、各リクエストごとにサーバー上で動的レンダリングを必要とするフレームワーク向けではありません。 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md index 8d0190cb0..491b72da2 100644 --- a/docs/ja/docs/tutorial/handling-errors.md +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -1,5 +1,6 @@ # エラーハンドリング { #handling-errors } + APIを使用しているクライアントにエラーを通知する必要がある状況はたくさんあります。 このクライアントは、フロントエンドを持つブラウザ、誰かのコード、IoTデバイスなどが考えられます。 diff --git a/docs/ja/docs/tutorial/header-params.md b/docs/ja/docs/tutorial/header-params.md index 1916baf61..c55fbc02d 100644 --- a/docs/ja/docs/tutorial/header-params.md +++ b/docs/ja/docs/tutorial/header-params.md @@ -24,7 +24,7 @@ /// -/// info | 情報 +/// note ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。 @@ -48,7 +48,7 @@ {* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} -/// warning | 注意 +/// warning `convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。 diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md index 8182c92ae..42b0eb523 100644 --- a/docs/ja/docs/tutorial/index.md +++ b/docs/ja/docs/tutorial/index.md @@ -1,5 +1,6 @@ # チュートリアル - ユーザーガイド { #tutorial-user-guide } + このチュートリアルでは、**FastAPI**のほとんどの機能を使う方法を段階的に紹介します。 各セクションは前のセクションを踏まえた内容になっています。しかし、トピックごとに分割されているので、特定のAPIのニーズを満たすために、任意の特定のトピックに直接進めるようになっています。 diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md index 6802e6c9a..0f5f0cb6c 100644 --- a/docs/ja/docs/tutorial/metadata.md +++ b/docs/ja/docs/tutorial/metadata.md @@ -11,10 +11,10 @@ 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` です。 | +| `version` | `str` | APIのバージョンです。これはOpenAPIのバージョンではなく、あなた自身のアプリケーションのバージョンです。たとえば `2.5.0` です。 | | `terms_of_service` | `str` | APIの利用規約へのURLです。指定する場合、URLである必要があります。 | -| `contact` | `dict` | 公開されるAPIの連絡先情報です。複数のフィールドを含められます。
contact fields
ParameterTypeDescription
namestr連絡先の個人/組織を識別する名前です。
urlstr連絡先情報を指すURLです。URL形式である必要があります。
emailstr連絡先の個人/組織のメールアドレスです。メールアドレス形式である必要があります。
| -| `license_info` | `dict` | 公開されるAPIのライセンス情報です。複数のフィールドを含められます。
license_info fields
ParameterTypeDescription
namestr必須license_info が設定されている場合)。APIに使用されるライセンス名です。
identifierstrAPIの [SPDX](https://spdx.org/licenses/) ライセンス式です。identifier フィールドは url フィールドと同時に指定できません。 OpenAPI 3.1.0、FastAPI 0.99.0 以降で利用できます。
urlstrAPIに使用されるライセンスへのURLです。URL形式である必要があります。
| +| `contact` | `dict` | 公開されるAPIの連絡先情報です。複数のフィールドを含められます。
contact のフィールド
パラメータ説明
namestr連絡先の個人/組織を識別する名前です。
urlstr連絡先情報を指すURLです。URL形式である必要があります。
emailstr連絡先の個人/組織のメールアドレスです。メールアドレス形式である必要があります。
| +| `license_info` | `dict` | 公開されるAPIのライセンス情報です。複数のフィールドを含められます。
license_info のフィールド
パラメータ説明
namestr必須license_info が設定されている場合)。APIに使用されるライセンス名です。
identifierstrAPIの [SPDX](https://spdx.org/licenses/) ライセンス式です。identifier フィールドは url フィールドと同時に指定できません。 OpenAPI 3.1.0、FastAPI 0.99.0 以降で利用できます。
urlstrAPIに使用されるライセンスへのURLです。URL形式である必要があります。
| 以下のように設定できます: @@ -74,7 +74,7 @@ OpenAPI 3.1.0 および FastAPI 0.99.0 以降では、`license_info` を `url` {* ../../docs_src/metadata/tutorial004_py310.py hl[21,26] *} -/// info | 情報 +/// note | 備考 タグの詳細は [Path Operation の設定](path-operation-configuration.md#tags) を参照してください。 diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md index 25a2783ea..05bf9208e 100644 --- a/docs/ja/docs/tutorial/path-operation-configuration.md +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -1,5 +1,6 @@ # Path Operationの設定 { #path-operation-configuration } + *path operationデコレータ*を設定するためのパラメータがいくつかあります。 /// warning | 注意 @@ -72,13 +73,13 @@ docstringに[Markdown](https://en.wikipedia.org/wiki/Markdown)を記述すれば {* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[18] *} -/// info | 情報 +/// note | 備考 `response_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。 /// -/// check | 確認 +/// tip | 豆知識 OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。 diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md index 55930eece..1e36e7dd1 100644 --- a/docs/ja/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -8,7 +8,7 @@ {* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} -/// info | 情報 +/// note | 備考 FastAPI はバージョン 0.95.0 で`Annotated`のサポートを追加し(そして推奨し始めました)。 @@ -131,7 +131,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `lt`: `l`ess `t`han * `le`: `l`ess than or `e`qual -/// info | 情報 +/// note | 備考 `Query`、`Path`、および後で見る他のクラスは、共通の`Param`クラスのサブクラスです。 diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index 8556b1c37..ec47cbe7a 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -20,7 +20,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー ここでは、 `item_id` は `int` として宣言されています。 -/// check | 確認 +/// tip | 豆知識 これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。 @@ -34,7 +34,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {"item_id":3} ``` -/// check | 確認 +/// tip | 豆知識 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。 @@ -66,7 +66,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー [http://127.0.0.1:8000/items/4.2](http://127.0.0.1:8000/items/4.2) で見られるように、`int` のかわりに `float` が与えられた場合にも同様なエラーが表示されます。 -/// check | 確認 +/// tip | 豆知識 したがって、同じPythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 @@ -82,7 +82,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー -/// check | 確認 +/// tip | 豆知識 繰り返しになりますが、同じPython型宣言を使用するだけで、**FastAPI**は対話的なドキュメントを自動的に生成します(Swagger UIを統合)。 diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index d34059801..38d2b5c68 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -24,12 +24,12 @@ FastAPIは、 `q` はデフォルト値が `= None` であるため、必須で そのために、まずは以下をインポートします: -* `fastapi` から `Query` -* `typing` から `Annotated` +- `fastapi` から `Query` +- `typing` から `Annotated` {* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[1,3] *} -/// info | 情報 +/// note | 備考 FastAPI はバージョン 0.95.0 で `Annotated` のサポートを追加し(推奨し始め)ました。 @@ -41,7 +41,7 @@ FastAPI はバージョン 0.95.0 で `Annotated` のサポートを追加し( ## `q` パラメータの型で `Annotated` を使う { #use-annotated-in-the-type-for-the-q-parameter } -以前、[Python Types Intro](../python-types.md#type-hints-with-metadata-annotations) で `Annotated` を使ってパラメータにメタデータを追加できると説明したことを覚えていますか? +以前、[Python 型入門](../python-types.md#type-hints-with-metadata-annotations) で `Annotated` を使ってパラメータにメタデータを追加できると説明したことを覚えていますか? いよいよ FastAPI で使うときです。 🚀 @@ -79,9 +79,9 @@ q: Annotated[str | None] = None FastAPI は次を行います: -* 最大長が 50 文字であることを確かめるようデータを **検証** する -* データが有効でないときに、クライアントに **明確なエラー** を表示する -* OpenAPI スキーマの *path operation* にパラメータを **ドキュメント化** する(その結果、**自動ドキュメント UI** に表示されます) +- 最大長が 50 文字であることを確かめるようデータを **検証** する +- データが有効でないときに、クライアントに **明確なエラー** を表示する +- OpenAPI スキーマの *path operation* にパラメータを **ドキュメント化** する(その結果、**自動ドキュメント UI** に表示されます) ## 代替(古い方法): デフォルト値としての `Query` { #alternative-old-query-as-the-default-value } @@ -174,9 +174,9 @@ FastAPI なしで同じ関数を **別の場所** から **呼び出しても** この特定の正規表現パターンは受け取ったパラメータの値をチェックします: -* `^`: は、これ以降の文字で始まり、これより以前には文字はありません。 -* `fixedquery`: は、正確な`fixedquery`を持っています. -* `$`: で終わる場合、`fixedquery`以降には文字はありません. +- `^`: は、これ以降の文字で始まり、これより以前には文字はありません。 +- `fixedquery`: は、正確な`fixedquery`を持っています. +- `$`: で終わる場合、`fixedquery`以降には文字はありません. もしこれらすべての **「正規表現」** のアイデアについて迷っていても、心配しないでください。多くの人にとって難しい話題です。正規表現を必要としなくても、まだ、多くのことができます。 @@ -242,7 +242,7 @@ q: Annotated[str | None, Query(min_length=3)] = None http://localhost:8000/items/?q=foo&q=bar ``` -*path operation function* 内の *function parameter* `q` で、複数の `q` *query parameters'* 値(`foo` と `bar`)を Python の `list` として受け取ります。 +*path operation function* 内の *function parameter* `q` で、複数の `q` *クエリパラメータ*の値(`foo` と `bar`)を Python の `list` として受け取ります。 そのため、このURLのレスポンスは以下のようになります: @@ -382,7 +382,7 @@ Pydantic には [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/va {* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *} -/// info | 情報 +/// note | 備考 これは Pydantic バージョン 2 以上で利用できます。 😎 @@ -432,16 +432,16 @@ Pydantic には [`BeforeValidator`](https://docs.pydantic.dev/latest/concepts/va 一般的なバリデーションとメタデータ: -* `alias` -* `title` -* `description` -* `deprecated` +- `alias` +- `title` +- `description` +- `deprecated` 文字列に固有のバリデーション: -* `min_length` -* `max_length` -* `pattern` +- `min_length` +- `max_length` +- `pattern` `AfterValidator` を使ったカスタムバリデーション。 diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 51e4eb944..2bca43a95 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -1,5 +1,6 @@ # クエリパラメータ { #query-parameters } + パスパラメータではない関数パラメータを宣言すると、それらは自動的に「クエリ」パラメータとして解釈されます。 {* ../../docs_src/query_params/tutorial001_py310.py hl[9] *} @@ -65,7 +66,7 @@ http://127.0.0.1:8000/items/?skip=20 この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 -/// check | 確認 +/// tip | 豆知識 パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 diff --git a/docs/ja/docs/tutorial/request-files.md b/docs/ja/docs/tutorial/request-files.md index 30a494afb..f4bd2314b 100644 --- a/docs/ja/docs/tutorial/request-files.md +++ b/docs/ja/docs/tutorial/request-files.md @@ -1,8 +1,9 @@ # リクエストファイル { #request-files } + `File` を使って、クライアントがアップロードするファイルを定義できます。 -/// info | 情報 +/// note | 備考 アップロードされたファイルを受け取るには、まず [`python-multipart`](https://github.com/Kludex/python-multipart) をインストールします。 @@ -28,7 +29,7 @@ $ pip install python-multipart {* ../../docs_src/request_files/tutorial001_an_py310.py hl[9] *} -/// info | 情報 +/// note | 備考 `File` は `Form` を直接継承したクラスです。 diff --git a/docs/ja/docs/tutorial/request-form-models.md b/docs/ja/docs/tutorial/request-form-models.md index 62aa9e298..6a71c149d 100644 --- a/docs/ja/docs/tutorial/request-form-models.md +++ b/docs/ja/docs/tutorial/request-form-models.md @@ -2,7 +2,7 @@ FastAPI では、フォームフィールドを宣言するために **Pydantic モデル**を使用できます。 -/// info | 情報 +/// note | 備考 フォームを使うには、まず [`python-multipart`](https://github.com/Kludex/python-multipart) をインストールします。 diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md index 651f07ff0..4865f29ae 100644 --- a/docs/ja/docs/tutorial/request-forms-and-files.md +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -2,7 +2,7 @@ `File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。 -/// info | 情報 +/// note | 備考 アップロードされたファイルやフォームデータを受信するには、まず[`python-multipart`](https://github.com/Kludex/python-multipart)をインストールします。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index c6b2a921a..0478a5439 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -2,7 +2,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。 -/// info | 情報 +/// note | 備考 フォームを使うためには、まず[`python-multipart`](https://github.com/Kludex/python-multipart)をインストールします。 @@ -32,7 +32,7 @@ $ pip install python-multipart `Form`では`Body`(および`Query`や`Path`、`Cookie`)と同じ設定を宣言することができます。これには、バリデーション、例、エイリアス(例えば`username`の代わりに`user-name`)などが含まれます。 -/// info | 情報 +/// note | 備考 `Form`は`Body`を直接継承するクラスです。 @@ -56,7 +56,7 @@ HTMLフォーム(`
`)がサーバにデータを送信する方 しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。 -これらのエンコーディングやフォームフィールドの詳細については、[MDN の `POST` ウェブドキュメント](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)を参照してください。 +これらのエンコーディングやフォームフィールドの詳細については、[MDN の `POST` のウェブドキュメント](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST)を参照してください。 /// @@ -70,4 +70,4 @@ HTMLフォーム(`
`)がサーバにデータを送信する方 ## まとめ { #recap } -フォームデータの入力パラメータを宣言するには、`Form`を使用する。 +フォームデータの入力パラメータを宣言するには、`Form`を使用します。 diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index b4024e0a0..4b38e6de9 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -72,7 +72,7 @@ FastAPIはこの `response_model` を使って、データのドキュメント {* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} -/// info | 情報 +/// note | 備考 `EmailStr` を使用するには、最初に [`email-validator`](https://github.com/JoshData/python-email-validator) をインストールしてください。 @@ -251,7 +251,7 @@ Pydanticフィールドとして有効ではないものを返し、ツール( } ``` -/// info | 情報 +/// note | 備考 以下も使用できます: diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md index 9237ac784..e4239e11a 100644 --- a/docs/ja/docs/tutorial/response-status-code.md +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -1,5 +1,6 @@ # レスポンスステータスコード { #response-status-code } + レスポンスモデルを指定するのと同じ方法で、レスポンスに使用されるHTTPステータスコードを以下の*path operations*のいずれかの`status_code`パラメータで宣言することもできます。 * `@app.get()` @@ -18,7 +19,7 @@ `status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。 -/// info | 情報 +/// note | 備考 `status_code`は代わりに、Pythonの[`http.HTTPStatus`](https://docs.python.org/3/library/http.html#http.HTTPStatus)のように、`IntEnum`を受け取ることもできます。 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index 87ee85f40..e44e2471d 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -1,5 +1,6 @@ # リクエストのExampleデータの宣言 { #declare-request-example-data } + アプリが受け取れるデータの例を宣言できます。 ここでは、それを行ういくつかの方法を紹介します。 @@ -24,7 +25,7 @@ /// -/// info | 情報 +/// note | 備考 OpenAPI 3.1.0(FastAPI 0.99.0以降で使用)では、**JSON Schema**標準の一部である`examples`がサポートされました。 @@ -155,7 +156,7 @@ OpenAPIは、仕様の他の部分にも`example`と`examples`フィールドを * `File()` * `Form()` -/// info | 情報 +/// note | 備考 この古いOpenAPI固有の`examples`パラメータは、FastAPI `0.103.0`以降は`openapi_examples`になりました。 @@ -171,7 +172,7 @@ OpenAPIは、仕様の他の部分にも`example`と`examples`フィールドを JSON Schemaのこの新しい`examples`フィールドは、OpenAPIの他の場所(上で説明)にあるような追加メタデータを持つdictではなく、**単なる例の`list`**です。 -/// info | 情報 +/// note | 備考 OpenAPI 3.1.0がこのJSON Schemaとの新しいよりシンプルな統合とともにリリースされた後も、しばらくの間、自動ドキュメントを提供するツールであるSwagger UIはOpenAPI 3.1.0をサポートしていませんでした(バージョン5.0.0からサポートされています🎉)。 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index e678ebce1..e5d7c58b5 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -24,7 +24,7 @@ ## 実行 { #run-it } -/// info | 情報 +/// note | 備考 [`python-multipart`](https://github.com/Kludex/python-multipart) パッケージは、`pip install "fastapi[standard]"` コマンドを実行すると **FastAPI** と一緒に自動的にインストールされます。 @@ -60,7 +60,7 @@ $ fastapi dev -/// check | Authorizeボタン! +/// tip | Authorizeボタン! すでにピカピカの新しい「Authorize」ボタンがあります。 @@ -109,7 +109,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー * ユーザーがフロントエンドでクリックして、フロントエンドのWebアプリの別のセクションに移動します。 * フロントエンドはAPIからさらにデータを取得する必要があります。 * しかし、特定のエンドポイントの認証が必要です。 - * したがって、APIで認証するため、HTTPヘッダー`Authorization`に`Bearer`の文字列とトークンを加えた値を送信します。 + * したがって、APIで認証するため、HTTPヘッダー`Authorization`に`Bearer `の文字列とトークンを加えた値を送信します。 * トークンに`foobar`が含まれている場合、`Authorization`ヘッダーの内容は次のようになります: `Bearer foobar`。 ## **FastAPI**の`OAuth2PasswordBearer` { #fastapis-oauth2passwordbearer } @@ -118,7 +118,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー この例では、**Bearer**トークンを使用して**OAuth2**を**Password**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。 -/// info | 情報 +/// note | 備考 「bearer」トークンが、唯一の選択肢ではありません。 @@ -148,7 +148,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー 実際の path operation もすぐに作ります。 -/// info | 情報 +/// note | 備考 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`tokenUrl`ではなく`token_url`であることを気に入らないかもしれません。 @@ -176,9 +176,9 @@ oauth2_scheme(some, parameters) **FastAPI**は、この依存関係を使用してOpenAPIスキーマ (および自動APIドキュメント) で「セキュリティスキーム」を定義できることを知っています。 -/// info | 技術詳細 +/// note | 技術詳細 -**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に統合する方法を知ることができます。 diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md index 60378fd98..f8e4295bf 100644 --- a/docs/ja/docs/tutorial/security/get-current-user.md +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -14,7 +14,7 @@ ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます: -{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *} +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:16] *} ## 依存関係 `get_current_user` を作成 { #create-a-get-current-user-dependency } @@ -52,7 +52,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ /// -/// check | 確認 +/// tip | 豆知識 依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の「dependables」)を持つことができます。 diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index 9c527121e..40cefad9d 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -1,6 +1,6 @@ # パスワード(およびハッシュ化)によるOAuth2、JWTトークンによるBearer { #oauth2-with-password-and-hashing-bearer-with-jwt-tokens } -これでセキュリティの流れが全てわかったので、JWTトークンと安全なパスワードのハッシュ化を使用して、実際にアプリケーションを安全にしてみましょう。 +これでセキュリティの流れが全てわかったので、JWTトークンと安全なパスワードのハッシュ化を使用して、実際にアプリケーションを安全にしてみましょう。 このコードは、アプリケーションで実際に使用したり、パスワードハッシュをデータベースに保存するといった用途に利用できます。 @@ -42,11 +42,11 @@ $ pip install pyjwt -/// info | 情報 +/// note | 備考 RSAやECDSAのようなデジタル署名アルゴリズムを使用する予定がある場合は、cryptographyライブラリの依存関係`pyjwt[crypto]`をインストールしてください。 -詳細は[PyJWT Installation docs](https://pyjwt.readthedocs.io/en/latest/installation.html)で確認できます。 +詳細は[PyJWT インストールに関するドキュメント](https://pyjwt.readthedocs.io/en/latest/installation.html)で確認できます。 /// @@ -120,7 +120,7 @@ pwdlibはbcryptハッシュアルゴリズムもサポートしていますが `authenticate_user` がデータベースに存在しないユーザー名で呼び出された場合でも、ダミーのハッシュを使って `verify_password` を実行します。 -これにより、ユーザー名が有効かどうかに関わらずエンドポイントの応答時間がおおよそ同じになり、既存のユーザー名を列挙するために悪用されうる「タイミング攻撃」を防止できます。 +これにより、ユーザー名が有効かどうかに関わらずエンドポイントの応答時間がおおよそ同じになり、既存のユーザー名を列挙するために悪用されうる**タイミング攻撃**を防止できます。 /// note | 備考 @@ -213,9 +213,9 @@ IDの衝突を回避するために、ユーザーのJWTトークンを作成す Username: `johndoe` Password: `secret` -/// check | 確認 +/// tip | 豆知識 -コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 +コードのどこにも平文のパスワード「`secret`」はなく、ハッシュ化されたものしかないことを確認してください。 /// diff --git a/docs/ja/docs/tutorial/security/simple-oauth2.md b/docs/ja/docs/tutorial/security/simple-oauth2.md index 842cd02e5..84f6101b7 100644 --- a/docs/ja/docs/tutorial/security/simple-oauth2.md +++ b/docs/ja/docs/tutorial/security/simple-oauth2.md @@ -14,7 +14,7 @@ OAuth2 では、「password flow」(ここで使用するフロー)を使う また、データベースのモデルでは任意の別名を使って構いません。 -しかし、ログイン用の path operation では、仕様との互換性を保つ(たとえば組み込みのAPIドキュメントシステムを使えるようにする)ために、これらの名前を使う必要があります。 +しかし、ログイン用の *path operation* では、仕様との互換性を保つ(たとえば組み込みのAPIドキュメントシステムを使えるようにする)ために、これらの名前を使う必要があります。 また、仕様では `username` と `password` はフォームデータとして送らなければならない(つまり、ここではJSONは使わない)ことも定められています。 @@ -32,7 +32,7 @@ OAuth2 では、「password flow」(ここで使用するフロー)を使う - `instagram_basic` は Facebook / Instagram で使われます。 - `https://www.googleapis.com/auth/drive` は Google で使われます。 -/// info | 情報 +/// note | 備考 OAuth2 における「スコープ」は、要求される特定の権限を表す単なる文字列です。 @@ -50,7 +50,7 @@ OAuth2 にとっては単なる文字列です。 ### `OAuth2PasswordRequestForm` { #oauth2passwordrequestform } -まず、`OAuth2PasswordRequestForm` をインポートし、`/token` の path operation に `Depends` で依存関係として使います: +まず、`OAuth2PasswordRequestForm` をインポートし、`/token` の *path operation* に `Depends` で依存関係として使います: {* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} @@ -72,7 +72,7 @@ OAuth2 の仕様では、固定値 `password` を持つフィールド `grant_ty - オプションの `client_id`(この例では不要) - オプションの `client_secret`(この例では不要) -/// info | 情報 +/// note | 備考 `OAuth2PasswordRequestForm` は、`OAuth2PasswordBearer` のように **FastAPI** にとって特別なクラスではありません。 @@ -132,7 +132,7 @@ OAuth2 の仕様では、固定値 `password` を持つフィールド `grant_ty `UserInDB(**user_dict)` は次を意味します: -`user_dict` のキーと値を、そのままキーワード引数として渡します。つまり次と同等です: +*`user_dict` のキーと値を、そのままキーワード引数として渡します。つまり次と同等です:* ```Python UserInDB( @@ -144,9 +144,9 @@ UserInDB( ) ``` -/// info | 情報 +/// note | 備考 -`**user_dict` のより完全な解説は、[**追加モデル**のドキュメント](../extra-models.md#about-user-in-dict)を参照してください。 +`**user_dict` のより完全な解説は、[**追加モデル**のドキュメント](../extra-models.md#about-user-in-model-dump)を参照してください。 /// @@ -188,7 +188,7 @@ UserInDB( アクティブなユーザーの場合にのみ `current_user` を取得したいとします。 -そこで、`get_current_active_user` を依存関係として利用する追加の依存関係 `get_current_active_user` を作成します。 +そこで、今度は `get_current_user` を依存関係として利用する追加の依存関係 `get_current_active_user` を作成します。 これら2つの依存関係は、ユーザーが存在しない、または非アクティブである場合に、HTTPエラーを返すだけです。 @@ -196,7 +196,7 @@ UserInDB( {* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} -/// info | 情報 +/// note | 備考 ここで返している値が `Bearer` の追加ヘッダー `WWW-Authenticate` も仕様の一部です。 @@ -236,7 +236,7 @@ Password: `secret` ### 自分のユーザーデータを取得 { #get-your-own-user-data } -`GET` の path `/users/me` を使います。 +今度は path `/users/me` で operation `GET` を使います。 次のようなユーザーデータが取得できます: @@ -268,7 +268,7 @@ User: `alice` Password: `secret2` -そして `GET` の path `/users/me` を使います。 +そして path `/users/me` で operation `GET` を使ってみます。 次のような「Inactive user」エラーになります: @@ -284,6 +284,6 @@ Password: `secret2` これらの道具を使えば、任意のデータベース、任意のユーザー/データモデルと互換性のあるセキュリティシステムを構築できます。 -ただし、実際にはまだ「安全」ではありません。 +唯一欠けている点は、実際にはまだ「安全」ではないことです。 次の章では、安全なパスワードハッシュライブラリと JWT トークンの使い方を見ていきます。 diff --git a/docs/ja/docs/tutorial/server-sent-events.md b/docs/ja/docs/tutorial/server-sent-events.md index d8168cef3..1019f806e 100644 --- a/docs/ja/docs/tutorial/server-sent-events.md +++ b/docs/ja/docs/tutorial/server-sent-events.md @@ -4,7 +4,7 @@ これは[JSON Lines のストリーミング](stream-json-lines.md)に似ていますが、`text/event-stream` フォーマットを使用します。これはブラウザがネイティブに [`EventSource` API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) でサポートしています。 -/// info | 情報 +/// note FastAPI 0.135.0 で追加されました。 @@ -27,7 +27,7 @@ data: {"name": "Plumbus", "price": 32.99} SSE は、AI チャットのストリーミング、ライブ通知、ログやオブザビリティなど、サーバーがクライアントへ更新をプッシュする用途で一般的に使われます。 -/// tip | 豆知識 +/// tip バイナリデータ(例: 動画や音声)をストリーミングしたい場合は、上級ガイド [データのストリーミング](../advanced/stream-data.md) を参照してください。 @@ -47,7 +47,7 @@ yield された各アイテムは JSON にエンコードされ、SSE イベン {* ../../docs_src/server_sent_events/tutorial001_py310.py ln[1:25] hl[10:12,23] *} -/// tip | 豆知識 +/// tip Pydantic が**Rust** 側でシリアライズを行うため、戻り値の型を宣言しない場合に比べて大幅に**高性能**になります。 @@ -81,13 +81,13 @@ Pydantic が**Rust** 側でシリアライズを行うため、戻り値の型 ## 生データ { #raw-data } -JSON エンコードせずにデータを送る必要がある場合は、`data` の代わりに `raw_data` を使用します。 +JSON エンコードせずにデータを送る必要がある場合は、`raw_data` を使用します。 -これは、整形済みテキスト、ログ行、または `[DONE]` のような特別な "センチネル" 値を送るのに有用です。 +これは、整形済みテキスト、ログ行、または 「センチネル」 といった特別な値(例: `[DONE]`)を送るのに有用です。 {* ../../docs_src/server_sent_events/tutorial003_py310.py hl[17] *} -/// note | 備考 +/// note `data` と `raw_data` は相互排他的です。各 `ServerSentEvent` ではどちらか一方しか設定できません。 diff --git a/docs/ja/docs/tutorial/sql-databases.md b/docs/ja/docs/tutorial/sql-databases.md index 13c71fdb2..190eedbbb 100644 --- a/docs/ja/docs/tutorial/sql-databases.md +++ b/docs/ja/docs/tutorial/sql-databases.md @@ -1,5 +1,6 @@ # SQL(リレーショナル)データベース { #sql-relational-databases } + FastAPI は SQL(リレーショナル)データベースの使用を必須にはしません。必要であれば、任意のデータベースを使用できます。 ここでは [SQLModel](https://sqlmodel.tiangolo.com/) を使った例を見ていきます。 diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index 81f281c2e..fd0d47e9c 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -2,6 +2,14 @@ `StaticFiles` を使用して、ディレクトリから静的ファイルを自動的に提供できます。 +/// tip | 豆知識 + +フロントエンドをホストする必要がある場合は、代わりに `app.frontend()` を使用してください。詳しくは [フロントエンド](frontend.md) を読んでください。 + +`app.frontend()` は内部で `StaticFiles` を使用しており、client-side routing の処理など、フロントエンド向けの追加の利点がいくつかあります。 + +/// + ## `StaticFiles` の使用 { #use-staticfiles } * `StaticFiles` をインポート。 diff --git a/docs/ja/docs/tutorial/stream-json-lines.md b/docs/ja/docs/tutorial/stream-json-lines.md index a247234e2..1f7af2f68 100644 --- a/docs/ja/docs/tutorial/stream-json-lines.md +++ b/docs/ja/docs/tutorial/stream-json-lines.md @@ -2,7 +2,7 @@ データのシーケンスを**「ストリーム」**で送りたい場合、**JSON Lines** を使って実現できます。 -/// info | 情報 +/// note | 備考 FastAPI 0.134.0 で追加されました。 @@ -48,7 +48,7 @@ sequenceDiagram これは JSON 配列(Python の list に相当)にとてもよく似ていますが、`[]` で囲まず、アイテム間の `,` もありません。その代わりに、**1 行に 1 つの JSON オブジェクト**で、改行文字で区切られます。 -/// info | 情報 +/// note | 備考 重要な点は、クライアントが前の行を消費している間に、アプリ側は次の行を順次生成して送れることです。 diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index 0277d73b7..e82fc261e 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -8,7 +8,7 @@ ## `TestClient` を使用 { #using-testclient } -/// info +/// note | 備考 `TestClient` を使用するには、まず [`httpx`](https://www.python-httpx.org) をインストールします。 @@ -22,7 +22,7 @@ $ pip install httpx `TestClient` をインポートします。 -`TestClient` を作成し、**FastAPI** に渡します。 +**FastAPI** アプリケーションを渡して `TestClient` を作成します。 `test_` から始まる名前の関数を作成します (これは `pytest` の標準的なコンベンションです)。 @@ -32,7 +32,7 @@ $ pip install httpx {* ../../docs_src/app_testing/tutorial001_py310.py hl[2,12,15:18] *} -/// tip +/// tip | 豆知識 テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 @@ -50,9 +50,9 @@ $ pip install httpx /// -/// tip +/// tip | 豆知識 -FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md) を参照してください。 +FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[非同期テスト](../advanced/async-tests.md) を参照してください。 /// @@ -64,7 +64,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ ### **FastAPI** アプリファイル { #fastapi-app-file } -[Bigger Applications](bigger-applications.md) で説明されている、次のようなファイル構成があるとします: +[大規模なアプリケーション](bigger-applications.md) で説明されている、次のようなファイル構成があるとします: ``` . @@ -113,7 +113,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ │   └── test_main.py ``` -ここで、**FastAPI** アプリがある `main.py` ファイルには、他の path operation があります。 +ここで、**FastAPI** アプリがある `main.py` ファイルには、他の **path operations** がいくつかあります。 エラーを返す可能性のある `GET` オペレーションがあります。 @@ -144,7 +144,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ (`httpx` または `TestClient` を使用して) バックエンドにデータを渡す方法の詳細は、[HTTPXのドキュメント](https://www.python-httpx.org)を確認してください。 -/// info +/// note | 備考 `TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 diff --git a/docs/ja/docs/virtual-environments.md b/docs/ja/docs/virtual-environments.md index 21b7cd472..19325fa1d 100644 --- a/docs/ja/docs/virtual-environments.md +++ b/docs/ja/docs/virtual-environments.md @@ -2,7 +2,7 @@ Pythonプロジェクトの作業では、**仮想環境**(または類似の仕組み)を使用し、プロジェクトごとにインストールするパッケージを分離するべきでしょう。 -/// info | 情報 +/// note | 備考 もし、仮想環境の概要や作成方法、使用方法について既にご存知なら、このセクションをスキップした方がよいかもしれません。🤓 @@ -18,7 +18,8 @@ Pythonプロジェクトの作業では、**仮想環境**(または類似の /// -/// info | 情報 +/// note | 備考 + このページでは、**仮想環境**の使用方法と、そのはたらきについて説明します。 もし**すべてを管理するツール**(Pythonのインストールも含む)を導入する準備ができているなら、[uv](https://github.com/astral-sh/uv) をお試しください。 @@ -34,15 +35,15 @@ Pythonプロジェクトの作業では、**仮想環境**(または類似の
```console -// Go to the home directory +// ホームディレクトリに移動 $ cd -// Create a directory for all your code projects +// すべてのコードプロジェクト用のディレクトリを作成 $ mkdir code -// Enter into that code directory +// その code ディレクトリに入る $ cd code -// Create a directory for this project +// このプロジェクト用のディレクトリを作成 $ mkdir awesome-project -// Enter into that project directory +// そのプロジェクトディレクトリに入る $ cd awesome-project ``` @@ -554,7 +555,7 @@ Pythonをインストールしたとき、ファイルを含んだいくつか
```console -// Don't run this now, it's just an example 🤓 +// 今は実行しないでください。これは単なる例です 🤓 $ pip install "fastapi[standard]" ---> 100% ``` @@ -800,7 +801,7 @@ $ cd ~/code/prisoner-of-azkaban $ python main.py -// Error importing sirius, it's not installed 😱 +// sirius のインポートエラー。インストールされていません 😱 Traceback (most recent call last): File "main.py", line 1, in import sirius @@ -808,20 +809,20 @@ Traceback (most recent call last):
-しかし、その仮想環境を無効化し、 `prisoner-of-askaban` のための新しい仮想環境を有効にすれば、 `python` を実行したときに `prisoner-of-azkaban` (アズカバンの囚人)の仮想環境の Python が使用されるようになります。 +しかし、その仮想環境を無効化し、 `prisoner-of-azkaban` のための新しい仮想環境を有効にすれば、 `python` を実行したときに `prisoner-of-azkaban` (アズカバンの囚人)の仮想環境の Python が使用されるようになります。
```console $ cd ~/code/prisoner-of-azkaban -// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎 +// 無効化のために古いディレクトリにいる必要はありません。どこにいても、他のプロジェクトに移動した後でも実行できます 😎 $ deactivate -// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀 +// prisoner-of-azkaban/.venv の仮想環境を有効化する 🚀 $ source .venv/bin/activate -// Now when you run python, it will find the package sirius installed in this virtual environment ✨ +// これで python を実行すると、この仮想環境にインストールされた sirius パッケージが見つかります ✨ $ python main.py I solemnly swear 🐺 diff --git a/docs/ja/mkdocs.yml b/docs/ja/mkdocs.yml deleted file mode 100644 index de18856f4..000000000 --- a/docs/ja/mkdocs.yml +++ /dev/null @@ -1 +0,0 @@ -INHERIT: ../en/mkdocs.yml diff --git a/docs/ko/docs/_llm-test.md b/docs/ko/docs/_llm-test.md index 8b7b275c0..9e9d0ee73 100644 --- a/docs/ko/docs/_llm-test.md +++ b/docs/ko/docs/_llm-test.md @@ -7,11 +7,11 @@ 사용 방법은 다음과 같습니다: * 언어별 프롬프트 `docs/{language code}/llm-prompt.md`를 준비합니다. -* 이 문서를 원하는 대상 언어로 새로 번역합니다(예: `translate.py`의 `translate-page` 명령). 그러면 `docs/{language code}/docs/_llm-test.md` 아래에 번역이 생성됩니다. +* 이 문서를 원하는 대상 언어로 새로 번역합니다(예: `translate.py`의 `translate-page` 명령어). 그러면 `docs/{language code}/docs/_llm-test.md` 아래에 번역이 생성됩니다. * 번역에서 문제가 없는지 확인합니다. * 필요하다면 언어별 프롬프트, 일반 프롬프트, 또는 영어 문서를 개선합니다. * 그런 다음 번역에서 남아 있는 문제를 수동으로 수정해 좋은 번역이 되게 합니다. -* 좋은 번역을 둔 상태에서 다시 번역합니다. 이상적인 결과는 LLM이 더 이상 번역에 변경을 만들지 않는 것입니다. 이는 일반 프롬프트와 언어별 프롬프트가 가능한 한 최선이라는 뜻입니다(때때로 몇 가지 seemingly random 변경을 할 수 있는데, 그 이유는 [LLM은 결정론적 알고리즘이 아니기 때문](https://doublespeak.chat/#/handbook#deterministic-output)입니다). +* 좋은 번역을 둔 상태에서 다시 번역합니다. 이상적인 결과는 LLM이 더 이상 번역에 변경을 만들지 않는 것입니다. 이는 일반 프롬프트와 언어별 프롬프트가 가능한 한 최선이라는 뜻입니다(때때로 몇 가지 겉보기에 무작위인 변경을 할 수 있는데, 그 이유는 [LLM은 결정론적 알고리즘이 아니기 때문](https://doublespeak.chat/#/handbook#deterministic-output)입니다). 테스트: @@ -124,10 +124,6 @@ works(foo="bar") # 이건 동작합니다 🎉 //// tab | 테스트 -/// info | 정보 -일부 텍스트 -/// - /// note | 참고 일부 텍스트 /// @@ -136,10 +132,6 @@ works(foo="bar") # 이건 동작합니다 🎉 일부 텍스트 /// -/// check | 확인 -일부 텍스트 -/// - /// tip | 팁 일부 텍스트 /// @@ -297,7 +289,7 @@ works(foo="bar") # 이건 동작합니다 🎉 * 애플리케이션을 서빙하다 * 페이지를 서빙하다 -* 앱 +* 애플리케이션 * 애플리케이션 * 요청 diff --git a/docs/ko/docs/advanced/additional-responses.md b/docs/ko/docs/advanced/additional-responses.md index e43d7c727..87866946b 100644 --- a/docs/ko/docs/advanced/additional-responses.md +++ b/docs/ko/docs/advanced/additional-responses.md @@ -34,7 +34,7 @@ /// -/// info | 정보 +/// note | 참고 `model` 키는 OpenAPI의 일부가 아닙니다. @@ -183,7 +183,7 @@ /// -/// info | 정보 +/// note | 참고 `responses` 파라미터에서 다른 미디어 타입을 명시적으로 지정하지 않는 한, FastAPI는 응답이 주요 응답 클래스와 동일한 미디어 타입(기본값 `application/json`)을 가진다고 가정합니다. diff --git a/docs/ko/docs/advanced/additional-status-codes.md b/docs/ko/docs/advanced/additional-status-codes.md index 6251b68b2..4762c8eed 100644 --- a/docs/ko/docs/advanced/additional-status-codes.md +++ b/docs/ko/docs/advanced/additional-status-codes.md @@ -8,7 +8,7 @@ 기본 상태 코드와 별도로 추가 상태 코드를 반환하려면 `JSONResponse`와 같이 `Response`를 직접 반환하고 추가 상태 코드를 직접 설정할 수 있습니다. -예를 들어 항목을 업데이트할 수 있는 *경로 처리*가 있고 성공 시 200 “OK”의 HTTP 상태 코드를 반환한다고 가정해 보겠습니다. +예를 들어 항목을 업데이트할 수 있는 *경로 처리*가 있고 성공 시 200 "OK"의 HTTP 상태 코드를 반환한다고 가정해 보겠습니다. 하지만 새로운 항목을 허용하기를 원할 것입니다. 그리고 항목이 이전에 존재하지 않았다면 이를 생성하고 HTTP 상태 코드 201 "Created"를 반환합니다. diff --git a/docs/ko/docs/advanced/advanced-dependencies.md b/docs/ko/docs/advanced/advanced-dependencies.md index 2755986a2..49b96bdad 100644 --- a/docs/ko/docs/advanced/advanced-dependencies.md +++ b/docs/ko/docs/advanced/advanced-dependencies.md @@ -79,7 +79,7 @@ checker(q="somequery") ### `yield`와 `scope`가 있는 의존성 { #dependencies-with-yield-and-scope } -0.121.0 버전에서 FastAPI는 `Depends(scope="function")` 지원을 추가했습니다. +0.121.0 버전에서 FastAPI는 `yield`가 있는 의존성을 위한 `Depends(scope="function")` 지원을 추가했습니다. `Depends(scope="function")`를 사용하면, `yield` 이후의 종료 코드는 *경로 처리 함수*가 끝난 직후(클라이언트에 응답이 반환되기 전)에 실행됩니다. @@ -99,7 +99,7 @@ FastAPI 0.118.0 이전에는 `yield`가 있는 의존성을 사용하면, *경 이 동작은 0.118.0에서 되돌려져, `yield` 이후의 종료 코드가 응답이 전송된 뒤 실행되도록 변경되었습니다. -/// info | 정보 +/// note | 참고 아래에서 보시겠지만, 이는 0.106.0 버전 이전의 동작과 매우 비슷하지만, 여러 개선 사항과 코너 케이스에 대한 버그 수정이 포함되어 있습니다. diff --git a/docs/ko/docs/advanced/custom-response.md b/docs/ko/docs/advanced/custom-response.md index e85ec3c74..d81a9dafb 100644 --- a/docs/ko/docs/advanced/custom-response.md +++ b/docs/ko/docs/advanced/custom-response.md @@ -41,7 +41,7 @@ {* ../../docs_src/custom_response/tutorial002_py310.py hl[2,7] *} -/// info | 정보 +/// note | 참고 `response_class` 매개변수는 응답의 "미디어 타입"을 정의하는 데에도 사용됩니다. @@ -65,7 +65,7 @@ /// -/// info | 정보 +/// note | 참고 물론 실제 `Content-Type` 헤더, 상태 코드 등은 반환된 `Response` 객체에서 가져옵니다. diff --git a/docs/ko/docs/advanced/dataclasses.md b/docs/ko/docs/advanced/dataclasses.md index 77e8d0464..609cb6cd9 100644 --- a/docs/ko/docs/advanced/dataclasses.md +++ b/docs/ko/docs/advanced/dataclasses.md @@ -18,7 +18,7 @@ FastAPI는 **Pydantic** 위에 구축되어 있으며, 지금까지는 Pydantic 이는 Pydantic 모델을 사용할 때와 같은 방식으로 동작합니다. 그리고 실제로도 내부적으로는 Pydantic을 사용해 같은 방식으로 구현됩니다. -/// info +/// note | 참고 dataclasses는 Pydantic 모델이 할 수 있는 모든 것을 할 수는 없다는 점을 기억하세요. diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md index 708ad443f..13db29ef2 100644 --- a/docs/ko/docs/advanced/events.md +++ b/docs/ko/docs/advanced/events.md @@ -6,15 +6,15 @@ 이 코드는 애플리케이션이 요청을 받기 **시작**하기 전에 실행되고, 요청 처리를 **끝낸 직후**에 실행되기 때문에 전체 애플리케이션의 **수명(lifespan)**을 다룹니다(잠시 후 "lifespan"이라는 단어가 중요해집니다 😉). -이는 전체 앱에서 사용해야 하는 **자원**을 설정하고, 요청 간에 **공유되는** 자원을 설정하고, 그리고/또는 이후에 **정리**하는 데 매우 유용할 수 있습니다. 예를 들어, 데이터베이스 연결 풀 또는 공유 머신러닝 모델을 로드하는 경우입니다. +이는 전체 애플리케이션에서 사용해야 하는 **자원**을 설정하고, 요청 간에 **공유되는** 자원을 설정하고, 그리고/또는 이후에 **정리**하는 데 매우 유용할 수 있습니다. 예를 들어, 데이터베이스 연결 풀 또는 공유 머신러닝 모델을 로드하는 경우입니다. ## 사용 사례 { #use-case } 먼저 **사용 사례** 예시로 시작한 다음, 이를 어떻게 해결할지 살펴보겠습니다. -요청을 처리하는 데 사용하고 싶은 **머신러닝 모델**이 있다고 상상해 봅시다. 🤖 +요청을 처리하는 데 사용하고 싶은 몇 가지 **머신러닝 모델**이 있다고 상상해 봅시다. 🤖 -동일한 모델이 요청 간에 공유되므로, 요청마다 모델이 하나씩 있거나 사용자마다 하나씩 있는 등의 방식이 아닙니다. +동일한 모델들이 요청 간에 공유되므로, 요청마다 모델이 하나씩 있거나 사용자마다 하나씩 있는 등의 방식이 아닙니다. 모델을 로드하는 데 **상당한 시간이 걸린다고 상상해 봅시다**, 왜냐하면 모델이 **디스크에서 많은 데이터를 읽어야** 하기 때문입니다. 그래서 모든 요청마다 이를 수행하고 싶지는 않습니다. @@ -24,7 +24,7 @@ ## Lifespan { #lifespan } -`FastAPI` 앱의 `lifespan` 매개변수와 "컨텍스트 매니저"를 사용하여 *시작*과 *종료* 로직을 정의할 수 있습니다(컨텍스트 매니저가 무엇인지 잠시 후에 보여드리겠습니다). +`FastAPI` 애플리케이션의 `lifespan` 매개변수와 "컨텍스트 매니저"를 사용하여 *시작*과 *종료* 로직을 정의할 수 있습니다(컨텍스트 매니저가 무엇인지 잠시 후에 보여드리겠습니다). 예제로 시작한 다음 자세히 살펴보겠습니다. @@ -32,7 +32,7 @@ {* ../../docs_src/events/tutorial003_py310.py hl[16,19] *} -여기서는 `yield` 이전에 (가짜) 모델 함수를 머신러닝 모델이 들어 있는 딕셔너리에 넣어 모델을 로드하는 비용이 큰 *시작* 작업을 시뮬레이션합니다. 이 코드는 애플리케이션이 **요청을 받기 시작하기 전**, *시작* 동안에 실행됩니다. +여기서는 `yield` 이전에 (가짜) 모델 함수를 머신러닝 모델들이 들어 있는 딕셔너리에 넣어 모델을 로드하는 비용이 큰 *시작* 작업을 시뮬레이션합니다. 이 코드는 애플리케이션이 **요청을 받기 시작하기 전**, *시작* 동안에 실행됩니다. 그리고 `yield` 직후에는 모델을 언로드합니다. 이 코드는 애플리케이션이 **요청 처리를 마친 후**, *종료* 직전에 실행됩니다. 예를 들어 메모리나 GPU 같은 자원을 해제할 수 있습니다. @@ -80,7 +80,7 @@ async with lifespan(app): 위의 코드 예제에서는 직접 사용하지 않고, FastAPI에 전달하여 FastAPI가 이를 사용하도록 합니다. -`FastAPI` 앱의 `lifespan` 매개변수는 **비동기 컨텍스트 매니저**를 받으므로, 새 `lifespan` 비동기 컨텍스트 매니저를 전달할 수 있습니다. +`FastAPI` 애플리케이션의 `lifespan` 매개변수는 **비동기 컨텍스트 매니저**를 받으므로, 새 `lifespan` 비동기 컨텍스트 매니저를 전달할 수 있습니다. {* ../../docs_src/events/tutorial003_py310.py hl[22] *} @@ -88,7 +88,7 @@ async with lifespan(app): /// warning | 경고 -*시작*과 *종료*를 처리하는 권장 방법은 위에서 설명한 대로 `FastAPI` 앱의 `lifespan` 매개변수를 사용하는 것입니다. `lifespan` 매개변수를 제공하면 `startup`과 `shutdown` 이벤트 핸들러는 더 이상 호출되지 않습니다. `lifespan`만 쓰거나 이벤트만 쓰거나 둘 중 하나이지, 둘 다는 아닙니다. +*시작*과 *종료*를 처리하는 권장 방법은 위에서 설명한 대로 `FastAPI` 애플리케이션의 `lifespan` 매개변수를 사용하는 것입니다. `lifespan` 매개변수를 제공하면 `startup`과 `shutdown` 이벤트 핸들러는 더 이상 호출되지 않습니다. `lifespan`만 쓰거나 이벤트만 쓰거나 둘 중 하나이지, 둘 다는 아닙니다. 이 부분은 아마 건너뛰셔도 됩니다. @@ -120,7 +120,7 @@ async with lifespan(app): 여기서 `shutdown` 이벤트 핸들러 함수는 텍스트 한 줄 `"Application shutdown"`을 `log.txt` 파일에 기록합니다. -/// info | 정보 +/// note | 참고 `open()` 함수에서 `mode="a"`는 "append"(추가)를 의미하므로, 기존 내용을 덮어쓰지 않고 파일에 있던 내용 뒤에 줄이 추가됩니다. @@ -150,9 +150,9 @@ async with lifespan(app): 호기심 많은 분들을 위한 기술적인 세부사항입니다. 🤓 -내부적으로 ASGI 기술 사양에서는 이것이 [Lifespan Protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html)의 일부이며, `startup`과 `shutdown`이라는 이벤트를 정의합니다. +내부적으로 ASGI 기술 사양에서는 이것이 [Lifespan 프로토콜](https://asgi.readthedocs.io/en/latest/specs/lifespan.html)의 일부이며, `startup`과 `shutdown`이라는 이벤트를 정의합니다. -/// info | 정보 +/// note | 참고 Starlette `lifespan` 핸들러에 대해서는 [Starlette의 Lifespan 문서](https://www.starlette.dev/lifespan/)에서 더 읽어볼 수 있습니다. diff --git a/docs/ko/docs/advanced/generate-clients.md b/docs/ko/docs/advanced/generate-clients.md index bf29e52e9..9cbe46ff8 100644 --- a/docs/ko/docs/advanced/generate-clients.md +++ b/docs/ko/docs/advanced/generate-clients.md @@ -2,7 +2,7 @@ **FastAPI**는 **OpenAPI** 사양을 기반으로 하므로, FastAPI의 API는 많은 도구가 이해할 수 있는 표준 형식으로 설명할 수 있습니다. -덕분에 여러 언어용 클라이언트 라이브러리(**SDKs**), 최신 **문서**, 그리고 코드와 동기화된 **테스트** 또는 **자동화 워크플로**를 쉽게 생성할 수 있습니다. +덕분에 최신 **문서**, 여러 언어용 클라이언트 라이브러리(**SDKs**), 그리고 코드와 동기화된 **테스트** 또는 **자동화 워크플로**를 쉽게 생성할 수 있습니다. 이 가이드에서는 FastAPI 백엔드용 **TypeScript SDK**를 생성하는 방법을 배웁니다. @@ -20,22 +20,6 @@ FastAPI는 **OpenAPI 3.1** 사양을 자동으로 생성하므로, 사용하는 /// -## FastAPI 스폰서의 SDK 생성기 { #sdk-generators-from-fastapi-sponsors } - -이 섹션에서는 FastAPI를 후원하는 회사들이 제공하는 **벤처 투자 기반** 및 **기업 지원** 솔루션을 소개합니다. 이 제품들은 고품질로 생성된 SDK에 더해 **추가 기능**과 **통합**을 제공합니다. - -✨ [**FastAPI 후원하기**](../help-fastapi.md#sponsor-the-author) ✨를 통해, 이 회사들은 프레임워크와 그 **생태계**가 건강하고 **지속 가능**하게 유지되도록 돕습니다. - -또한 이들의 후원은 FastAPI **커뮤니티**(여러분)에 대한 강한 헌신을 보여주며, **좋은 서비스**를 제공하는 것뿐 아니라, 견고하고 활발한 프레임워크인 FastAPI를 지원하는 데에도 관심이 있음을 나타냅니다. 🙇 - -예를 들어 다음을 사용해 볼 수 있습니다: - -* [Speakeasy](https://speakeasy.com/editor?utm_source=fastapi+repo&utm_medium=github+sponsorship) -* [Stainless](https://www.stainless.com/?utm_source=fastapi&utm_medium=referral) -* [liblab](https://developers.liblab.com/tutorials/sdk-for-fastapi?utm_source=fastapi) - -이 중 일부는 오픈 소스이거나 무료 티어를 제공하므로, 비용 부담 없이 사용해 볼 수 있습니다. 다른 상용 SDK 생성기도 있으며 온라인에서 찾을 수 있습니다. 🤓 - ## TypeScript SDK 만들기 { #create-a-typescript-sdk } 간단한 FastAPI 애플리케이션으로 시작해 보겠습니다: diff --git a/docs/ko/docs/advanced/json-base64-bytes.md b/docs/ko/docs/advanced/json-base64-bytes.md index b5e55a41a..b24acda86 100644 --- a/docs/ko/docs/advanced/json-base64-bytes.md +++ b/docs/ko/docs/advanced/json-base64-bytes.md @@ -4,7 +4,7 @@ ## Base64와 파일 { #base64-vs-files } -바이너리 데이터 업로드에는 [요청 파일](../tutorial/request-files.md)을, 바이너리 데이터 전송에는 [커스텀 응답 - FileResponse](./custom-response.md#fileresponse--fileresponse-)를 사용할 수 있는지 먼저 고려하세요. JSON으로 인코딩하는 대신 말입니다. +바이너리 데이터 업로드에는 [요청 파일](../tutorial/request-files.md)을, 바이너리 데이터 전송에는 [커스텀 응답 - FileResponse](./custom-response.md#fileresponse)를 사용할 수 있는지 먼저 고려하세요. JSON으로 인코딩하는 대신 말입니다. JSON은 UTF-8로 인코딩된 문자열만 포함할 수 있으므로, 원시 바이트를 그대로 담을 수 없습니다. diff --git a/docs/ko/docs/advanced/openapi-callbacks.md b/docs/ko/docs/advanced/openapi-callbacks.md index fa71acdcf..a44997ba2 100644 --- a/docs/ko/docs/advanced/openapi-callbacks.md +++ b/docs/ko/docs/advanced/openapi-callbacks.md @@ -165,15 +165,15 @@ https://www.external.org/events/invoices/2expen51ve ### 콜백 라우터 추가하기 { #add-the-callback-router } -이 시점에서, 위에서 만든 콜백 라우터 안에 *콜백 경로 처리(들)*(즉 *external developer*가 *external API*에 구현해야 하는 것들)을 준비했습니다. +이 시점에서, 위에서 만든 콜백 라우터 안에 *콜백 경로 처리(들)*(즉 *외부 개발자*가 *external API*에 구현해야 하는 것들)을 준비했습니다. -이제 *여러분의 API 경로 처리 데코레이터*에서 `callbacks` 파라미터를 사용해, 그 콜백 라우터의 `.routes` 속성(실제로는 routes/*경로 처리*의 `list`)을 전달합니다: +이제 *여러분의 API 경로 처리 데코레이터*에서 `callbacks` 파라미터를 사용해, 그 콜백 라우터의 `.routes` 속성을 전달합니다: {* ../../docs_src/openapi_callbacks/tutorial001_py310.py hl[33] *} /// tip | 팁 -`callback=`에 라우터 자체(`invoices_callback_router`)를 넘기는 것이 아니라, `invoices_callback_router.routes`처럼 `.routes` 속성을 넘긴다는 점에 주목하세요. +`callbacks=`에 라우터 자체(`invoices_callback_router`)를 넘기는 것이 아니라, `invoices_callback_router.routes`처럼 `.routes` 속성을 넘긴다는 점에 주목하세요. FastAPI는 이 라우트들을 사용하여 콜백 OpenAPI 문서를 생성합니다. /// diff --git a/docs/ko/docs/advanced/openapi-webhooks.md b/docs/ko/docs/advanced/openapi-webhooks.md index e40a7bb18..bb3f7895c 100644 --- a/docs/ko/docs/advanced/openapi-webhooks.md +++ b/docs/ko/docs/advanced/openapi-webhooks.md @@ -22,7 +22,7 @@ webhook의 URL을 등록하는 방법과 실제로 그 요청을 보내는 코 이렇게 하면 사용자가 여러분의 **webhook** 요청을 받기 위해 **자신들의 API를 구현**하기가 훨씬 쉬워지고, 경우에 따라서는 자신의 API 코드 일부를 자동 생성할 수도 있습니다. -/// info | 정보 +/// note | 참고 Webhooks는 OpenAPI 3.1.0 이상에서 사용할 수 있으며, FastAPI `0.99.0` 이상에서 지원됩니다. @@ -36,7 +36,7 @@ Webhooks는 OpenAPI 3.1.0 이상에서 사용할 수 있으며, FastAPI `0.99.0` 여러분이 정의한 webhook은 **OpenAPI** 스키마와 자동 **docs UI**에 포함됩니다. -/// info | 정보 +/// note | 참고 `app.webhooks` 객체는 실제로 `APIRouter`일 뿐이며, 여러 파일로 앱을 구조화할 때 사용하는 것과 동일한 타입입니다. diff --git a/docs/ko/docs/advanced/path-operation-advanced-configuration.md b/docs/ko/docs/advanced/path-operation-advanced-configuration.md index 253a6f302..398816005 100644 --- a/docs/ko/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/ko/docs/advanced/path-operation-advanced-configuration.md @@ -2,7 +2,7 @@ ## OpenAPI operationId { #openapi-operationid } -/// warning | 경고 +/// warning OpenAPI “전문가”가 아니라면, 아마 이 내용은 필요하지 않을 것입니다. @@ -16,19 +16,13 @@ OpenAPI “전문가”가 아니라면, 아마 이 내용은 필요하지 않 ### *경로 처리 함수* 이름을 operationId로 사용하기 { #using-the-path-operation-function-name-as-the-operationid } -API의 함수 이름을 `operationId`로 사용하고 싶다면, 모든 API를 순회하면서 `APIRoute.name`을 사용해 각 *경로 처리*의 `operation_id`를 덮어쓸 수 있습니다. +API의 함수 이름을 `operationId`로 사용하고 싶다면, `FastAPI`에 사용자 정의 `generate_unique_id_function`을 전달할 수 있습니다. -모든 *경로 처리*를 추가한 뒤에 수행해야 합니다. +이 함수는 각 `APIRoute`를 받아 그 *경로 처리*에 사용할 `operationId`를 반환합니다. -{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2, 12:21, 24] *} +{* ../../docs_src/path_operation_advanced_configuration/tutorial002_py310.py hl[2,5:6,9] *} -/// tip | 팁 - -`app.openapi()`를 수동으로 호출한다면, 그 전에 `operationId`들을 업데이트해야 합니다. - -/// - -/// warning | 경고 +/// warning 이렇게 할 경우, 각 *경로 처리 함수*의 이름이 고유하도록 보장해야 합니다. @@ -78,7 +72,7 @@ OpenAPI 명세에서는 이를 [Operation Object](https://github.com/OAI/OpenAPI 이 *경로 처리* 전용 OpenAPI 스키마는 보통 **FastAPI**가 자동으로 생성하지만, 확장할 수도 있습니다. -/// tip | 팁 +/// tip 이는 저수준 확장 지점입니다. @@ -163,7 +157,7 @@ OpenAPI 명세에서는 이를 [Operation Object](https://github.com/OAI/OpenAPI {* ../../docs_src/path_operation_advanced_configuration/tutorial007_py310.py hl[24:31] *} -/// tip | 팁 +/// tip 여기서는 같은 Pydantic 모델을 재사용합니다. diff --git a/docs/ko/docs/advanced/response-change-status-code.md b/docs/ko/docs/advanced/response-change-status-code.md index f30474917..5e54dc75e 100644 --- a/docs/ko/docs/advanced/response-change-status-code.md +++ b/docs/ko/docs/advanced/response-change-status-code.md @@ -1,5 +1,6 @@ # 응답 - 상태 코드 변경 { #response-change-status-code } + 기본 [응답 상태 코드 설정](../tutorial/response-status-code.md)이 가능하다는 걸 이미 알고 계실 겁니다. 하지만 경우에 따라 기본 설정과 다른 상태 코드를 반환해야 할 때가 있습니다. diff --git a/docs/ko/docs/advanced/response-cookies.md b/docs/ko/docs/advanced/response-cookies.md index b73d71969..f17046e7b 100644 --- a/docs/ko/docs/advanced/response-cookies.md +++ b/docs/ko/docs/advanced/response-cookies.md @@ -26,7 +26,7 @@ {* ../../docs_src/response_cookies/tutorial001_py310.py hl[10:12] *} -/// tip +/// tip | 팁 `Response` 매개변수를 사용하지 않고 응답을 직접 반환하는 경우, FastAPI는 이를 직접 반환한다는 점에 유의하세요. diff --git a/docs/ko/docs/advanced/response-directly.md b/docs/ko/docs/advanced/response-directly.md index 301a259b2..fc2efc728 100644 --- a/docs/ko/docs/advanced/response-directly.md +++ b/docs/ko/docs/advanced/response-directly.md @@ -18,7 +18,7 @@ `Response` 또는 그 하위 클래스를 반환할 수 있습니다. -/// info | 정보 +/// note | 참고 `JSONResponse` 자체도 `Response`의 하위 클래스입니다. diff --git a/docs/ko/docs/advanced/response-headers.md b/docs/ko/docs/advanced/response-headers.md index e7157d8f4..769972967 100644 --- a/docs/ko/docs/advanced/response-headers.md +++ b/docs/ko/docs/advanced/response-headers.md @@ -1,5 +1,6 @@ # 응답 헤더 { #response-headers } + ## `Response` 매개변수 사용하기 { #use-a-response-parameter } 여러분은 *경로 처리 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다 (쿠키와 같이 사용할 수 있습니다). diff --git a/docs/ko/docs/advanced/security/oauth2-scopes.md b/docs/ko/docs/advanced/security/oauth2-scopes.md index 5a785ff9f..265f82aa7 100644 --- a/docs/ko/docs/advanced/security/oauth2-scopes.md +++ b/docs/ko/docs/advanced/security/oauth2-scopes.md @@ -4,9 +4,9 @@ 이를 통해 OAuth2 표준을 따르는 더 세밀한 권한 시스템을 OpenAPI 애플리케이션(및 API 문서)에 통합할 수 있습니다. -스코프를 사용하는 OAuth2는 Facebook, Google, GitHub, Microsoft, X(Twitter) 등 많은 대형 인증 제공자가 사용하는 메커니즘입니다. 이들은 이를 통해 사용자와 애플리케이션에 특정 권한을 제공합니다. +스코프를 사용하는 OAuth2는 Facebook, Google, GitHub, Microsoft, X (Twitter) 등 많은 대형 인증 제공자가 사용하는 메커니즘입니다. 이들은 이를 통해 사용자와 애플리케이션에 특정 권한을 제공합니다. -Facebook, Google, GitHub, Microsoft, X(Twitter)로 “로그인”할 때마다, 해당 애플리케이션은 스코프가 있는 OAuth2를 사용하고 있습니다. +Facebook, Google, GitHub, Microsoft, X (Twitter)로 “로그인”할 때마다, 해당 애플리케이션은 스코프가 있는 OAuth2를 사용하고 있습니다. 이 섹션에서는 **FastAPI** 애플리케이션에서 동일한 “스코프가 있는 OAuth2”로 인증(Authentication)과 인가(Authorization)를 관리하는 방법을 확인합니다. @@ -46,7 +46,7 @@ OpenAPI(예: API 문서)에서는 “security schemes”를 정의할 수 있습 * `instagram_basic` 는 Facebook/Instagram에서 사용합니다. * `https://www.googleapis.com/auth/drive` 는 Google에서 사용합니다. -/// info | 정보 +/// note | 참고 OAuth2에서 “스코프”는 필요한 특정 권한을 선언하는 문자열일 뿐입니다. @@ -126,7 +126,7 @@ OAuth2 입장에서는 그저 문자열입니다. {* ../../docs_src/security/tutorial005_an_py310.py hl[5,141,172] *} -/// info | 기술 세부사항 +/// note | 기술 세부사항 `Security`는 실제로 `Depends`의 서브클래스이며, 나중에 보게 될 추가 매개변수 하나만 더 있습니다. diff --git a/docs/ko/docs/advanced/settings.md b/docs/ko/docs/advanced/settings.md index 49a2b640e..f7e8c20e7 100644 --- a/docs/ko/docs/advanced/settings.md +++ b/docs/ko/docs/advanced/settings.md @@ -1,5 +1,6 @@ # 설정과 환경 변수 { #settings-and-environment-variables } + 많은 경우 애플리케이션에는 외부 설정이나 구성(예: secret key, 데이터베이스 자격 증명, 이메일 서비스 자격 증명 등)이 필요할 수 있습니다. 이러한 설정 대부분은 데이터베이스 URL처럼 변동 가능(변경될 수 있음)합니다. 그리고 많은 설정은 secret처럼 민감할 수 있습니다. diff --git a/docs/ko/docs/advanced/stream-data.md b/docs/ko/docs/advanced/stream-data.md index 5eda170cb..94276876f 100644 --- a/docs/ko/docs/advanced/stream-data.md +++ b/docs/ko/docs/advanced/stream-data.md @@ -2,9 +2,9 @@ JSON으로 구조화할 수 있는 데이터를 스트리밍하려면 [JSON Lines 스트리밍](../tutorial/stream-json-lines.md)을 사용하세요. -하지만 순수 바이너리 데이터나 문자열을 스트리밍하려면 다음과 같이 하면 됩니다. +하지만 **순수 바이너리 데이터**나 문자열을 스트리밍하려면 다음과 같이 하면 됩니다. -/// info | 정보 +/// note | 참고 FastAPI 0.134.0에 추가되었습니다. @@ -12,21 +12,21 @@ FastAPI 0.134.0에 추가되었습니다. ## 사용 예시 { #use-cases } -예를 들어 AI LLM 서비스의 출력에서 바로 순수 문자열을 스트리밍하고 싶다면 이를 사용할 수 있습니다. +예를 들어 **AI LLM** 서비스의 출력에서 바로 순수 문자열을 스트리밍하고 싶다면 이를 사용할 수 있습니다. -또한 큰 바이너리 파일을 스트리밍하는 데 사용할 수 있습니다. 한 번에 모두 메모리로 읽지 않고, 읽는 즉시 데이터 청크를 순차적으로 스트리밍합니다. +또한 **큰 바이너리 파일**을 스트리밍하는 데 사용할 수 있습니다. 한 번에 모두 메모리로 읽지 않고, 읽는 즉시 데이터 청크를 순차적으로 스트리밍합니다. -이 방식으로 비디오나 오디오를 스트리밍할 수도 있으며, 처리하면서 생성된 데이터를 곧바로 전송할 수도 있습니다. +이 방식으로 **비디오**나 **오디오**를 스트리밍할 수도 있으며, 처리하면서 생성된 데이터를 곧바로 전송할 수도 있습니다. ## `yield`와 함께 `StreamingResponse` 사용하기 { #a-streamingresponse-with-yield } -경로 처리 함수에서 `response_class=StreamingResponse`를 선언하면 `yield`를 사용해 데이터 청크를 순차적으로 보낼 수 있습니다. +*경로 처리 함수*에서 `response_class=StreamingResponse`를 선언하면 `yield`를 사용해 데이터 청크를 순차적으로 보낼 수 있습니다. {* ../../docs_src/stream_data/tutorial001_py310.py ln[1:23] hl[20,23] *} FastAPI는 각 데이터 청크를 있는 그대로 `StreamingResponse`에 전달하며, JSON 등으로 변환하려고 하지 않습니다. -### async가 아닌 경로 처리 함수 { #non-async-path-operation-functions } +### async가 아닌 *경로 처리 함수* { #non-async-path-operation-functions } `async`가 없는 일반 `def` 함수에서도 동일하게 `yield`를 사용할 수 있습니다. @@ -40,7 +40,7 @@ FastAPI는 데이터를 Pydantic으로 JSON으로 변환하거나 어떤 방식 {* ../../docs_src/stream_data/tutorial001_py310.py ln[32:35] hl[33] *} -이는 곧 `StreamingResponse`를 사용할 때 타입 애너테이션과 무관하게, 전송 기준에 맞춰 바이트 데이터를 생성하고 인코딩할 자유와 책임이 여러분에게 있음을 의미합니다. 🤓 +이는 곧 `StreamingResponse`를 사용할 때 타입 애너테이션과 무관하게, 전송 기준에 맞춰 바이트 데이터를 생성하고 인코딩할 **자유**와 **책임**이 여러분에게 있음을 의미합니다. 🤓 ### 바이트 스트리밍 { #stream-bytes } @@ -58,7 +58,7 @@ FastAPI는 데이터를 Pydantic으로 JSON으로 변환하거나 어떤 방식 {* ../../docs_src/stream_data/tutorial002_py310.py ln[6,19:20] hl[20] *} -그런 다음 경로 처리 함수에서 `response_class=PNGStreamingResponse`로 이 새 클래스를 사용할 수 있습니다: +그런 다음 *경로 처리 함수*에서 `response_class=PNGStreamingResponse`로 이 새 클래스를 사용할 수 있습니다: {* ../../docs_src/stream_data/tutorial002_py310.py ln[23:27] hl[23] *} @@ -90,7 +90,7 @@ FastAPI는 데이터를 Pydantic으로 JSON으로 변환하거나 어떤 방식 또한 디스크나 네트워크에서 읽기 때문에, 많은 경우 읽기 작업은 이벤트 루프를 막을 수 있는 블로킹 연산입니다. -/// info | 정보 +/// note | 참고 위의 예시는 예외적인 경우입니다. `io.BytesIO` 객체는 이미 메모리에 있으므로 읽기가 아무 것도 차단하지 않습니다. @@ -98,7 +98,7 @@ FastAPI는 데이터를 Pydantic으로 JSON으로 변환하거나 어떤 방식 /// -이벤트 루프가 블로킹되는 것을 피하려면 경로 처리 함수를 `async def` 대신 일반 `def`로 선언하세요. 그러면 FastAPI가 스레드풀 워커에서 실행하여 메인 루프가 막히지 않도록 합니다. +이벤트 루프가 블로킹되는 것을 피하려면 *경로 처리 함수*를 `async def` 대신 일반 `def`로 선언하세요. 그러면 FastAPI가 스레드풀 워커에서 실행하여 메인 루프가 막히지 않도록 합니다. {* ../../docs_src/stream_data/tutorial002_py310.py ln[30:34] hl[31] *} diff --git a/docs/ko/docs/advanced/strict-content-type.md b/docs/ko/docs/advanced/strict-content-type.md index 82683e15c..39ecde4b6 100644 --- a/docs/ko/docs/advanced/strict-content-type.md +++ b/docs/ko/docs/advanced/strict-content-type.md @@ -81,7 +81,7 @@ http://localhost:8000/v1/agents/multivac 이 설정을 사용하면 `Content-Type` 헤더가 없는 요청도 본문이 JSON으로 파싱됩니다. 이는 이전 버전의 FastAPI와 동일한 동작입니다. -/// info | 정보 +/// note | 참고 이 동작과 설정은 FastAPI 0.132.0에 추가되었습니다. diff --git a/docs/ko/docs/advanced/websockets.md b/docs/ko/docs/advanced/websockets.md index 0b920c3b3..b37d93804 100644 --- a/docs/ko/docs/advanced/websockets.md +++ b/docs/ko/docs/advanced/websockets.md @@ -111,7 +111,7 @@ WebSocket 엔드포인트에서 `fastapi`에서 다음을 가져와 사용할 {* ../../docs_src/websockets_/tutorial002_an_py310.py hl[68:69,82] *} -/// info | 정보 +/// note | 참고 WebSocket이기 때문에 `HTTPException`을 발생시키는 것은 적절하지 않습니다. 대신 `WebSocketException`을 발생시킵니다. diff --git a/docs/ko/docs/advanced/wsgi.md b/docs/ko/docs/advanced/wsgi.md index 921e426ef..2b3012a46 100644 --- a/docs/ko/docs/advanced/wsgi.md +++ b/docs/ko/docs/advanced/wsgi.md @@ -6,7 +6,7 @@ ## `WSGIMiddleware` 사용하기 { #using-wsgimiddleware } -/// info | 정보 +/// note | 참고 이를 사용하려면 `a2wsgi`를 설치해야 합니다. 예: `pip install a2wsgi` @@ -42,7 +42,7 @@ Hello, World from Flask! ``` -그리고 [http://localhost:8000/v2](http://localhost:8000/v2)로 이동하면 **FastAPI**의 응답을 볼 수 있습니다: +그리고 [http://localhost:8000/v2](http://localhost:8000/v2)로 이동하면 FastAPI의 응답을 볼 수 있습니다: ```JSON { diff --git a/docs/ko/docs/alternatives.md b/docs/ko/docs/alternatives.md index 4f92f69d2..1bd0ba56a 100644 --- a/docs/ko/docs/alternatives.md +++ b/docs/ko/docs/alternatives.md @@ -24,7 +24,7 @@ ### [Django REST Framework](https://www.django-rest-framework.org/) { #django-rest-framework } -Django REST framework는 Django를 기반으로 Web API를 구축하기 위한 유연한 toolkit으로 만들어졌고, Django의 API 기능을 개선하기 위한 목적이었습니다. +Django REST Framework는 Django를 기반으로 Web API를 구축하기 위한 유연한 toolkit으로 만들어졌고, Django의 API 기능을 개선하기 위한 목적이었습니다. Mozilla, Red Hat, Eventbrite를 포함해 많은 회사에서 사용합니다. @@ -36,7 +36,7 @@ Django REST Framework는 Tom Christie가 만들었습니다. **FastAPI**의 기 /// -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 자동 API 문서화 웹 사용자 인터페이스를 제공하기. @@ -56,7 +56,7 @@ Flask는 "microframework"로, Django에 기본으로 포함된 데이터베이 Flask의 단순함을 고려하면 API를 구축하는 데 잘 맞는 것처럼 보였습니다. 다음으로 찾고자 했던 것은 Flask용 "Django REST Framework"였습니다. -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 micro-framework가 되기. 필요한 도구와 구성요소를 쉽게 조합할 수 있도록 하기. @@ -80,7 +80,7 @@ Requests는 매우 단순하고 직관적인 설계를 가졌고, 합리적인 그래서 공식 웹사이트에서 말하듯이: -> Requests is one of the most downloaded Python packages of all time +> Requests는 역대 가장 많이 다운로드된 Python 패키지 중 하나입니다 사용 방법은 매우 간단합니다. 예를 들어 `GET` 요청을 하려면 다음처럼 작성합니다: @@ -98,7 +98,7 @@ def read_url(): `requests.get(...)`와 `@app.get(...)`의 유사성을 확인해 보세요. -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 * 단순하고 직관적인 API를 갖기. * HTTP method 이름(operations)을 직접, 직관적이고 명확한 방식으로 사용하기. @@ -118,7 +118,7 @@ def read_url(): 그래서 2.0 버전을 이야기할 때는 "Swagger"라고 말하는 것이 일반적이고, 3+ 버전은 "OpenAPI"라고 말하는 것이 일반적입니다. -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 커스텀 schema 대신, API 사양을 위한 열린 표준을 채택하고 사용하기. @@ -147,7 +147,7 @@ API에 또 하나 크게 필요한 기능은 데이터 검증입니다. 특정 하지만 Python type hints가 존재하기 전에 만들어졌습니다. 그래서 각 스키마를 정의하려면 Marshmallow가 제공하는 특정 유틸리티와 클래스를 사용해야 합니다. -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 데이터 타입과 검증을 제공하는 "schema"를 코드로 정의하고, 이를 자동으로 활용하기. @@ -163,13 +163,13 @@ Webargs는 Flask를 포함한 여러 framework 위에서 이를 제공하기 위 아주 훌륭한 도구이며, 저도 **FastAPI**를 만들기 전에 많이 사용했습니다. -/// info | 정보 +/// note | 참고 Webargs는 Marshmallow와 같은 개발자들이 만들었습니다. /// -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 들어오는 요청 데이터의 자동 검증을 갖기. @@ -193,13 +193,13 @@ Flask, Starlette, Responder 등에서 이런 방식으로 동작합니다. 에디터가 이를 크게 도와주지 못합니다. 또한 파라미터나 Marshmallow schema를 수정해놓고 YAML docstring도 같이 수정하는 것을 잊어버리면, 생성된 schema는 오래된 상태가 됩니다. -/// info | 정보 +/// note | 참고 APISpec은 Marshmallow와 같은 개발자들이 만들었습니다. /// -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 API를 위한 열린 표준인 OpenAPI를 지원하기. @@ -223,15 +223,15 @@ Flask + Flask-apispec + Marshmallow + Webargs 조합은 **FastAPI**를 만들기 * [https://github.com/tiangolo/full-stack-flask-couchbase](https://github.com/tiangolo/full-stack-flask-couchbase) * [https://github.com/tiangolo/full-stack-flask-couchdb](https://github.com/tiangolo/full-stack-flask-couchdb) -그리고 이 동일한 full-stack generator들이 [**FastAPI** Project Generators](project-generation.md)의 기반이 되었습니다. +그리고 이 동일한 full-stack generator들이 [**FastAPI** 프로젝트 생성기](project-generation.md)의 기반이 되었습니다. -/// info | 정보 +/// note | 참고 Flask-apispec은 Marshmallow와 같은 개발자들이 만들었습니다. /// -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 serialization과 validation을 정의하는 동일한 코드로부터 OpenAPI schema를 자동 생성하기. @@ -251,7 +251,7 @@ Angular 2에서 영감을 받은 의존성 주입 시스템이 통합되어 있 중첩 모델을 잘 처리하지 못합니다. 즉, 요청의 JSON body가 내부 필드를 가진 JSON 객체이고 그 내부 필드들이 다시 중첩된 JSON 객체인 경우, 제대로 문서화하고 검증할 수 없습니다. -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 Python 타입을 사용해 뛰어난 에디터 지원을 제공하기. @@ -271,7 +271,7 @@ Python 타입을 사용해 뛰어난 에디터 지원을 제공하기. /// -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 미친 성능을 낼 수 있는 방법을 찾기. @@ -283,11 +283,11 @@ Python 타입을 사용해 뛰어난 에디터 지원을 제공하기. Falcon은 또 다른 고성능 Python framework로, 최소한으로 설계되었고 Hug 같은 다른 framework의 기반으로 동작하도록 만들어졌습니다. -함수가 두 개의 파라미터(하나는 "request", 하나는 "response")를 받도록 설계되어 있습니다. 그런 다음 request에서 일부를 "읽고", response에 일부를 "작성"합니다. 이 설계 때문에, 표준 Python type hints를 함수 파라미터로 사용해 요청 파라미터와 body를 선언하는 것이 불가능합니다. +함수가 두 개의 파라미터(하나는 "요청", 하나는 "응답")를 받도록 설계되어 있습니다. 그런 다음 요청에서 일부를 "읽고", 응답에 일부를 "작성"합니다. 이 설계 때문에, 표준 Python type hints를 함수 파라미터로 사용해 요청 파라미터와 body를 선언하는 것이 불가능합니다. -따라서 데이터 검증, serialization, 문서화는 자동으로 되지 않고 코드로 해야 합니다. 또는 Hug처럼 Falcon 위에 framework를 얹어 구현해야 합니다. request 객체 하나와 response 객체 하나를 파라미터로 받는 Falcon의 설계에서 영감을 받은 다른 framework에서도 같은 구분이 나타납니다. +따라서 데이터 검증, serialization, 문서화는 자동으로 되지 않고 코드로 해야 합니다. 또는 Hug처럼 Falcon 위에 framework를 얹어 구현해야 합니다. 요청 객체 하나와 응답 객체 하나를 파라미터로 받는 Falcon의 설계에서 영감을 받은 다른 framework에서도 같은 구분이 나타납니다. -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 훌륭한 성능을 얻는 방법을 찾기. @@ -313,7 +313,7 @@ Pydantic 같은 서드파티 라이브러리를 사용해 데이터 검증/seria Route는 한 곳에서 선언하고, 다른 곳에 선언된 함수를 사용합니다(엔드포인트를 처리하는 함수 바로 위에 둘 수 있는 decorator를 사용하는 대신). 이는 Flask(및 Starlette)보다는 Django 방식에 가깝습니다. 코드에서 상대적으로 강하게 결합된 것들을 분리해 놓습니다. -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 모델 속성의 "default" 값으로 데이터 타입에 대한 추가 검증을 정의하기. 이는 에디터 지원을 개선하며, 이전에는 Pydantic에 없었습니다. @@ -335,13 +335,13 @@ OpenAPI나 JSON Schema 같은 표준을 기반으로 하지 않았기 때문에 동기식 Python 웹 framework의 이전 표준(WSGI) 기반이어서 Websockets와 다른 것들을 처리할 수는 없지만, 성능은 여전히 높습니다. -/// info | 정보 +/// note | 참고 Hug는 Timothy Crosley가 만들었습니다. Python 파일에서 import를 자동으로 정렬하는 훌륭한 도구인 [`isort`](https://github.com/timothycrosley/isort)의 제작자이기도 합니다. /// -/// check | **FastAPI**에 영감을 준 아이디어들 +/// tip | **FastAPI**에 영감을 준 아이디어 Hug는 APIStar의 일부에 영감을 주었고, 저는 APIStar와 함께 Hug를 가장 유망한 도구 중 하나로 보았습니다. @@ -375,7 +375,7 @@ Body schema 정의는 Pydantic처럼 동일한 Python type hints를 사용하지 이제 APIStar는 web framework가 아니라 OpenAPI 사양을 검증하기 위한 도구 모음입니다. -/// info | 정보 +/// note | 참고 APIStar는 Tom Christie가 만들었습니다. 다음을 만든 사람과 동일합니다: @@ -385,7 +385,7 @@ APIStar는 Tom Christie가 만들었습니다. 다음을 만든 사람과 동일 /// -/// check | **FastAPI**에 영감을 준 것 +/// tip | **FastAPI**에 영감을 준 점 존재하게 만들기. @@ -409,7 +409,7 @@ Pydantic은 Python type hints를 기반으로 데이터 검증, serialization, Marshmallow와 비교할 수 있습니다. 다만 benchmark에서 Marshmallow보다 빠릅니다. 그리고 동일한 Python type hints를 기반으로 하므로 에디터 지원도 훌륭합니다. -/// check | **FastAPI**가 이를 사용하는 목적 +/// tip | **FastAPI**는 이를 사용해 모든 데이터 검증, 데이터 serialization, 자동 모델 문서화(JSON Schema 기반)를 처리하기. @@ -430,7 +430,7 @@ Starlette는 경량 -/// info | 정보 +/// note | 참고 아름다운 일러스트: [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨 @@ -205,7 +206,7 @@ def results(): 대부분의 시간을 카운터 앞에서 기다리는 데 🕙 썼기 때문에, 대화하거나 작업을 걸 시간은 많지 않았습니다. 😞 -/// info | 정보 +/// note | 참고 아름다운 일러스트: [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot). 🎨 diff --git a/docs/ko/docs/deployment/cloud.md b/docs/ko/docs/deployment/cloud.md index 9d9dc93a3..106a9ec3a 100644 --- a/docs/ko/docs/deployment/cloud.md +++ b/docs/ko/docs/deployment/cloud.md @@ -10,13 +10,13 @@ 최소한의 노력으로 API를 **구축**, **배포**, **접근**하는 과정을 간소화합니다. -FastAPI로 앱을 빌드할 때의 동일한 **개발자 경험**을 클라우드에 **배포**하는 데에도 제공합니다. 🎉 +FastAPI로 애플리케이션을 빌드할 때의 동일한 **개발자 경험**을 클라우드에 **배포**하는 데에도 제공합니다. 🎉 FastAPI Cloud는 *FastAPI and friends* 오픈 소스 프로젝트의 주요 후원자이자 자금 제공자입니다. ✨ ## 클라우드 제공업체 - 후원자들 { #cloud-providers-sponsors } -다른 몇몇 클라우드 제공업체들도 ✨ [**FastAPI를 후원합니다**](../help-fastapi.md#sponsor-the-author) ✨. 🙇 +다른 몇몇 클라우드 제공업체들도 ✨ [**FastAPI를 후원합니다**](https://github.com/sponsors/tiangolo) ✨. 🙇 가이드를 따라 하고 서비스를 사용해보기 위해 이들도 고려해볼 수 있습니다: diff --git a/docs/ko/docs/deployment/concepts.md b/docs/ko/docs/deployment/concepts.md index a5c5e53e0..0bfd9dbad 100644 --- a/docs/ko/docs/deployment/concepts.md +++ b/docs/ko/docs/deployment/concepts.md @@ -104,7 +104,7 @@ TLS Termination Proxy로 사용할 수 있는 도구는 예를 들어 다음과 ### 시작 시 자동 실행 { #run-automatically-on-startup } -일반적으로 서버 프로그램(예: Uvicorn)은 서버가 시작될 때 자동으로 시작되고, **사람의 개입** 없이도 FastAPI 앱을 실행하는 프로세스가 항상 실행 중이도록(예: FastAPI 앱을 실행하는 Uvicorn) 구성하고 싶을 것입니다. +일반적으로 서버 프로그램(예: Uvicorn)은 서버가 시작될 때 자동으로 시작되고, **사람의 개입** 없이도 FastAPI 애플리케이션을 실행하는 프로세스가 항상 실행 중이도록(예: FastAPI 애플리케이션을 실행하는 Uvicorn) 구성하고 싶을 것입니다. ### 별도의 프로그램 { #separate-program } @@ -159,7 +159,7 @@ FastAPI로 웹 API를 만들 때 코드에 오류가 있으면, FastAPI는 보 /// -애플리케이션을 재시작하는 역할은 **외부 컴포넌트**가 맡는 편이 보통 좋습니다. 그 시점에는 Uvicorn과 Python을 포함한 애플리케이션이 이미 크래시했기 때문에, 같은 앱의 같은 코드 안에서 이를 해결할 방법이 없기 때문입니다. +애플리케이션을 재시작하는 역할은 **외부 컴포넌트**가 맡는 편이 보통 좋습니다. 그 시점에는 Uvicorn과 Python을 포함한 애플리케이션이 이미 크래시했기 때문에, 같은 애플리케이션의 같은 코드 안에서 이를 해결할 방법이 없기 때문입니다. ### 자동 재시작을 위한 도구 예시 { #example-tools-to-restart-automatically } @@ -243,7 +243,7 @@ FastAPI 애플리케이션은 Uvicorn을 실행하는 `fastapi` 명령 같은 **컨테이너**, Docker, Kubernetes에 대한 일부 내용이 아직은 잘 이해되지 않아도 괜찮습니다. -다음 장에서 컨테이너 이미지, Docker, Kubernetes 등을 더 설명하겠습니다: [컨테이너에서 FastAPI - Docker](docker.md). +향후 장에서 컨테이너 이미지, Docker, Kubernetes 등을 더 설명하겠습니다: [컨테이너에서 FastAPI - Docker](docker.md). /// @@ -275,13 +275,13 @@ FastAPI 애플리케이션은 Uvicorn을 실행하는 `fastapi` 명령 같은 가능한 아이디어는 다음과 같습니다: -* 앱 컨테이너보다 먼저 실행되는 Kubernetes의 “Init Container” +* 애플리케이션 컨테이너보다 먼저 실행되는 Kubernetes의 “Init Container” * 사전 단계를 실행한 다음 애플리케이션을 시작하는 bash 스크립트 * 이 bash 스크립트를 시작/재시작하고, 오류를 감지하는 등의 방법도 여전히 필요합니다. /// tip | 팁 -컨테이너로 이를 처리하는 더 구체적인 예시는 다음 장에서 제공하겠습니다: [컨테이너에서 FastAPI - Docker](docker.md). +컨테이너로 이를 처리하는 더 구체적인 예시는 향후 장에서 제공하겠습니다: [컨테이너에서 FastAPI - Docker](docker.md). /// diff --git a/docs/ko/docs/deployment/docker.md b/docs/ko/docs/deployment/docker.md index d965af1d1..db166bf24 100644 --- a/docs/ko/docs/deployment/docker.md +++ b/docs/ko/docs/deployment/docker.md @@ -11,7 +11,7 @@ FastAPI 애플리케이션을 배포할 때 일반적인 접근 방법은 **리 ///
-Dockerfile Preview 👀 +Dockerfile 미리보기 👀 ```Dockerfile FROM python:3.14 @@ -26,7 +26,7 @@ COPY ./app /code/app CMD ["fastapi", "run", "app/main.py", "--port", "80"] -# If running behind a proxy like Nginx or Traefik add --proxy-headers +# Nginx나 Traefik 같은 프록시 뒤에서 실행한다면 --proxy-headers를 추가하세요 # CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"] ``` @@ -46,7 +46,7 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"] **컨테이너**는 **컨테이너 이미지**에서 실행됩니다. -컨테이너 이미지는 컨테이너에 있어야 하는 모든 파일, 환경 변수, 기본 명령/프로그램의 **정적** 버전입니다. 여기서 **정적**이라는 것은 컨테이너 **이미지**가 실행 중이거나 수행되는 것이 아니라, 패키징된 파일과 메타데이터일 뿐이라는 뜻입니다. +컨테이너 이미지는 컨테이너에 있어야 하는 모든 파일, 환경 변수, 기본 명령어/프로그램의 **정적** 버전입니다. 여기서 **정적**이라는 것은 컨테이너 **이미지**가 실행 중이거나 수행되는 것이 아니라, 패키징된 파일과 메타데이터일 뿐이라는 뜻입니다. 저장된 정적 콘텐츠인 "**컨테이너 이미지**"와 달리, "**컨테이너**"는 보통 실행 중인 인스턴스, 즉 **실행되는** 대상을 의미합니다. @@ -62,7 +62,7 @@ Docker는 **컨테이너 이미지**와 **컨테이너**를 생성하고 관리 또한 [Docker Hub](https://hub.docker.com/)에는 다양한 도구, 환경, 데이터베이스, 애플리케이션을 위한 미리 만들어진 **공식 컨테이너 이미지**가 공개되어 있습니다. -예를 들어, 공식 [Python Image](https://hub.docker.com/_/python)가 있습니다. +예를 들어, 공식 [Python 이미지](https://hub.docker.com/_/python)가 있습니다. 그리고 데이터베이스 등 다양한 용도의 다른 이미지도 많이 있습니다. 예를 들면: @@ -81,11 +81,11 @@ Docker나 Kubernetes 같은 모든 컨테이너 관리 시스템에는 이러한 ## 컨테이너와 프로세스 { #containers-and-processes } -**컨테이너 이미지**는 보통 **컨테이너**가 시작될 때 실행되어야 하는 기본 프로그램/명령과 해당 프로그램에 전달할 매개변수를 메타데이터에 포함합니다. 커맨드 라인에서 실행할 때와 매우 유사합니다. +**컨테이너 이미지**는 보통 **컨테이너**가 시작될 때 실행되어야 하는 기본 프로그램/명령어와 해당 프로그램에 전달할 매개변수를 메타데이터에 포함합니다. 커맨드 라인에서 실행할 때와 매우 유사합니다. -**컨테이너**가 시작되면 해당 명령/프로그램을 실행합니다(다만 오버라이드하여 다른 명령/프로그램을 실행하게 할 수도 있습니다). +**컨테이너**가 시작되면 해당 명령어/프로그램을 실행합니다(다만 오버라이드하여 다른 명령어/프로그램을 실행하게 할 수도 있습니다). -컨테이너는 **메인 프로세스**(명령 또는 프로그램)가 실행되는 동안 실행됩니다. +컨테이너는 **메인 프로세스**(명령어 또는 프로그램)가 실행되는 동안 실행됩니다. 컨테이너는 보통 **단일 프로세스**를 가지지만, 메인 프로세스에서 서브프로세스를 시작할 수도 있으며, 그러면 같은 컨테이너에 **여러 프로세스**가 존재하게 됩니다. @@ -132,7 +132,7 @@ Successfully installed fastapi pydantic
-/// info | 정보 +/// note | 참고 패키지 의존성을 정의하고 설치하는 다른 형식과 도구도 있습니다. @@ -218,11 +218,11 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80"] 따라서 컨테이너 이미지 빌드 시간을 최적화하려면 `Dockerfile`의 **끝부분 근처**에 두는 것이 중요합니다. -6. 내부적으로 Uvicorn을 사용하는 `fastapi run`을 사용하도록 **명령**을 설정합니다. +6. 내부적으로 Uvicorn을 사용하는 `fastapi run`을 사용하도록 **명령어**를 설정합니다. `CMD`는 문자열 리스트를 받으며, 각 문자열은 커맨드 라인에서 공백으로 구분해 입력하는 항목들입니다. - 이 명령은 **현재 작업 디렉터리**에서 실행되며, 이는 위에서 `WORKDIR /code`로 설정한 `/code` 디렉터리와 같습니다. + 이 명령어는 **현재 작업 디렉터리**에서 실행되며, 이는 위에서 `WORKDIR /code`로 설정한 `/code` 디렉터리와 같습니다. /// tip | 팁 @@ -258,7 +258,7 @@ FastAPI가 정상적으로 종료(graceful shutdown)되고 [lifespan 이벤트]( 자세한 내용은 [shell and exec form에 대한 Docker 문서](https://docs.docker.com/reference/dockerfile/#shell-and-exec-form)를 참고하세요. -이는 `docker compose`를 사용할 때 꽤 눈에 띌 수 있습니다. 좀 더 기술적인 상세 내용은 Docker Compose FAQ 섹션을 참고하세요: [Why do my services take 10 seconds to recreate or stop?](https://docs.docker.com/compose/faq/#why-do-my-services-take-10-seconds-to-recreate-or-stop). +이는 `docker compose`를 사용할 때 꽤 눈에 띌 수 있습니다. 좀 더 기술적인 상세 내용은 Docker Compose FAQ 섹션을 참고하세요: [왜 내 서비스는 다시 생성되거나 중지되는 데 10초가 걸리나요?](https://docs.docker.com/compose/faq/#why-do-my-services-take-10-seconds-to-recreate-or-stop). #### 디렉터리 구조 { #directory-structure } @@ -409,7 +409,7 @@ CMD ["fastapi", "run", "main.py", "--port", "80"] 2. 단일 파일 `main.py`에 있는 애플리케이션을 제공(serve)하기 위해 `fastapi run`을 사용합니다. -`fastapi run`에 파일을 전달하면, 이것이 패키지의 일부가 아닌 단일 파일이라는 것을 자동으로 감지하고, 어떻게 임포트해서 FastAPI 앱을 제공할지 알아냅니다. 😎 +`fastapi run`에 파일을 전달하면, 이것이 패키지의 일부가 아닌 단일 파일이라는 것을 자동으로 감지하고, 어떻게 임포트해서 FastAPI 애플리케이션을 제공할지 알아냅니다. 😎 ## 배포 개념 { #deployment-concepts } @@ -472,17 +472,17 @@ HTTPS에 사용되는 동일한 **TLS 종료 프록시** 컴포넌트가 **로 /// -또한 컨테이너로 작업할 때, 이를 시작하고 관리하는 시스템은 이미 해당 **로드 밸런서**(또는 **TLS 종료 프록시**)에서 여러분의 앱이 있는 컨테이너로 **네트워크 통신**(예: HTTP 요청)을 전달하는 내부 도구를 가지고 있습니다. +또한 컨테이너로 작업할 때, 이를 시작하고 관리하는 시스템은 이미 해당 **로드 밸런서**(또는 **TLS 종료 프록시**)에서 여러분의 애플리케이션이 있는 컨테이너로 **네트워크 통신**(예: HTTP 요청)을 전달하는 내부 도구를 가지고 있습니다. ### 하나의 로드 밸런서 - 여러 워커 컨테이너 { #one-load-balancer-multiple-worker-containers } -**Kubernetes** 같은 분산 컨테이너 관리 시스템에서는 내부 네트워킹 메커니즘을 통해, 메인 **포트**에서 대기하는 단일 **로드 밸런서**가 여러분의 앱을 실행하는 **여러 컨테이너**로 통신(요청)을 전달할 수 있습니다. +**Kubernetes** 같은 분산 컨테이너 관리 시스템에서는 내부 네트워킹 메커니즘을 통해, 메인 **포트**에서 대기하는 단일 **로드 밸런서**가 여러분의 애플리케이션을 실행하는 **여러 컨테이너**로 통신(요청)을 전달할 수 있습니다. -앱을 실행하는 각 컨테이너는 보통 **프로세스 하나만** 가집니다(예: FastAPI 애플리케이션을 실행하는 Uvicorn 프로세스). 모두 같은 것을 실행하는 **동일한 컨테이너**이지만, 각자 고유한 프로세스, 메모리 등을 가집니다. 이렇게 하면 CPU의 **서로 다른 코어** 또는 **서로 다른 머신**에서 **병렬화**의 이점을 얻을 수 있습니다. +애플리케이션을 실행하는 각 컨테이너는 보통 **프로세스 하나만** 가집니다(예: FastAPI 애플리케이션을 실행하는 Uvicorn 프로세스). 모두 같은 것을 실행하는 **동일한 컨테이너**이지만, 각자 고유한 프로세스, 메모리 등을 가집니다. 이렇게 하면 CPU의 **서로 다른 코어** 또는 **서로 다른 머신**에서 **병렬화**의 이점을 얻을 수 있습니다. -그리고 **로드 밸런서**가 있는 분산 컨테이너 시스템은 여러분의 앱을 실행하는 각 컨테이너에 **번갈아가며** 요청을 **분산**합니다. 따라서 각 요청은 여러분의 앱을 실행하는 여러 **복제된 컨테이너** 중 하나에서 처리될 수 있습니다. +그리고 **로드 밸런서**가 있는 분산 컨테이너 시스템은 여러분의 애플리케이션을 실행하는 각 컨테이너에 **번갈아가며** 요청을 **분산**합니다. 따라서 각 요청은 여러분의 애플리케이션을 실행하는 여러 **복제된 컨테이너** 중 하나에서 처리될 수 있습니다. -또한 보통 이 **로드 밸런서**는 클러스터 내 *다른* 앱으로 가는 요청(예: 다른 도메인, 또는 다른 URL 경로 접두사 아래로 가는 요청)도 처리할 수 있으며, 그 통신을 클러스터에서 실행 중인 *그 다른* 애플리케이션의 올바른 컨테이너로 전달할 수 있습니다. +또한 보통 이 **로드 밸런서**는 클러스터 내 *다른* 애플리케이션으로 가는 요청(예: 다른 도메인, 또는 다른 URL 경로 접두사 아래로 가는 요청)도 처리할 수 있으며, 그 통신을 클러스터에서 실행 중인 *그 다른* 애플리케이션의 올바른 컨테이너로 전달할 수 있습니다. ### 컨테이너당 하나의 프로세스 { #one-process-per-container } @@ -556,7 +556,7 @@ CMD ["fastapi", "run", "app/main.py", "--port", "80", "--workers", "4"] **여러 컨테이너**가 있고 각 컨테이너가 보통 **단일 프로세스**를 실행한다면(예: **Kubernetes** 클러스터), 복제된 워커 컨테이너를 실행하기 **전에**, 단일 컨테이너에서 단일 프로세스로 **시작 전 사전 단계**를 수행하는 **별도의 컨테이너**를 두고 싶을 가능성이 큽니다. -/// info | 정보 +/// note | 참고 Kubernetes를 사용한다면, 이는 아마도 [Init Container](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/)일 것입니다. @@ -566,7 +566,7 @@ Kubernetes를 사용한다면, 이는 아마도 [Init Container](https://kuberne ### 단일 컨테이너 { #single-container } -**단일 컨테이너**에서 여러 **워커 프로세스**(또는 단일 프로세스)를 시작하는 단순한 셋업이라면, 앱이 있는 프로세스를 시작하기 직전에 같은 컨테이너에서 시작 전 사전 단계를 실행할 수 있습니다. +**단일 컨테이너**에서 여러 **워커 프로세스**(또는 단일 프로세스)를 시작하는 단순한 셋업이라면, 애플리케이션이 있는 프로세스를 시작하기 직전에 같은 컨테이너에서 시작 전 사전 단계를 실행할 수 있습니다. ### 베이스 도커 이미지 { #base-docker-image } @@ -582,7 +582,7 @@ Kubernetes를 사용한다면, 이는 아마도 [Init Container](https://kuberne 이 Docker 이미지는 Uvicorn이 죽은 워커를 관리하고 재시작하는 기능을 지원하지 않던 시기에 만들어졌습니다. 그래서 Gunicorn과 Uvicorn을 함께 사용해야 했고, Gunicorn이 Uvicorn 워커 프로세스를 관리하고 재시작하도록 하기 위해 상당한 복잡성이 추가되었습니다. -하지만 이제 Uvicorn(그리고 `fastapi` 명령)은 `--workers`를 지원하므로, 베이스 도커 이미지를 사용하는 대신 직접 이미지를 빌드하지 않을 이유가 없습니다(코드 양도 사실상 거의 같습니다 😅). +하지만 이제 Uvicorn(그리고 `fastapi` 명령어)은 `--workers`를 지원하므로, 베이스 도커 이미지를 사용하는 대신 직접 이미지를 빌드하지 않을 이유가 없습니다(코드 양도 사실상 거의 같습니다 😅). /// @@ -600,7 +600,7 @@ Kubernetes를 사용한다면, 이는 아마도 [Init Container](https://kuberne ## `uv`를 사용하는 도커 이미지 { #docker-image-with-uv } -프로젝트를 설치하고 관리하기 위해 [uv](https://github.com/astral-sh/uv)를 사용한다면, [uv Docker guide](https://docs.astral.sh/uv/guides/integration/docker/)를 따를 수 있습니다. +프로젝트를 설치하고 관리하기 위해 [uv](https://github.com/astral-sh/uv)를 사용한다면, [uv Docker 가이드](https://docs.astral.sh/uv/guides/integration/docker/)를 따를 수 있습니다. ## 요약 { #recap } diff --git a/docs/ko/docs/deployment/fastapicloud.md b/docs/ko/docs/deployment/fastapicloud.md index a601f5416..5fe057f47 100644 --- a/docs/ko/docs/deployment/fastapicloud.md +++ b/docs/ko/docs/deployment/fastapicloud.md @@ -1,26 +1,6 @@ # FastAPI Cloud { #fastapi-cloud } -**한 번의 명령**으로 FastAPI 앱을 [FastAPI Cloud](https://fastapicloud.com)에 배포할 수 있습니다. 아직이라면 대기자 명단에 등록해 보세요. 🚀 - -## 로그인하기 { #login } - -먼저 **FastAPI Cloud** 계정이 이미 있는지 확인하세요(대기자 명단에서 초대해 드렸을 거예요 😉). - -그다음 로그인합니다: - -
- -```console -$ fastapi login - -You are logged in to FastAPI Cloud 🚀 -``` - -
- -## 배포하기 { #deploy } - -이제 **한 번의 명령**으로 앱을 배포합니다: +**한 번의 명령**으로 FastAPI 앱을 [FastAPI Cloud](https://fastapicloud.com)에 배포할 수 있습니다. 🚀
@@ -36,6 +16,8 @@ Deploying to FastAPI Cloud...
+CLI가 FastAPI 애플리케이션을 자동으로 감지하여 클라우드에 배포합니다. 로그인되어 있지 않다면, 인증을 완료할 수 있도록 브라우저가 자동으로 열립니다. + 이게 전부입니다! 이제 해당 URL에서 앱에 접근할 수 있습니다. ✨ ## FastAPI Cloud 소개 { #about-fastapi-cloud } diff --git a/docs/ko/docs/deployment/https.md b/docs/ko/docs/deployment/https.md index 06ac147cd..1db7dd25c 100644 --- a/docs/ko/docs/deployment/https.md +++ b/docs/ko/docs/deployment/https.md @@ -14,7 +14,7 @@ HTTPS는 그냥 “켜져 있거나” 아니면 “꺼져 있는” 것이라 이제 **개발자 관점**에서 HTTPS를 생각할 때 염두에 두어야 할 여러 가지가 있습니다: -* HTTPS를 사용하려면, **서버**가 **제3자**가 발급한 **"인증서(certificates)"**를 **보유**해야 합니다. +* HTTPS를 사용하려면, **서버**가 **제3자**가 생성한 **"인증서(certificates)"**를 **보유**해야 합니다. * 이 인증서는 실제로 '생성'되는 것이 아니라 제3자로부터 **발급/획득**하는 것입니다. * 인증서에는 **유효 기간**이 있습니다. * 즉, **만료**됩니다. diff --git a/docs/ko/docs/deployment/manually.md b/docs/ko/docs/deployment/manually.md index 719968682..fbac8169f 100644 --- a/docs/ko/docs/deployment/manually.md +++ b/docs/ko/docs/deployment/manually.md @@ -1,6 +1,6 @@ # 서버를 수동으로 실행하기 { #run-a-server-manually } -## `fastapi run` 명령 사용하기 { #use-the-fastapi-run-command } +## `fastapi run` 명령어 사용하기 { #use-the-fastapi-run-command } 요약하면, `fastapi run`을 사용해 FastAPI 애플리케이션을 서비스하세요: @@ -40,7 +40,7 @@ $ fastapi run fastapi run ASGI라고 불리는, Python 웹 프레임워크와 서버를 만들기 위한 표준을 사용합니다. FastAPI는 ASGI 웹 프레임워크입니다. -원격 서버 머신에서 **FastAPI** 애플리케이션(또는 다른 ASGI 애플리케이션)을 실행하기 위해 필요한 핵심 요소는 **Uvicorn** 같은 ASGI 서버 프로그램입니다. `fastapi` 명령에는 기본으로 이것이 포함되어 있습니다. +원격 서버 머신에서 **FastAPI** 애플리케이션(또는 다른 ASGI 애플리케이션)을 실행하기 위해 필요한 핵심 요소는 **Uvicorn** 같은 ASGI 서버 프로그램입니다. `fastapi` 명령어에는 기본으로 이것이 포함되어 있습니다. 다음을 포함해 여러 대안이 있습니다: @@ -56,7 +56,6 @@ FastAPI는 - +
**Pydantic v2**의 이 기능 덕분에 API 문서는 더 **정밀**해지고, 자동 생성된 클라이언트와 SDK가 있다면 그것들도 더 정밀해져서 더 나은 **developer experience**와 일관성을 제공할 수 있습니다. 🎉 @@ -85,7 +85,7 @@ 그런 경우에는, **FastAPI**에서 `separate_input_output_schemas=False` 파라미터로 이 기능을 비활성화할 수 있습니다. -/// info | 정보 +/// note | 참고 `separate_input_output_schemas` 지원은 FastAPI `0.102.0`에 추가되었습니다. 🤓 diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 91d27fcee..f839c82ef 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -1,3 +1,8 @@ +--- +include_yaml: + sponsors: data/sponsors.yml +--- + # FastAPI { #fastapi }