Browse Source

Merge branch 'tiangolo:master' into fix/conider-alias-in-form

pull/10319/head
ht 2 years ago
committed by GitHub
parent
commit
cbf974c06a
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      .github/actions/comment-docs-preview-in-pr/Dockerfile
  2. 2
      .github/actions/notify-translations/Dockerfile
  3. 2
      .github/actions/notify-translations/app/main.py
  4. 4
      .github/workflows/test.yml
  5. 2
      README.md
  6. 80
      docs/en/data/github_sponsors.yml
  7. 138
      docs/en/data/people.yml
  8. 5
      docs/en/data/sponsors.yml
  9. 48
      docs/en/docs/img/sponsors/bump-sh-banner.svg
  10. 56
      docs/en/docs/img/sponsors/bump-sh.svg
  11. 22
      docs/en/docs/release-notes.md
  12. 2
      docs/en/overrides/main.html
  13. 2
      docs/fr/docs/advanced/path-operation-advanced-configuration.md
  14. 2
      docs/fr/docs/alternatives.md
  15. 2
      docs/fr/docs/async.md
  16. 14
      docs/fr/docs/features.md
  17. 4
      docs/fr/docs/help-fastapi.md
  18. 4
      docs/fr/docs/index.md
  19. 2
      docs/fr/docs/python-types.md
  20. 2
      docs/fr/docs/tutorial/body.md
  21. 2
      docs/fr/docs/tutorial/first-steps.md
  22. 2
      docs/fr/docs/tutorial/query-params.md
  23. 200
      docs/ja/docs/deployment/https.md
  24. 17
      docs/ko/docs/deployment/cloud.md
  25. 2
      docs/ru/docs/tutorial/body-fields.md
  26. 42
      docs/uk/docs/tutorial/encoder.md
  27. 130
      docs/uk/docs/tutorial/extra-data-types.md
  28. 430
      docs/zh/docs/async.md
  29. 214
      docs/zh/docs/tutorial/security/simple-oauth2.md
  30. 2
      fastapi/__init__.py
  31. 14
      fastapi/_compat.py
  32. 4
      fastapi/datastructures.py
  33. 4
      fastapi/openapi/models.py
  34. 2
      tests/test_compat.py
  35. 4
      tests/test_filter_pydantic_sub_model_pv2.py
  36. 6
      tests/test_openapi_separate_input_output_schemas.py
  37. 38
      tests/test_tutorial/test_body_updates/test_tutorial001.py
  38. 38
      tests/test_tutorial/test_body_updates/test_tutorial001_py310.py
  39. 38
      tests/test_tutorial/test_body_updates/test_tutorial001_py39.py
  40. 22
      tests/test_tutorial/test_dataclasses/test_tutorial003.py
  41. 32
      tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py
  42. 32
      tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
  43. 32
      tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py
  44. 32
      tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py
  45. 4
      tests/test_tutorial/test_path_params/test_tutorial005.py
  46. 20
      tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py
  47. 20
      tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py
  48. 20
      tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py

2
.github/actions/comment-docs-preview-in-pr/Dockerfile

@ -1,4 +1,4 @@
FROM python:3.7
FROM python:3.9
RUN pip install httpx "pydantic==1.5.1" pygithub

2
.github/actions/notify-translations/Dockerfile

@ -1,4 +1,4 @@
FROM python:3.7
FROM python:3.9
RUN pip install httpx PyGithub "pydantic==1.5.1" "pyyaml>=5.3.1,<6.0.0"

2
.github/actions/notify-translations/app/main.py

@ -9,7 +9,7 @@ import httpx
from github import Github
from pydantic import BaseModel, BaseSettings, SecretStr
awaiting_label = "awaiting review"
awaiting_label = "awaiting-review"
lang_all_label = "lang-all"
approved_label = "approved-2"
translations_path = Path(__file__).parent / "translations.yml"

4
.github/workflows/test.yml

@ -29,7 +29,7 @@ jobs:
id: cache
with:
path: ${{ env.pythonLocation }}
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt') }}-test-v05
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt') }}-test-v06
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-tests.txt
@ -62,7 +62,7 @@ jobs:
id: cache
with:
path: ${{ env.pythonLocation }}
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt') }}-test-v05
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt') }}-test-v06
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: pip install -r requirements-tests.txt

2
README.md

@ -50,7 +50,7 @@ The key features are:
<a href="https://platform.sh/try-it-now/?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023" target="_blank" title="Build, run and scale your apps on a modern, reliable, and secure PaaS."><img src="https://fastapi.tiangolo.com/img/sponsors/platform-sh.png"></a>
<a href="https://www.buildwithfern.com/?utm_source=tiangolo&utm_medium=website&utm_campaign=main-badge" target="_blank" title="Fern | SDKs and API docs"><img src="https://fastapi.tiangolo.com/img/sponsors/fern.svg"></a>
<a href="https://www.porter.run" target="_blank" title="Deploy FastAPI on AWS with a few clicks"><img src="https://fastapi.tiangolo.com/img/sponsors/porter.png"></a>
<a href="https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor" target="_blank" title="Automate FastAPI documentation generation with Bump.sh"><img src="https://fastapi.tiangolo.com/img/sponsors/bump-sh.png"></a>
<a href="https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor" target="_blank" title="Automate FastAPI documentation generation with Bump.sh"><img src="https://fastapi.tiangolo.com/img/sponsors/bump-sh.svg"></a>
<a href="https://www.deta.sh/?ref=fastapi" target="_blank" title="The launchpad for all your (team's) ideas"><img src="https://fastapi.tiangolo.com/img/sponsors/deta.svg"></a>
<a href="https://training.talkpython.fm/fastapi-courses" target="_blank" title="FastAPI video courses on demand from people you trust"><img src="https://fastapi.tiangolo.com/img/sponsors/talkpython.png"></a>
<a href="https://testdriven.io/courses/tdd-fastapi/" target="_blank" title="Learn to build high-quality web apps with best practices"><img src="https://fastapi.tiangolo.com/img/sponsors/testdriven.svg"></a>

80
docs/en/data/github_sponsors.yml

@ -1,5 +1,8 @@
sponsors:
- - login: cryptapi
- - login: bump-sh
avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4
url: https://github.com/bump-sh
- login: cryptapi
avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4
url: https://github.com/cryptapi
- login: porter-dev
@ -29,15 +32,15 @@ sponsors:
- login: deepset-ai
avatarUrl: https://avatars.githubusercontent.com/u/51827949?v=4
url: https://github.com/deepset-ai
- login: svix
avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4
url: https://github.com/svix
- login: databento-bot
avatarUrl: https://avatars.githubusercontent.com/u/98378480?u=494f679996e39427f7ddb1a7de8441b7c96fb670&v=4
url: https://github.com/databento-bot
- login: VincentParedes
avatarUrl: https://avatars.githubusercontent.com/u/103889729?v=4
url: https://github.com/VincentParedes
- - login: getsentry
avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4
url: https://github.com/getsentry
- - login: acsone
avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4
url: https://github.com/acsone
@ -50,9 +53,6 @@ sponsors:
- login: marvin-robot
avatarUrl: https://avatars.githubusercontent.com/u/41086007?u=091c5cb75af363123d66f58194805a97220ee1a7&v=4
url: https://github.com/marvin-robot
- login: Flint-company
avatarUrl: https://avatars.githubusercontent.com/u/48908872?u=355cd3d8992d4be8173058e7000728757c55ad49&v=4
url: https://github.com/Flint-company
- login: BoostryJP
avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4
url: https://github.com/BoostryJP
@ -77,9 +77,6 @@ sponsors:
- login: AccentDesign
avatarUrl: https://avatars.githubusercontent.com/u/2429332?v=4
url: https://github.com/AccentDesign
- login: RodneyU215
avatarUrl: https://avatars.githubusercontent.com/u/3329665?u=ec6a9adf8e7e8e306eed7d49687c398608d1604f&v=4
url: https://github.com/RodneyU215
- login: americanair
avatarUrl: https://avatars.githubusercontent.com/u/12281813?v=4
url: https://github.com/americanair
@ -89,16 +86,10 @@ sponsors:
- - login: povilasb
avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4
url: https://github.com/povilasb
- login: mukulmantosh
avatarUrl: https://avatars.githubusercontent.com/u/15572034?u=006f0a33c0e15bb2de57474a2cf7d2f8ee05f5a0&v=4
url: https://github.com/mukulmantosh
- login: primer-io
avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4
url: https://github.com/primer-io
- - login: indeedeng
avatarUrl: https://avatars.githubusercontent.com/u/2905043?v=4
url: https://github.com/indeedeng
- login: NateXVI
- - login: NateXVI
avatarUrl: https://avatars.githubusercontent.com/u/48195620?u=4bc8751ae50cb087c40c1fe811764aa070b9eea6&v=4
url: https://github.com/NateXVI
- - login: Kludex
@ -113,9 +104,6 @@ sponsors:
- login: jstanden
avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4
url: https://github.com/jstanden
- login: dekoza
avatarUrl: https://avatars.githubusercontent.com/u/210980?u=c03c78a8ae1039b500dfe343665536ebc51979b2&v=4
url: https://github.com/dekoza
- login: pamelafox
avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4
url: https://github.com/pamelafox
@ -143,9 +131,6 @@ sponsors:
- login: mickaelandrieu
avatarUrl: https://avatars.githubusercontent.com/u/1247388?u=599f6e73e452a9453f2bd91e5c3100750e731ad4&v=4
url: https://github.com/mickaelandrieu
- login: jonakoudijs
avatarUrl: https://avatars.githubusercontent.com/u/1906344?u=5ca0c9a1a89b6a2ba31abe35c66bdc07af60a632&v=4
url: https://github.com/jonakoudijs
- login: Shark009
avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4
url: https://github.com/Shark009
@ -227,6 +212,9 @@ sponsors:
- login: Filimoa
avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4
url: https://github.com/Filimoa
- login: rahulsalgare
avatarUrl: https://avatars.githubusercontent.com/u/21974430?u=ade6f182b94554ab8491d7421de5e78f711dcaf8&v=4
url: https://github.com/rahulsalgare
- login: BrettskiPy
avatarUrl: https://avatars.githubusercontent.com/u/30988215?u=d8a94a67e140d5ee5427724b292cc52d8827087a&v=4
url: https://github.com/BrettskiPy
@ -245,9 +233,6 @@ sponsors:
- login: ProteinQure
avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4
url: https://github.com/ProteinQure
- login: askurihin
avatarUrl: https://avatars.githubusercontent.com/u/37978981?v=4
url: https://github.com/askurihin
- login: arleybri18
avatarUrl: https://avatars.githubusercontent.com/u/39681546?u=5c028f81324b0e8c73b3c15bc4e7b0218d2ba0c3&v=4
url: https://github.com/arleybri18
@ -266,27 +251,18 @@ sponsors:
- login: dudikbender
avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4
url: https://github.com/dudikbender
- login: thisistheplace
avatarUrl: https://avatars.githubusercontent.com/u/57633545?u=a3f3a7f8ace8511c6c067753f6eb6aee0db11ac6&v=4
url: https://github.com/thisistheplace
- login: yakkonaut
avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4
url: https://github.com/yakkonaut
- login: patsatsia
avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4
url: https://github.com/patsatsia
- login: daverin
avatarUrl: https://avatars.githubusercontent.com/u/70378377?u=6d1814195c0de7162820eaad95a25b423a3869c0&v=4
url: https://github.com/daverin
- login: anthonycepeda
avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=4252c6b6dc5024af502a823a3ac5e7a03a69963f&v=4
url: https://github.com/anthonycepeda
- login: DelfinaCare
avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4
url: https://github.com/DelfinaCare
- login: hbakri
avatarUrl: https://avatars.githubusercontent.com/u/92298226?u=36eee6d75db1272264d3ee92f1871f70b8917bd8&v=4
url: https://github.com/hbakri
- login: osawa-koki
avatarUrl: https://avatars.githubusercontent.com/u/94336223?u=59c6fe6945bcbbaff87b2a794238671b060620d2&v=4
url: https://github.com/osawa-koki
@ -305,6 +281,9 @@ sponsors:
- login: bryanculbertson
avatarUrl: https://avatars.githubusercontent.com/u/144028?u=defda4f90e93429221cc667500944abde60ebe4a&v=4
url: https://github.com/bryanculbertson
- login: yourkin
avatarUrl: https://avatars.githubusercontent.com/u/178984?u=b43a7e5f8818f7d9083d3b110118d9c27d48a794&v=4
url: https://github.com/yourkin
- login: slafs
avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4
url: https://github.com/slafs
@ -320,9 +299,6 @@ sponsors:
- login: securancy
avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4
url: https://github.com/securancy
- login: hardbyte
avatarUrl: https://avatars.githubusercontent.com/u/855189?u=aa29e92f34708814d6b67fcd47ca4cf2ce1c04ed&v=4
url: https://github.com/hardbyte
- login: browniebroke
avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4
url: https://github.com/browniebroke
@ -423,7 +399,7 @@ sponsors:
avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4
url: https://github.com/jangia
- login: timzaz
avatarUrl: https://avatars.githubusercontent.com/u/19709244?u=e6658f6b0b188294ce2db20dad94a678fcea718d&v=4
avatarUrl: https://avatars.githubusercontent.com/u/19709244?u=264d7db95c28156363760229c30ee1116efd4eeb&v=4
url: https://github.com/timzaz
- login: shuheng-liu
avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4
@ -443,6 +419,9 @@ sponsors:
- login: joerambo
avatarUrl: https://avatars.githubusercontent.com/u/26282974?v=4
url: https://github.com/joerambo
- login: msniezynski
avatarUrl: https://avatars.githubusercontent.com/u/27588547?u=0e3be5ac57dcfdf124f470bcdf74b5bf79af1b6c&v=4
url: https://github.com/msniezynski
- login: rlnchow
avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4
url: https://github.com/rlnchow
@ -464,6 +443,12 @@ sponsors:
- login: miraedbswo
avatarUrl: https://avatars.githubusercontent.com/u/36796047?u=9e7a5b3e558edc61d35d0f9dfac37541bae7f56d&v=4
url: https://github.com/miraedbswo
- login: DSMilestone6538
avatarUrl: https://avatars.githubusercontent.com/u/37230924?u=f299dce910366471523155e0cb213356d34aadc1&v=4
url: https://github.com/DSMilestone6538
- login: curegit
avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4
url: https://github.com/curegit
- login: kristiangronberg
avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4
url: https://github.com/kristiangronberg
@ -491,11 +476,8 @@ sponsors:
- login: romabozhanovgithub
avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4
url: https://github.com/romabozhanovgithub
- login: mnicolleUTC
avatarUrl: https://avatars.githubusercontent.com/u/68548924?u=1fdd7f436bb1f4857c3415e62aa8fbc055fc1a76&v=4
url: https://github.com/mnicolleUTC
- login: mbukeRepo
avatarUrl: https://avatars.githubusercontent.com/u/70356088?u=e125069c6ac5c49355e2b3ca2aa66a445fc4cccd&v=4
avatarUrl: https://avatars.githubusercontent.com/u/70356088?u=d2eb23e2b222a3b316c4183b05a3236b32819dc2&v=4
url: https://github.com/mbukeRepo
- - login: ssbarnea
avatarUrl: https://avatars.githubusercontent.com/u/102495?u=b4bf6818deefe59952ac22fec6ed8c76de1b8f7c&v=4
@ -515,12 +497,12 @@ sponsors:
- login: danburonline
avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=2cad4388c1544e539ecb732d656e42fb07b4ff2d&v=4
url: https://github.com/danburonline
- login: koalawangyang
avatarUrl: https://avatars.githubusercontent.com/u/40114367?u=3bb94010f0473b8d4c2edea5a8c1cab61e6a1b22&v=4
url: https://github.com/koalawangyang
- login: rwxd
avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4
url: https://github.com/rwxd
- login: lodine-software
avatarUrl: https://avatars.githubusercontent.com/u/133536046?v=4
url: https://github.com/lodine-software
- login: shywn-mrk
avatarUrl: https://avatars.githubusercontent.com/u/51455763?u=389e2608e4056fe5e1f23e9ad56a9415277504d3&v=4
url: https://github.com/shywn-mrk
- login: almeida-matheus
avatarUrl: https://avatars.githubusercontent.com/u/66216198?u=54335eaa0ced626be5c1ff52fead1ebc032286ec&v=4
url: https://github.com/almeida-matheus

138
docs/en/data/people.yml

@ -1,12 +1,12 @@
maintainers:
- login: tiangolo
answers: 1866
prs: 486
answers: 1868
prs: 496
avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4
url: https://github.com/tiangolo
experts:
- login: Kludex
count: 480
count: 501
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
- login: dmontagu
@ -26,7 +26,7 @@ experts:
avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4
url: https://github.com/JarroVGIT
- login: jgould22
count: 164
count: 168
avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4
url: https://github.com/jgould22
- login: euri10
@ -61,10 +61,10 @@ experts:
count: 49
avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4
url: https://github.com/sm-Fifteen
- login: yinziyan1206
- login: acidjunk
count: 45
avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4
url: https://github.com/yinziyan1206
avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4
url: https://github.com/acidjunk
- login: insomnes
count: 45
avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4
@ -73,14 +73,14 @@ experts:
count: 45
avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4
url: https://github.com/Dustyposa
- login: acidjunk
count: 45
avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4
url: https://github.com/acidjunk
- login: adriangb
count: 44
count: 45
avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4
url: https://github.com/adriangb
- login: yinziyan1206
count: 44
avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4
url: https://github.com/yinziyan1206
- login: odiseo0
count: 43
avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4
@ -93,18 +93,22 @@ experts:
count: 40
avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4
url: https://github.com/includeamin
- login: chbndrhnns
count: 38
avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4
url: https://github.com/chbndrhnns
- login: STeveShary
count: 37
avatarUrl: https://avatars.githubusercontent.com/u/5167622?u=de8f597c81d6336fcebc37b32dfd61a3f877160c&v=4
url: https://github.com/STeveShary
- login: chbndrhnns
count: 36
avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4
url: https://github.com/chbndrhnns
- login: krishnardt
count: 35
avatarUrl: https://avatars.githubusercontent.com/u/31960541?u=47f4829c77f4962ab437ffb7995951e41eeebe9b&v=4
url: https://github.com/krishnardt
- login: n8sty
count: 32
avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4
url: https://github.com/n8sty
- login: panla
count: 32
avatarUrl: https://avatars.githubusercontent.com/u/41326348?u=ba2fda6b30110411ecbf406d187907e2b420ac19&v=4
@ -117,10 +121,6 @@ experts:
count: 26
avatarUrl: https://avatars.githubusercontent.com/u/43723790?u=9bcce836bbce55835291c5b2ac93a4e311f4b3c3&v=4
url: https://github.com/dbanty
- login: n8sty
count: 25
avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4
url: https://github.com/n8sty
- login: wshayes
count: 25
avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4
@ -149,6 +149,10 @@ experts:
count: 20
avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4
url: https://github.com/chris-allnutt
- login: chrisK824
count: 19
avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4
url: https://github.com/chrisK824
- login: zoliknemet
count: 18
avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4
@ -157,6 +161,10 @@ experts:
count: 18
avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4
url: https://github.com/retnikt
- login: ebottos94
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4
url: https://github.com/ebottos94
- login: Hultner
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4
@ -173,55 +181,39 @@ experts:
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4
url: https://github.com/caeser1996
- login: nymous
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4
url: https://github.com/nymous
- login: jonatasoli
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4
url: https://github.com/jonatasoli
- login: ebottos94
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4
url: https://github.com/ebottos94
- login: dstlny
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4
url: https://github.com/dstlny
- login: chrisK824
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4
url: https://github.com/chrisK824
- login: nymous
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4
url: https://github.com/nymous
- login: abhint
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4
url: https://github.com/abhint
last_month_active:
- login: JavierSanchezCastro
count: 12
avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4
url: https://github.com/JavierSanchezCastro
- login: Kludex
count: 10
count: 8
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
- login: jgould22
count: 8
avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4
url: https://github.com/jgould22
- login: romabozhanovgithub
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4
url: https://github.com/romabozhanovgithub
- login: n8sty
count: 5
count: 7
avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4
url: https://github.com/n8sty
- login: chrisK824
count: 3
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4
url: https://github.com/chrisK824
- login: danielfcollier
count: 3
avatarUrl: https://avatars.githubusercontent.com/u/38995330?u=5799be795fc310f75f3a5fe9242307d59b194520&v=4
url: https://github.com/danielfcollier
top_contributors:
- login: waynerv
count: 25
@ -235,14 +227,14 @@ top_contributors:
count: 21
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
- login: jaystone776
count: 18
avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4
url: https://github.com/jaystone776
- login: dmontagu
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4
url: https://github.com/dmontagu
- login: jaystone776
count: 17
avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4
url: https://github.com/jaystone776
- login: Xewus
count: 14
avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4
@ -307,6 +299,10 @@ top_contributors:
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4
url: https://github.com/ComicShrimp
- login: tamtam-fitness
count: 5
avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4
url: https://github.com/tamtam-fitness
- login: jekirl
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/2546697?u=a027452387d85bd4a14834e19d716c99255fb3b7&v=4
@ -347,21 +343,25 @@ top_contributors:
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4
url: https://github.com/ivan-abc
- login: rostik1410
count: 4
avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4
url: https://github.com/rostik1410
top_reviewers:
- login: Kludex
count: 136
count: 139
avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4
url: https://github.com/Kludex
- login: yezz123
count: 80
avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4
url: https://github.com/yezz123
- login: BilalAlpaslan
count: 79
avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4
url: https://github.com/BilalAlpaslan
- login: yezz123
count: 78
avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4
url: https://github.com/yezz123
- login: iudeen
count: 53
count: 54
avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4
url: https://github.com/iudeen
- login: tokusumi
@ -380,14 +380,14 @@ top_reviewers:
count: 45
avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4
url: https://github.com/ycd
- login: Xewus
count: 44
avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4
url: https://github.com/Xewus
- login: cikay
count: 41
avatarUrl: https://avatars.githubusercontent.com/u/24587499?u=e772190a051ab0eaa9c8542fcff1892471638f2b&v=4
url: https://github.com/cikay
- login: Xewus
count: 39
avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4
url: https://github.com/Xewus
- login: JarroVGIT
count: 34
avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4
@ -460,6 +460,10 @@ top_reviewers:
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4
url: https://github.com/axel584
- login: Alexandrhub
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4
url: https://github.com/Alexandrhub
- login: DevDae
count: 16
avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4
@ -472,10 +476,6 @@ top_reviewers:
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4
url: https://github.com/delhi09
- login: Alexandrhub
count: 15
avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4
url: https://github.com/Alexandrhub
- login: sh0nk
count: 13
avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4
@ -484,6 +484,10 @@ top_reviewers:
count: 13
avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4
url: https://github.com/peidrao
- login: wdh99
count: 13
avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4
url: https://github.com/wdh99
- login: r0b2g1t
count: 13
avatarUrl: https://avatars.githubusercontent.com/u/5357541?u=6428442d875d5d71aaa1bb38bb11c4be1a526bc2&v=4
@ -500,10 +504,6 @@ top_reviewers:
count: 11
avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4
url: https://github.com/solomein-sv
- login: wdh99
count: 11
avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4
url: https://github.com/wdh99
- login: mariacamilagl
count: 10
avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4

5
docs/en/data/sponsors.yml

@ -13,7 +13,7 @@ gold:
img: https://fastapi.tiangolo.com/img/sponsors/porter.png
- url: https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor
title: Automate FastAPI documentation generation with Bump.sh
img: https://fastapi.tiangolo.com/img/sponsors/bump-sh.png
img: https://fastapi.tiangolo.com/img/sponsors/bump-sh.svg
silver:
- url: https://www.deta.sh/?ref=fastapi
title: The launchpad for all your (team's) ideas
@ -43,9 +43,6 @@ bronze:
- url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source
title: Biosecurity risk assessments made easy.
img: https://fastapi.tiangolo.com/img/sponsors/exoflare.png
- url: https://www.flint.sh
title: IT expertise, consulting and development by passionate people
img: https://fastapi.tiangolo.com/img/sponsors/flint.png
- url: https://bit.ly/3JJ7y5C
title: Build cross-modal and multimodal applications on the cloud
img: https://fastapi.tiangolo.com/img/sponsors/jina2.svg

48
docs/en/docs/img/sponsors/bump-sh-banner.svg

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 38 KiB

56
docs/en/docs/img/sponsors/bump-sh.svg

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 45 KiB

22
docs/en/docs/release-notes.md

@ -2,9 +2,31 @@
## Latest Changes
* 🔧 Update sponsors, Bump.sh images. PR [#10381](https://github.com/tiangolo/fastapi/pull/10381) by [@tiangolo](https://github.com/tiangolo).
* 👥 Update FastAPI People. PR [#10363](https://github.com/tiangolo/fastapi/pull/10363) by [@tiangolo](https://github.com/tiangolo).
## 0.103.2
### Refactors
* ⬆️ Upgrade compatibility with Pydantic v2.4, new renamed functions and JSON Schema input/output models with default values. PR [#10344](https://github.com/tiangolo/fastapi/pull/10344) by [@tiangolo](https://github.com/tiangolo).
### Translations
* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/extra-data-types.md`. PR [#10132](https://github.com/tiangolo/fastapi/pull/10132) by [@ArtemKhymenko](https://github.com/ArtemKhymenko).
* 🌐 Fix typos in French translations for `docs/fr/docs/advanced/path-operation-advanced-configuration.md`, `docs/fr/docs/alternatives.md`, `docs/fr/docs/async.md`, `docs/fr/docs/features.md`, `docs/fr/docs/help-fastapi.md`, `docs/fr/docs/index.md`, `docs/fr/docs/python-types.md`, `docs/fr/docs/tutorial/body.md`, `docs/fr/docs/tutorial/first-steps.md`, `docs/fr/docs/tutorial/query-params.md`. PR [#10154](https://github.com/tiangolo/fastapi/pull/10154) by [@s-rigaud](https://github.com/s-rigaud).
* 🌐 Add Chinese translation for `docs/zh/docs/async.md`. PR [#5591](https://github.com/tiangolo/fastapi/pull/5591) by [@mkdir700](https://github.com/mkdir700).
* 🌐 Update Chinese translation for `docs/tutorial/security/simple-oauth2.md`. PR [#3844](https://github.com/tiangolo/fastapi/pull/3844) by [@jaystone776](https://github.com/jaystone776).
* 🌐 Add Korean translation for `docs/ko/docs/deployment/cloud.md`. PR [#10191](https://github.com/tiangolo/fastapi/pull/10191) by [@Sion99](https://github.com/Sion99).
* 🌐 Add Japanese translation for `docs/ja/docs/deployment/https.md`. PR [#10298](https://github.com/tiangolo/fastapi/pull/10298) by [@tamtam-fitness](https://github.com/tamtam-fitness).
* 🌐 Fix typo in Russian translation for `docs/ru/docs/tutorial/body-fields.md`. PR [#10224](https://github.com/tiangolo/fastapi/pull/10224) by [@AlertRED](https://github.com/AlertRED).
* 🌐 Add Polish translation for `docs/pl/docs/help-fastapi.md`. PR [#10121](https://github.com/tiangolo/fastapi/pull/10121) by [@romabozhanovgithub](https://github.com/romabozhanovgithub).
* 🌐 Add Russian translation for `docs/ru/docs/tutorial/header-params.md`. PR [#10226](https://github.com/tiangolo/fastapi/pull/10226) by [@AlertRED](https://github.com/AlertRED).
* 🌐 Add Chinese translation for `docs/zh/docs/deployment/versions.md`. PR [#10276](https://github.com/tiangolo/fastapi/pull/10276) by [@xzmeng](https://github.com/xzmeng).
### Internal
* 🔧 Update sponsors, remove Flint. PR [#10349](https://github.com/tiangolo/fastapi/pull/10349) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Rename label "awaiting review" to "awaiting-review" to simplify search queries. PR [#10343](https://github.com/tiangolo/fastapi/pull/10343) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors, enable Svix (revert #10228). PR [#10253](https://github.com/tiangolo/fastapi/pull/10253) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors, remove Svix. PR [#10228](https://github.com/tiangolo/fastapi/pull/10228) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update sponsors, add Bump.sh. PR [#10227](https://github.com/tiangolo/fastapi/pull/10227) by [@tiangolo](https://github.com/tiangolo).

2
docs/en/overrides/main.html

@ -49,7 +49,7 @@
<div class="item">
<a title="Automate FastAPI documentation generation with Bump.sh" style="display: block; position: relative;" href="https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor" target="_blank">
<span class="sponsor-badge">sponsor</span>
<img class="sponsor-image" src="/img/sponsors/bump-sh-banner.png" />
<img class="sponsor-image" src="/img/sponsors/bump-sh-banner.svg" />
</a>
</div>
</div>

2
docs/fr/docs/advanced/path-operation-advanced-configuration.md

@ -66,7 +66,7 @@ Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le
Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI.
!!! note "Détails techniques"
La spécification OpenAPI appelle ces métaonnées des <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Objets d'opération</a>.
La spécification OpenAPI appelle ces métadonnées des <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#operation-object" class="external-link" target="_blank">Objets d'opération</a>.
Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation.

2
docs/fr/docs/alternatives.md

@ -387,7 +387,7 @@ Gérer toute la validation des données, leur sérialisation et la documentation
### <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>
Starlette est un framework/toolkit léger <abbr title="Le nouveau standard pour construire des applications web assynchrones en Python">ASGI</abbr>, qui est idéal pour construire des services asyncio performants.
Starlette est un framework/toolkit léger <abbr title="Le nouveau standard pour construire des applications web asynchrones en Python">ASGI</abbr>, qui est idéal pour construire des services asyncio performants.
Il est très simple et intuitif. Il est conçu pour être facilement extensible et avoir des composants modulaires.

2
docs/fr/docs/async.md

@ -250,7 +250,7 @@ Par exemple :
### Concurrence + Parallélisme : Web + Machine Learning
Avec **FastAPI** vous pouvez bénéficier de la concurrence qui est très courante en developement web (c'est l'attrait principal de NodeJS).
Avec **FastAPI** vous pouvez bénéficier de la concurrence qui est très courante en développement web (c'est l'attrait principal de NodeJS).
Mais vous pouvez aussi profiter du parallélisme et multiprocessing afin de gérer des charges **CPU bound** qui sont récurrentes dans les systèmes de *Machine Learning*.

14
docs/fr/docs/features.md

@ -71,9 +71,9 @@ my_second_user: User = User(**second_user_data)
Tout le framework a été conçu pour être facile et intuitif d'utilisation, toutes les décisions de design ont été testées sur de nombreux éditeurs avant même de commencer le développement final afin d'assurer la meilleure expérience de développement possible.
Dans le dernier sondage effectué auprès de développeurs python il était clair que <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">la fonctionnalité la plus utilisée est "l'autocomplètion"</a>.
Dans le dernier sondage effectué auprès de développeurs python il était clair que <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">la fonctionnalité la plus utilisée est "l’autocomplétion"</a>.
Tout le framwork **FastAPI** a été conçu avec cela en tête. L'autocomplétion fonctionne partout.
Tout le framework **FastAPI** a été conçu avec cela en tête. L'autocomplétion fonctionne partout.
Vous devrez rarement revenir à la documentation.
@ -136,7 +136,7 @@ FastAPI contient un système simple mais extrêmement puissant d'<abbr title='au
* Même les dépendances peuvent avoir des dépendances, créant une hiérarchie ou un **"graph" de dépendances**
* Tout est **automatiquement géré** par le framework
* Toutes les dépendances peuvent éxiger des données d'une requêtes et **Augmenter les contraintes d'un path operation** et de la documentation automatique.
* Toutes les dépendances peuvent exiger des données d'une requêtes et **Augmenter les contraintes d'un path operation** et de la documentation automatique.
* **Validation automatique** même pour les paramètres de *path operation* définis dans les dépendances.
* Supporte les systèmes d'authentification d'utilisateurs complexes, les **connexions de base de données**, etc.
* **Aucun compromis** avec les bases de données, les frontends, etc. Mais une intégration facile avec n'importe lequel d'entre eux.
@ -157,11 +157,11 @@ Tout intégration est conçue pour être si simple à utiliser (avec des dépend
**FastAPI** est complètement compatible (et basé sur) <a href="https://www.starlette.io/" class="external-link" target="_blank"><strong>Starlette</strong></a>. Le code utilisant Starlette que vous ajouterez fonctionnera donc aussi.
En fait, `FastAPI` est un sous compposant de `Starlette`. Donc, si vous savez déjà comment utiliser Starlette, la plupart des fonctionnalités fonctionneront de la même manière.
En fait, `FastAPI` est un sous composant de `Starlette`. Donc, si vous savez déjà comment utiliser Starlette, la plupart des fonctionnalités fonctionneront de la même manière.
Avec **FastAPI** vous aurez toutes les fonctionnalités de **Starlette** (FastAPI est juste Starlette sous stéroïdes):
* Des performances vraiments impressionnantes. C'est l'<a href="https://github.com/encode/starlette#performance" class="external-link" target="_blank">un des framework Python les plus rapide, à égalité avec **NodeJS** et **GO**</a>.
* Des performances vraiment impressionnantes. C'est l'<a href="https://github.com/encode/starlette#performance" class="external-link" target="_blank">un des framework Python les plus rapide, à égalité avec **NodeJS** et **GO**</a>.
* Le support des **WebSockets**.
* Le support de **GraphQL**.
* Les <abbr title="En anglais: In-process background tasks">tâches d'arrière-plan.</abbr>
@ -180,7 +180,7 @@ Inclus des librairies externes basées, aussi, sur Pydantic, servent d'<abbr tit
Cela signifie aussi que, dans la plupart des cas, vous pouvez fournir l'objet reçu d'une requête **directement à la base de données**, comme tout est validé automatiquement.
Inversément, dans la plupart des cas vous pourrez juste envoyer l'objet récupéré de la base de données **directement au client**
Inversement, dans la plupart des cas vous pourrez juste envoyer l'objet récupéré de la base de données **directement au client**
Avec **FastAPI** vous aurez toutes les fonctionnalités de **Pydantic** (comme FastAPI est basé sur Pydantic pour toutes les manipulations de données):
@ -194,7 +194,7 @@ Avec **FastAPI** vous aurez toutes les fonctionnalités de **Pydantic** (comme
* Valide les **structures complexes**:
* Utilise les modèles hiérarchique de Pydantic, le `typage` Python pour les `Lists`, `Dict`, etc.
* Et les validateurs permettent aux schémas de données complexes d'être clairement et facilement définis, validés et documentés sous forme d'un schéma JSON.
* Vous pouvez avoir des objets **JSON fortements imbriqués** tout en ayant, pour chacun, de la validation et des annotations.
* Vous pouvez avoir des objets **JSON fortement imbriqués** tout en ayant, pour chacun, de la validation et des annotations.
* **Renouvelable**:
* Pydantic permet de définir de nouveaux types de données ou vous pouvez étendre la validation avec des méthodes sur un modèle décoré avec le<abbr title="en anglais: validator decorator"> décorateur de validation</abbr>
* 100% de couverture de test.

4
docs/fr/docs/help-fastapi.md

@ -36,8 +36,8 @@ Vous pouvez :
* <a href="https://twitter.com/tiangolo" class="external-link" target="_blank">Me suivre sur **Twitter**</a>.
* Dites-moi comment vous utilisez FastAPI (j'adore entendre ça).
* Entendre quand je fais des annonces ou que je lance de nouveaux outils.
* <a href="https://www.linkedin.com/in/tiangolo/" class="external-link" target="_blank">Vous connectez à moi sur **Linkedin**</a>.
* Etre notifié quand je fais des annonces ou que je lance de nouveaux outils (bien que j'utilise plus souvent Twitte 🤷‍♂).
* <a href="https://www.linkedin.com/in/tiangolo/" class="external-link" target="_blank">Vous connectez à moi sur **LinkedIn**</a>.
* Etre notifié quand je fais des annonces ou que je lance de nouveaux outils (bien que j'utilise plus souvent Twitter 🤷‍♂).
* Lire ce que j’écris (ou me suivre) sur <a href="https://dev.to/tiangolo" class="external-link" target="_blank">**Dev.to**</a> ou <a href="https://medium.com/@tiangolo" class="external-link" target="_blank">**Medium**</a>.
* Lire d'autres idées, articles, et sur les outils que j'ai créés.
* Suivez-moi pour lire quand je publie quelque chose de nouveau.

4
docs/fr/docs/index.md

@ -424,7 +424,7 @@ Pour un exemple plus complet comprenant plus de fonctionnalités, voir le <a hre
* Déclaration de **paramètres** provenant d'autres endroits différents comme : **<abbr title="en anglais : headers">en-têtes</abbr>.**, **cookies**, **champs de formulaire** et **fichiers**.
* L'utilisation de **contraintes de validation** comme `maximum_length` ou `regex`.
* Un **<abbr title="aussi connu sous le nom de composants, ressources, fournisseurs, services, injectables">systéme d'injection de dépendance </abbr>** très puissant et facile à utiliser .
* Un **<abbr title="aussi connu sous le nom de composants, ressources, fournisseurs, services, injectables">système d'injection de dépendance </abbr>** très puissant et facile à utiliser .
* Sécurité et authentification, y compris la prise en charge de **OAuth2** avec les **<abbr title="en anglais : JWT tokens">jetons <abbr title="JSON Web Tokens">JWT</abbr></abbr>** et l'authentification **HTTP Basic**.
* Des techniques plus avancées (mais tout aussi faciles) pour déclarer les **modèles <abbr title="JavaScript Object Notation">JSON</abbr> profondément imbriqués** (grâce à Pydantic).
* Intégration de **GraphQL** avec <a href="https://strawberry.rocks" class="external-link" target="_blank">Strawberry</a> et d'autres bibliothèques.
@ -450,7 +450,7 @@ Utilisées par Pydantic:
Utilisées par Starlette :
* <a href="https://requests.readthedocs.io" target="_blank"><code>requests</code></a> - Obligatoire si vous souhaitez utiliser `TestClient`.
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Obligatoire si vous souhaitez utiliser la configuration de template par defaut.
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Obligatoire si vous souhaitez utiliser la configuration de template par défaut.
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Obligatoire si vous souhaitez supporter le <abbr title="convertit la chaine de caractère d'une requête HTTP en donnée Python">"décodage"</abbr> de formulaire avec `request.form()`.
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Obligatoire pour la prise en charge de `SessionMiddleware`.
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI).

2
docs/fr/docs/python-types.md

@ -119,7 +119,7 @@ Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'aut
<img src="/img/python-types/image04.png">
Maintenant que vous avez connaissance du problème, convertissez `age` en <abbr title="string">chaine de caractères</abbr> grâce à `str(age)` :
Maintenant que vous avez connaissance du problème, convertissez `age` en <abbr title="string">chaîne de caractères</abbr> grâce à `str(age)` :
```Python hl_lines="2"
{!../../../docs_src/python_types/tutorial004.py!}

2
docs/fr/docs/tutorial/body.md

@ -98,7 +98,7 @@ Et vous obtenez aussi de la vérification d'erreur pour les opérations incorrec
<img src="/img/tutorial/body/image04.png">
Ce n'est pas un hasard, ce framework entier a été bati avec ce design comme objectif.
Ce n'est pas un hasard, ce framework entier a été bâti avec ce design comme objectif.
Et cela a été rigoureusement testé durant la phase de design, avant toute implémentation, pour s'assurer que cela fonctionnerait avec tous les éditeurs.

2
docs/fr/docs/tutorial/first-steps.md

@ -170,7 +170,7 @@ Si vous créez votre app avec :
{!../../../docs_src/first_steps/tutorial002.py!}
```
Et la mettez dans un fichier `main.py`, alors vous appeleriez `uvicorn` avec :
Et la mettez dans un fichier `main.py`, alors vous appelleriez `uvicorn` avec :
<div class="termy">

2
docs/fr/docs/tutorial/query-params.md

@ -75,7 +75,7 @@ Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut.
!!! note
**FastAPI** saura que `q` est optionnel grâce au `=None`.
Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre editeur de texte pour détecter des erreurs dans votre code.
Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code.
## Conversion des types des paramètres de requête

200
docs/ja/docs/deployment/https.md

@ -0,0 +1,200 @@
# HTTPS について
HTTPSは単に「有効」か「無効」かで決まるものだと思いがちです。
しかし、それよりもはるかに複雑です。
!!! tip
もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。
利用者の視点から **HTTPS の基本を学ぶ**に当たっては、次のリソースをオススメします: <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>.
さて、**開発者の視点**から、HTTPSについて考える際に念頭に置くべきことをいくつかみていきましょう:
* HTTPSの場合、**サーバ**は**第三者**によって生成された**「証明書」を持つ**必要があります。
* これらの証明書は「生成」されたものではなく、実際には第三者から**取得**されたものです。
* 証明書には**有効期限**があります。
* つまりいずれ失効します。
* そのため**更新**をし、第三者から**再度取得**する必要があります。
* 接続の暗号化は**TCPレベル**で行われます。
* それは**HTTPの1つ下**のレイヤーです。
* つまり、**証明書と暗号化**の処理は、**HTTPの前**に行われます。
* **TCPは "ドメイン "について知りません**。IPアドレスについてのみ知っています。
* 要求された**特定のドメイン**に関する情報は、**HTTPデータ**に入ります。
* **HTTPS証明書**は、**特定のドメイン**を「証明」しますが、プロトコルと暗号化はTCPレベルで行われ、どのドメインが扱われているかを**知る前**に行われます。
* **デフォルトでは**、**IPアドレスごとに1つのHTTPS証明書**しか持てないことになります。
* これは、サーバーの規模やアプリケーションの規模に寄りません。
* しかし、これには**解決策**があります。
* **TLS**プロトコル(HTTPの前に、TCPレベルで暗号化を処理するもの)には、**<a href="https://en.wikipedia.org/wiki/Server_Name_Indication" class="external-link" target="_blank"><abbr title="サーバー名表示">SNI</abbr></a>**と呼ばれる**拡張**があります。
* このSNI拡張機能により、1つのサーバー(**単一のIPアドレス**を持つ)が**複数のHTTPS証明書**を持ち、**複数のHTTPSドメイン/アプリケーション**にサービスを提供できるようになります。
* これが機能するためには、**パブリックIPアドレス**でリッスンしている、サーバー上で動作している**単一の**コンポーネント(プログラム)が、サーバー内の**すべてのHTTPS証明書**を持っている必要があります。
* セキュアな接続を取得した**後**でも、通信プロトコルは**HTTPのまま**です。
* コンテンツは**HTTPプロトコル**で送信されているにもかかわらず、**暗号化**されています。
サーバー(マシン、ホストなど)上で**1つのプログラム/HTTPサーバー**を実行させ、**HTTPSに関する全てのこと**を管理するのが一般的です。
**暗号化された HTTPS リクエスト** を受信し、**復号化された HTTP リクエスト** を同じサーバーで実行されている実際の HTTP アプリケーション(この場合は **FastAPI** アプリケーション)に送信し、アプリケーションから **HTTP レスポンス** を受け取り、適切な **HTTPS 証明書** を使用して **暗号化** し、そして**HTTPS** を使用してクライアントに送り返します。
このサーバーはしばしば **<a href="https://en.wikipedia.org/wiki/TLS_termination_proxy" class="external-link" target="_blank">TLS Termination Proxy</a>**と呼ばれます。
TLS Termination Proxyとして使えるオプションには、以下のようなものがあります:
* Traefik(証明書の更新も対応)
* Caddy (証明書の更新も対応)
* Nginx
* HAProxy
## Let's Encrypt
Let's Encrypt以前は、これらの**HTTPS証明書**は信頼できる第三者によって販売されていました。
これらの証明書を取得するための手続きは面倒で、かなりの書類を必要とし、証明書はかなり高価なものでした。
しかしその後、**<a href="https://letsencrypt.org/" class="external-link" target="_blank">Let's Encrypt</a>** が作られました。
これはLinux Foundationのプロジェクトから生まれたものです。 自動化された方法で、**HTTPS証明書を無料で**提供します。これらの証明書は、すべての標準的な暗号化セキュリティを使用し、また短命(約3ヶ月)ですが、こういった寿命の短さによって、**セキュリティは実際に優れています**。
ドメインは安全に検証され、証明書は自動的に生成されます。また、証明書の更新も自動化されます。
このアイデアは、これらの証明書の取得と更新を自動化することで、**安全なHTTPSを、無料で、永遠に**利用できるようにすることです。
## 開発者のための HTTPS
ここでは、HTTPS APIがどのように見えるかの例を、主に開発者にとって重要なアイデアに注意を払いながら、ステップ・バイ・ステップで説明します。
### ドメイン名
ステップの初めは、**ドメイン名**を**取得すること**から始まるでしょう。その後、DNSサーバー(おそらく同じクラウドプロバイダー)に設定します。
おそらくクラウドサーバー(仮想マシン)かそれに類するものを手に入れ、<abbr title="変わらない">固定の</abbr> **パブリックIPアドレス**を持つことになるでしょう。
DNSサーバーでは、**取得したドメイン**をあなたのサーバーのパプリック**IPアドレス**に向けるレコード(「`Aレコード`」)を設定します。
これはおそらく、最初の1回だけあり、すべてをセットアップするときに行うでしょう。
!!! tip
ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。
### DNS
では、実際のHTTPSの部分に注目してみよう。
まず、ブラウザは**DNSサーバー**に**ドメインに対するIP**が何であるかを確認します。今回は、`someapp.example.com`とします。
DNSサーバーは、ブラウザに特定の**IPアドレス**を使用するように指示します。このIPアドレスは、DNSサーバーで設定した、あなたのサーバーが使用するパブリックIPアドレスになります。
<img src="/img/deployment/https/https01.svg">
### TLS Handshake の開始
ブラウザはIPアドレスと**ポート443**(HTTPSポート)で通信します。
通信の最初の部分は、クライアントとサーバー間の接続を確立し、使用する暗号鍵などを決めるだけです。
<img src="/img/deployment/https/https02.svg">
TLS接続を確立するためのクライアントとサーバー間のこのやりとりは、**TLSハンドシェイク**と呼ばれます。
### SNI拡張機能付きのTLS
サーバー内の**1つのプロセス**だけが、特定 の**IPアドレス**の特定の**ポート** で待ち受けることができます。
同じIPアドレスの他のポートで他のプロセスがリッスンしている可能性もありますが、IPアドレスとポートの組み合わせごとに1つだけです。
TLS(HTTPS)はデフォルトで`443`という特定のポートを使用する。つまり、これが必要なポートです。
このポートをリッスンできるのは1つのプロセスだけなので、これを実行するプロセスは**TLS Termination Proxy**となります。
TLS Termination Proxyは、1つ以上の**TLS証明書**(HTTPS証明書)にアクセスできます。
前述した**SNI拡張機能**を使用して、TLS Termination Proxy は、利用可能なTLS (HTTPS)証明書のどれを接続先として使用すべきかをチェックし、クライアントが期待するドメインに一致するものを使用します。
今回は、`someapp.example.com`の証明書を使うことになります。
<img src="/img/deployment/https/https03.svg">
クライアントは、そのTLS証明書を生成したエンティティ(この場合はLet's Encryptですが、これについては後述します)をすでに**信頼**しているため、その証明書が有効であることを**検証**することができます。
次に証明書を使用して、クライアントとTLS Termination Proxy は、 **TCP通信**の残りを**どのように暗号化するかを決定**します。これで**TLSハンドシェイク**の部分が完了します。
この後、クライアントとサーバーは**暗号化されたTCP接続**を持ちます。そして、その接続を使って実際の**HTTP通信**を開始することができます。
これが**HTTPS**であり、純粋な(暗号化されていない)TCP接続ではなく、**セキュアなTLS接続**の中に**HTTP**があるだけです。
!!! tip
通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。
### HTTPS リクエスト
これでクライアントとサーバー(具体的にはブラウザとTLS Termination Proxy)は**暗号化されたTCP接続**を持つことになり、**HTTP通信**を開始することができます。
そこで、クライアントは**HTTPSリクエスト**を送信します。これは、暗号化されたTLSコネクションを介した単なるHTTPリクエストです。
<img src="/img/deployment/https/https04.svg">
### リクエストの復号化
TLS Termination Proxy は、合意が取れている暗号化を使用して、**リクエストを復号化**し、**プレーン (復号化された) HTTP リクエスト** をアプリケーションを実行しているプロセス (例えば、FastAPI アプリケーションを実行している Uvicorn を持つプロセス) に送信します。
<img src="/img/deployment/https/https05.svg">
### HTTP レスポンス
アプリケーションはリクエストを処理し、**プレーン(暗号化されていない)HTTPレスポンス** をTLS Termination Proxyに送信します。
<img src="/img/deployment/https/https06.svg">
### HTTPS レスポンス
TLS Termination Proxyは次に、事前に合意が取れている暗号(`someapp.example.com`の証明書から始まる)を使って**レスポンスを暗号化し**、ブラウザに送り返す。
その後ブラウザでは、レスポンスが有効で正しい暗号キーで暗号化されていることなどを検証します。そして、ブラウザはレスポンスを**復号化**して処理します。
<img src="/img/deployment/https/https07.svg">
クライアント(ブラウザ)は、レスポンスが正しいサーバーから来たことを知ることができます。 なぜなら、そのサーバーは、以前に**HTTPS証明書**を使って合意した暗号を使っているからです。
### 複数のアプリケーション
同じサーバー(または複数のサーバー)に、例えば他のAPIプログラムやデータベースなど、**複数のアプリケーション**が存在する可能性があります。
特定のIPとポート(この例ではTLS Termination Proxy)を扱うことができるのは1つのプロセスだけですが、他のアプリケーション/プロセスも、同じ**パブリックIPとポート**の組み合わせを使用しようとしない限り、サーバー上で実行することができます。
<img src="/img/deployment/https/https08.svg">
そうすれば、TLS Termination Proxy は、**複数のドメイン**や複数のアプリケーションのHTTPSと証明書を処理し、それぞれのケースで適切なアプリケーションにリクエストを送信することができます。
### 証明書の更新
将来のある時点で、各証明書は(取得後約3ヶ月で)**失効**します。
その後、Let's Encryptと通信する別のプログラム(別のプログラムである場合もあれば、同じTLS Termination Proxyである場合もある)によって、証明書を更新します。
<img src="/img/deployment/https/https.svg">
**TLS証明書**は、IPアドレスではなく、**ドメイン名に関連付けられて**います。
したがって、証明書を更新するために、更新プログラムは、認証局(Let's Encrypt)に対して、**そのドメインが本当に「所有」し、管理している**ことを**証明**する必要があります。
そのために、またさまざまなアプリケーションのニーズに対応するために、いくつかの方法があります。よく使われる方法としては:
* **いくつかのDNSレコードを修正します。**
* これをするためには、更新プログラムはDNSプロバイダーのAPIをサポートする必要があります。したがって、使用しているDNSプロバイダーによっては、このオプションが使える場合もあれば、使えない場合もあります。
* ドメインに関連付けられたパブリックIPアドレス上で、(少なくとも証明書取得プロセス中は)**サーバー**として実行します。
* 上で述べたように、特定のIPとポートでリッスンできるプロセスは1つだけです。
* これは、同じTLS Termination Proxyが証明書の更新処理も行う場合に非常に便利な理由の1つです。
* そうでなければ、TLS Termination Proxyを一時的に停止し、証明書を取得するために更新プログラムを起動し、TLS Termination Proxyで証明書を設定し、TLS Termination Proxyを再起動しなければならないかもしれません。TLS Termination Proxyが停止している間はアプリが利用できなくなるため、これは理想的ではありません。
アプリを提供しながらこのような更新処理を行うことは、アプリケーション・サーバー(Uvicornなど)でTLS証明書を直接使用するのではなく、TLS Termination Proxyを使用して**HTTPSを処理する別のシステム**を用意したくなる主な理由の1つです。
## まとめ
**HTTPS**を持つことは非常に重要であり、ほとんどの場合、かなり**クリティカル**です。開発者として HTTPS に関わる労力のほとんどは、これらの**概念とその仕組みを理解する**ことです。
しかし、ひとたび**開発者向けHTTPS**の基本的な情報を知れば、簡単な方法ですべてを管理するために、さまざまなツールを組み合わせて設定することができます。
次の章では、**FastAPI** アプリケーションのために **HTTPS** をセットアップする方法について、いくつかの具体例を紹介します。🔒

17
docs/ko/docs/deployment/cloud.md

@ -0,0 +1,17 @@
# FastAPI를 클라우드 제공업체에서 배포하기
사실상 거의 **모든 클라우드 제공업체**를 사용하여 여러분의 FastAPI 애플리케이션을 배포할 수 있습니다.
대부분의 경우, 주요 클라우드 제공업체에서는 FastAPI를 배포할 수 있도록 가이드를 제공합니다.
## 클라우드 제공업체 - 후원자들
몇몇 클라우드 제공업체들은 [**FastAPI를 후원하며**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, 이를 통해 FastAPI와 FastAPI **생태계**가 지속적이고 건전한 **발전**을 할 수 있습니다.
이는 FastAPI와 **커뮤니티** (여러분)에 대한 진정한 헌신을 보여줍니다. 그들은 여러분에게 **좋은 서비스**를 제공할 뿐 만이 아니라 여러분이 **훌륭하고 건강한 프레임워크인** FastAPI 를 사용하길 원하기 때문입니다. 🙇
아래와 같은 서비스를 사용해보고 각 서비스의 가이드를 따를 수도 있습니다:
* <a href="https://docs.platform.sh/languages/python.html?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023" class="external-link" target="_blank">Platform.sh</a>
* <a href="https://docs.porter.run/language-specific-guides/fastapi" class="external-link" target="_blank">Porter</a>
* <a href="https://www.deta.sh/?ref=fastapi" class="external-link" target="_blank">Deta</a>

2
docs/ru/docs/tutorial/body-fields.md

@ -37,7 +37,7 @@
{!> ../../../docs_src/body_fields/tutorial001.py!}
```
Функция `Field` работает так же, как `Query`, `Path` и `Body`, у ее такие же параметры и т.д.
Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д.
!!! note "Технические детали"
На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic.

42
docs/uk/docs/tutorial/encoder.md

@ -0,0 +1,42 @@
# JSON Compatible Encoder
Існують випадки, коли вам може знадобитися перетворити тип даних (наприклад, модель Pydantic) в щось сумісне з JSON (наприклад, `dict`, `list`, і т. д.).
Наприклад, якщо вам потрібно зберегти це в базі даних.
Для цього, **FastAPI** надає `jsonable_encoder()` функцію.
## Використання `jsonable_encoder`
Давайте уявимо, що у вас є база даних `fake_db`, яка приймає лише дані, сумісні з JSON.
Наприклад, вона не приймає об'єкти типу `datetime`, оскільки вони не сумісні з JSON.
Отже, об'єкт типу `datetime` потрібно перетворити в рядок `str`, який містить дані в <a href="https://en.wikipedia.org/wiki/ISO_8601" class="external-link" target="_blank">ISO форматі</a>.
Тим самим способом ця база даних не прийматиме об'єкт типу Pydantic model (об'єкт з атрибутами), а лише `dict`.
Ви можете використовувати `jsonable_encoder` для цього.
Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON:
=== "Python 3.10+"
```Python hl_lines="4 21"
{!> ../../../docs_src/encoder/tutorial001_py310.py!}
```
=== "Python 3.6+"
```Python hl_lines="5 22"
{!> ../../../docs_src/encoder/tutorial001.py!}
```
У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`.
Результат виклику цієї функції - це щось, що можна кодувати з використанням стандарту Python <a href="https://docs.python.org/3/library/json.html#json.dumps" class="external-link" target="_blank">`json.dumps()`</a>.
Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON.
!!! Примітка
`jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях.

130
docs/uk/docs/tutorial/extra-data-types.md

@ -0,0 +1,130 @@
# Додаткові типи даних
До цього часу, ви використовували загальнопоширені типи даних, такі як:
* `int`
* `float`
* `str`
* `bool`
Але можна також використовувати більш складні типи даних.
І ви все ще матимете ті ж можливості, які були показані до цього:
* Чудова підтримка редактора.
* Конвертація даних з вхідних запитів.
* Конвертація даних для відповіді.
* Валідація даних.
* Автоматична анотація та документація.
## Інші типи даних
Ось додаткові типи даних для використання:
* `UUID`:
* Стандартний "Універсальний Унікальний Ідентифікатор", який часто використовується як ідентифікатор у багатьох базах даних та системах.
* У запитах та відповідях буде представлений як `str`.
* `datetime.datetime`:
* Пайтонівський `datetime.datetime`.
* У запитах та відповідях буде представлений як `str` в форматі ISO 8601, як: `2008-09-15T15:53:00+05:00`.
* `datetime.date`:
* Пайтонівський `datetime.date`.
* У запитах та відповідях буде представлений як `str` в форматі ISO 8601, як: `2008-09-15`.
* `datetime.time`:
* Пайтонівський `datetime.time`.
* У запитах та відповідях буде представлений як `str` в форматі ISO 8601, як: `14:23:55.003`.
* `datetime.timedelta`:
* Пайтонівський `datetime.timedelta`.
* У запитах та відповідях буде представлений як `float` загальної кількості секунд.
* Pydantic також дозволяє представляти це як "ISO 8601 time diff encoding", <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#json_encoders" class="external-link" target="_blank">більше інформації дивись у документації</a>.
* `frozenset`:
* У запитах і відповідях це буде оброблено так само, як і `set`:
* У запитах список буде зчитано, дублікати будуть видалені та він буде перетворений на `set`.
* У відповідях, `set` буде перетворений на `list`.
* Згенерована схема буде вказувати, що значення `set` є унікальними (з використанням JSON Schema's `uniqueItems`).
* `bytes`:
* Стандартний Пайтонівський `bytes`.
* У запитах і відповідях це буде оброблено як `str`.
* Згенерована схема буде вказувати, що це `str` з "форматом" `binary`.
* `Decimal`:
* Стандартний Пайтонівський `Decimal`.
* У запитах і відповідях це буде оброблено так само, як і `float`.
* Ви можете перевірити всі дійсні типи даних Pydantic тут: <a href="https://pydantic-docs.helpmanual.io/usage/types" class="external-link" target="_blank">типи даних Pydantic</a>.
## Приклад
Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів.
=== "Python 3.10+"
```Python hl_lines="1 3 12-16"
{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
```
=== "Python 3.9+"
```Python hl_lines="1 3 12-16"
{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
```
=== "Python 3.6+"
```Python hl_lines="1 3 13-17"
{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
```
=== "Python 3.10+ non-Annotated"
!!! tip
Бажано використовувати `Annotated` версію, якщо це можливо.
```Python hl_lines="1 2 11-15"
{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
```
=== "Python 3.6+ non-Annotated"
!!! tip
Бажано використовувати `Annotated` версію, якщо це можливо.
```Python hl_lines="1 2 12-16"
{!> ../../../docs_src/extra_data_types/tutorial001.py!}
```
Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як:
=== "Python 3.10+"
```Python hl_lines="18-19"
{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!}
```
=== "Python 3.9+"
```Python hl_lines="18-19"
{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!}
```
=== "Python 3.6+"
```Python hl_lines="19-20"
{!> ../../../docs_src/extra_data_types/tutorial001_an.py!}
```
=== "Python 3.10+ non-Annotated"
!!! tip
Бажано використовувати `Annotated` версію, якщо це можливо.
```Python hl_lines="17-18"
{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!}
```
=== "Python 3.6+ non-Annotated"
!!! tip
Бажано використовувати `Annotated` версію, якщо це можливо.
```Python hl_lines="18-19"
{!> ../../../docs_src/extra_data_types/tutorial001.py!}
```

430
docs/zh/docs/async.md

@ -0,0 +1,430 @@
# 并发 async / await
有关路径操作函数的 `async def` 语法以及异步代码、并发和并行的一些背景知识。
## 赶时间吗?
<abbr title="too long; didn't read(长文警告)"><strong>TL;DR:</strong></abbr>
如果你正在使用第三方库,它们会告诉你使用 `await` 关键字来调用它们,就像这样:
```Python
results = await some_library()
```
然后,通过 `async def` 声明你的 *路径操作函数*
```Python hl_lines="2"
@app.get('/')
async def read_results():
results = await some_library()
return results
```
!!! note
你只能在被 `async def` 创建的函数内使用 `await`
---
如果你正在使用一个第三方库和某些组件(比如:数据库、API、文件系统...)进行通信,第三方库又不支持使用 `await` (目前大多数数据库三方库都是这样),这种情况你可以像平常那样使用 `def` 声明一个路径操作函数,就像这样:
```Python hl_lines="2"
@app.get('/')
def results():
results = some_library()
return results
```
---
如果你的应用程序不需要与其他任何东西通信而等待其响应,请使用 `async def`
---
如果你不清楚,使用 `def` 就好.
---
**注意**:你可以根据需要在路径操作函数中混合使用 `def``async def`,并使用最适合你的方式去定义每个函数。FastAPI 将为他们做正确的事情。
无论如何,在上述任何情况下,FastAPI 仍将异步工作,速度也非常快。
但是,通过遵循上述步骤,它将能够进行一些性能优化。
## 技术细节
Python 的现代版本支持通过一种叫**"协程"**——使用 `async``await` 语法的东西来写**”异步代码“**。
让我们在下面的部分中逐一介绍:
* **异步代码**
* **`async``await`**
* **协程**
## 异步代码
异步代码仅仅意味着编程语言 💬 有办法告诉计算机/程序 🤖 在代码中的某个点,它 🤖 将不得不等待在某些地方完成一些事情。让我们假设一些事情被称为 "慢文件"📝.
所以,在等待"慢文件"📝完成的这段时间,计算机可以做一些其他工作。
然后计算机/程序 🤖 每次有机会都会回来,因为它又在等待,或者它 🤖 完成了当前所有的工作。而且它 🤖 将查看它等待的所有任务中是否有已经完成的,做它必须做的任何事情。
接下来,它 🤖 完成第一个任务(比如是我们的"慢文件"📝) 并继续与之相关的一切。
这个"等待其他事情"通常指的是一些相对较慢(与处理器和 RAM 存储器的速度相比)的 <abbr title="Input and Output">I/O</abbr> 操作,比如说:
* 通过网络发送来自客户端的数据
* 客户端接收来自网络中的数据
* 磁盘中要由系统读取并提供给程序的文件的内容
* 程序提供给系统的要写入磁盘的内容
* 一个 API 的远程调用
* 一个数据库操作,直到完成
* 一个数据库查询,直到返回结果
* 等等.
这个执行的时间大多是在等待 <abbr title="Input and Output">I/O</abbr> 操作,因此它们被叫做 "I/O 密集型" 操作。
它被称为"异步"的原因是因为计算机/程序不必与慢任务"同步",去等待任务完成的确切时刻,而在此期间不做任何事情直到能够获取任务结果才继续工作。
相反,作为一个"异步"系统,一旦完成,任务就可以排队等待一段时间(几微秒),等待计算机程序完成它要做的任何事情,然后回来获取结果并继续处理它们。
对于"同步"(与"异步"相反),他们通常也使用"顺序"一词,因为计算机程序在切换到另一个任务之前是按顺序执行所有步骤,即使这些步骤涉及到等待。
### 并发与汉堡
上述异步代码的思想有时也被称为“并发”,它不同于“并行”。
并发和并行都与“不同的事情或多或少同时发生”有关。
但是并发和并行之间的细节是完全不同的。
要了解差异,请想象以下关于汉堡的故事:
### 并发汉堡
你和你的恋人一起去快餐店,你排队在后面,收银员从你前面的人接单。😍
<img src="/img/async/concurrent-burgers/concurrent-burgers-01.png" class="illustration">
然后轮到你了,你为你的恋人和你选了两个非常豪华的汉堡。🍔🍔
<img src="/img/async/concurrent-burgers/concurrent-burgers-02.png" class="illustration">
收银员对厨房里的厨师说了一些话,让他们知道他们必须为你准备汉堡(尽管他们目前正在为之前的顾客准备汉堡)。
<img src="/img/async/concurrent-burgers/concurrent-burgers-03.png" class="illustration">
你付钱了。 💸
收银员给你轮到的号码。
<img src="/img/async/concurrent-burgers/concurrent-burgers-04.png" class="illustration">
当你在等待的时候,你和你的恋人一起去挑选一张桌子,然后你们坐下来聊了很长时间(因为汉堡很豪华,需要一些时间来准备)。
当你和你的恋人坐在桌子旁,等待汉堡的时候,你可以用这段时间来欣赏你的恋人是多么的棒、可爱和聪明✨😍✨。
<img src="/img/async/concurrent-burgers/concurrent-burgers-05.png" class="illustration">
在等待中和你的恋人交谈时,你会不时地查看柜台上显示的号码,看看是否已经轮到你了。
然后在某个时刻,终于轮到你了。你去柜台拿汉堡然后回到桌子上。
<img src="/img/async/concurrent-burgers/concurrent-burgers-06.png" class="illustration">
你们享用了汉堡,整个过程都很开心。✨
<img src="/img/async/concurrent-burgers/concurrent-burgers-07.png" class="illustration">
!!! info
漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
---
在那个故事里,假设你是计算机程序 🤖 。
当你在排队时,你只是闲着😴, 轮到你前不做任何事情(仅排队)。但排队很快,因为收银员只接订单(不准备订单),所以这一切都还好。
然后,当轮到你时,需要你做一些实际性的工作,比如查看菜单,决定你想要什么,让你的恋人选择,支付,检查你是否提供了正确的账单或卡,检查你的收费是否正确,检查订单是否有正确的项目,等等。
此时,即使你仍然没有汉堡,你和收银员的工作也"暂停"了⏸, 因为你必须等待一段时间 🕙 让你的汉堡做好。
但是,当你离开柜台并坐在桌子旁,在轮到你的号码前的这段时间,你可以将焦点切换到 🔀 你的恋人上,并做一些"工作"⏯ 🤓。你可以做一些非常"有成效"的事情,比如和你的恋人调情😍.
之后,收银员 💁 把号码显示在显示屏上,并说到 "汉堡做好了",而当显示的号码是你的号码时,你不会立刻疯狂地跳起来。因为你知道没有人会偷你的汉堡,因为你有你的号码,而其他人又有他们自己的号码。
所以你要等待你的恋人完成故事(完成当前的工作⏯ /正在做的事🤓), 轻轻微笑,说你要吃汉堡⏸.
然后你去柜台🔀, 到现在初始任务已经完成⏯, 拿起汉堡,说声谢谢,然后把它们送到桌上。这就完成了与计数器交互的步骤/任务⏹. 这反过来又产生了一项新任务,即"吃汉堡"🔀 ⏯, 上一个"拿汉堡"的任务已经结束了⏹.
### 并行汉堡
现在让我们假设不是"并发汉堡",而是"并行汉堡"。
你和你的恋人一起去吃并行快餐。
你站在队伍中,同时是厨师的几个收银员(比方说8个)从前面的人那里接单。
你之前的每个人都在等待他们的汉堡准备好后才离开柜台,因为8名收银员都会在下一份订单前马上准备好汉堡。
<img src="/img/async/parallel-burgers/parallel-burgers-01.png" class="illustration">
然后,终于轮到你了,你为你的恋人和你订购了两个非常精美的汉堡。
你付钱了 💸。
<img src="/img/async/parallel-burgers/parallel-burgers-02.png" class="illustration">
收银员去厨房。
你站在柜台前 🕙等待着,这样就不会有人在你之前抢走你的汉堡,因为没有轮流的号码。
<img src="/img/async/parallel-burgers/parallel-burgers-03.png" class="illustration">
当你和你的恋人忙于不让任何人出现在你面前,并且在他们到来的时候拿走你的汉堡时,你无法关注到你的恋人。😞
这是"同步"的工作,你被迫与服务员/厨师 👨‍🍳"同步"。你在此必须等待 🕙 ,在收银员/厨师 👨‍🍳 完成汉堡并将它们交给你的确切时间到达之前一直等待,否则其他人可能会拿走它们。
<img src="/img/async/parallel-burgers/parallel-burgers-04.png" class="illustration">
你经过长时间的等待 🕙 ,收银员/厨师 👨‍🍳终于带着汉堡回到了柜台。
<img src="/img/async/parallel-burgers/parallel-burgers-05.png" class="illustration">
你拿着汉堡,和你的情人一起上桌。
你们仅仅是吃了它们,就结束了。⏹
<img src="/img/async/parallel-burgers/parallel-burgers-06.png" class="illustration">
没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。
!!! info
漂亮的插画来自 <a href="https://www.instagram.com/ketrinadrawsalot" class="external-link" target="_blank">Ketrina Thompson</a>. 🎨
---
在这个并行汉堡的场景中,你是一个计算机程序 🤖 且有两个处理器(你和你的恋人),都在等待 🕙 ,并投入他们的注意力 ⏯ 在柜台上等待了很长一段时间。
这家快餐店有 8 个处理器(收银员/厨师)。而并发汉堡店可能只有 2 个(一个收银员和一个厨师)。
但最终的体验仍然不是最好的。😞
---
这将是与汉堡的类似故事。🍔
一种更"贴近生活"的例子,想象一家银行。
直到最近,大多数银行都有多个出纳员 👨‍💼👨‍💼👨‍💼👨‍💼 还有一条长长排队队伍🕙🕙🕙🕙🕙🕙🕙🕙。
所有收银员都是一个接一个的在客户面前做完所有的工作👨‍💼⏯.
你必须经过 🕙 较长时间排队,否则你就没机会了。
你可不会想带你的恋人 😍 和你一起去银行办事🏦.
### 汉堡结论
在"你与恋人一起吃汉堡"的这个场景中,因为有很多人在等待🕙, 使用并发系统更有意义⏸🔀⏯.
大多数 Web 应用都是这样的。
你的服务器正在等待很多很多用户通过他们不太好的网络发送来的请求。
然后再次等待 🕙 响应回来。
这个"等待" 🕙 是以微秒为单位测量的,但总的来说,最后还是等待很久。
这就是为什么使用异步对于 Web API 很有意义的原因 ⏸🔀⏯。
这种异步机制正是 NodeJS 受到欢迎的原因(尽管 NodeJS 不是并行的),以及 Go 作为编程语言的优势所在。
这与 **FastAPI** 的性能水平相同。
您可以同时拥有并行性和异步性,您可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言(<a href="https://www.techempower.com/benchmarks/#section=data-r17&hw=ph&test=query&l=zijmkf-1" class="external-link" target="_blank">全部归功于 Starlette</a>)。
### 并发比并行好吗?
不!这不是故事的本意。
并发不同于并行。而是在需要大量等待的特定场景下效果更好。因此,在 Web 应用程序开发中,它通常比并行要好得多,但这并不意味着全部。
因此,为了平衡这一点,想象一下下面的短篇故事:
> 你必须打扫一个又大又脏的房子。
*是的,这就是完整的故事。*
---
在任何地方, 都不需要等待 🕙 ,只需要在房子的多个地方做着很多工作。
你可以像汉堡的例子那样轮流执行,先是客厅,然后是厨房,但因为你不需要等待 🕙 ,对于任何事情都是清洁,清洁,还是清洁,轮流不会影响任何事情。
无论是否轮流执行(并发),都需要相同的时间来完成,而你也会完成相同的工作量。
但在这种情况下,如果你能带上 8 名前收银员/厨师,现在是清洁工一起清扫,他们中的每一个人(加上你)都能占据房子的一个区域来清扫,你就可以在额外的帮助下并行的更快地完成所有工作。
在这个场景中,每个清洁工(包括您)都将是一个处理器,完成这个工作的一部分。
由于大多数执行时间是由实际工作(而不是等待)占用的,并且计算机中的工作是由 <abbr title="Central Processing Unit">CPU</abbr> 完成的,所以他们称这些问题为"CPU 密集型"。
---
CPU 密集型操作的常见示例是需要复杂的数学处理。
例如:
* **音频**或**图像**处理;
* **计算机视觉**: 一幅图像由数百万像素组成,每个像素有3种颜色值,处理通常需要同时对这些像素进行计算;
* **机器学习**: 它通常需要大量的"矩阵"和"向量"乘法。想象一个包含数字的巨大电子表格,并同时将所有数字相乘;
* **深度学习**: 这是机器学习的一个子领域,同样适用。只是没有一个数字的电子表格可以相乘,而是一个庞大的数字集合,在很多情况下,你需要使用一个特殊的处理器来构建和使用这些模型。
### 并发 + 并行: Web + 机器学习
使用 **FastAPI**,您可以利用 Web 开发中常见的并发机制的优势(NodeJS 的主要吸引力)。
并且,您也可以利用并行和多进程(让多个进程并行运行)的优点来处理与机器学习系统中类似的 **CPU 密集型** 工作。
这一点,再加上 Python 是**数据科学**、机器学习(尤其是深度学习)的主要语言这一简单事实,使得 **FastAPI** 与数据科学/机器学习 Web API 和应用程序(以及其他许多应用程序)非常匹配。
了解如何在生产环境中实现这种并行性,可查看此文 [Deployment](deployment/index.md){.internal-link target=_blank}。
## `async``await`
现代版本的 Python 有一种非常直观的方式来定义异步代码。这使它看起来就像正常的"顺序"代码,并在适当的时候"等待"。
当有一个操作需要等待才能给出结果,且支持这个新的 Python 特性时,您可以编写如下代码:
```Python
burgers = await get_burgers(2)
```
这里的关键是 `await`。它告诉 Python 它必须等待 ⏸ `get_burgers(2)` 完成它的工作 🕙 ,然后将结果存储在 `burgers` 中。这样,Python 就会知道此时它可以去做其他事情 🔀 ⏯ (比如接收另一个请求)。
要使 `await` 工作,它必须位于支持这种异步机制的函数内。因此,只需使用 `async def` 声明它:
```Python hl_lines="1"
async def get_burgers(number: int):
# Do some asynchronous stuff to create the burgers
return burgers
```
...而不是 `def`:
```Python hl_lines="2"
# This is not asynchronous
def get_sequential_burgers(number: int):
# Do some sequential stuff to create the burgers
return burgers
```
使用 `async def`,Python 就知道在该函数中,它将遇上 `await`,并且它可以"暂停" ⏸ 执行该函数,直至执行其他操作 🔀 后回来。
当你想调用一个 `async def` 函数时,你必须"等待"它。因此,这不会起作用:
```Python
# This won't work, because get_burgers was defined with: async def
burgers = get_burgers(2)
```
---
因此,如果您使用的库告诉您可以使用 `await` 调用它,则需要使用 `async def` 创建路径操作函数 ,如:
```Python hl_lines="2-3"
@app.get('/burgers')
async def read_burgers():
burgers = await get_burgers(2)
return burgers
```
### 更多技术细节
您可能已经注意到,`await` 只能在 `async def` 定义的函数内部使用。
但与此同时,必须"等待"通过 `async def` 定义的函数。因此,带 `async def` 的函数也只能在 `async def` 定义的函数内部调用。
那么,这关于先有鸡还是先有蛋的问题,如何调用第一个 `async` 函数?
如果您使用 **FastAPI**,你不必担心这一点,因为"第一个"函数将是你的路径操作函数,FastAPI 将知道如何做正确的事情。
但如果您想在没有 FastAPI 的情况下使用 `async` / `await`,则可以这样做。
### 编写自己的异步代码
Starlette (和 **FastAPI**) 是基于 <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a> 实现的,这使得它们可以兼容 Python 的标准库 <a href="https://docs.python.org/3/library/asyncio-task.html" class="external-link" target="_blank">asyncio</a><a href="https://trio.readthedocs.io/en/stable/" class="external-link" target="_blank">Trio</a>
特别是,你可以直接使用 <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a> 来处理高级的并发用例,这些用例需要在自己的代码中使用更高级的模式。
即使您没有使用 **FastAPI**,您也可以使用 <a href="https://anyio.readthedocs.io/en/stable/" class="external-link" target="_blank">AnyIO</a> 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。
### 其他形式的异步代码
这种使用 `async``await` 的风格在语言中相对较新。
但它使处理异步代码变得容易很多。
这种相同的语法(或几乎相同)最近也包含在现代版本的 JavaScript 中(在浏览器和 NodeJS 中)。
但在此之前,处理异步代码非常复杂和困难。
在以前版本的 Python,你可以使用多线程或者 <a href="https://www.gevent.org/" class="external-link" target="_blank">Gevent</a>。但代码的理解、调试和思考都要复杂许多。
在以前版本的 NodeJS / 浏览器 JavaScript 中,你会使用"回调",因此也可能导致<a href="http://callbackhell.com/" class="external-link" target="_blank">回调地狱</a>
## 协程
**协程**只是 `async def` 函数返回的一个非常奇特的东西的称呼。Python 知道它有点像一个函数,它可以启动,也会在某个时刻结束,而且它可能会在内部暂停 ⏸ ,只要内部有一个 `await`
通过使用 `async``await` 的异步代码的所有功能大多数被概括为"协程"。它可以与 Go 的主要关键特性 "Goroutines" 相媲美。
## 结论
让我们再来回顾下上文所说的:
> Python 的现代版本可以通过使用 `async``await` 语法创建**协程**,并用于支持**异步代码**。
现在应该能明白其含义了。✨
所有这些使得 FastAPI(通过 Starlette)如此强大,也是它拥有如此令人印象深刻的性能的原因。
## 非常技术性的细节
!!! warning
你可以跳过这里。
这些都是 FastAPI 如何在内部工作的技术细节。
如果您有相当多的技术知识(协程、线程、阻塞等),并且对 FastAPI 如何处理 `async def` 与常规 `def` 感到好奇,请继续。
### 路径操作函数
当你使用 `def` 而不是 `async def` 来声明一个*路径操作函数*时,它运行在外部的线程池中并等待其结果,而不是直接调用(因为它会阻塞服务器)。
如果您使用过另一个不以上述方式工作的异步框架,并且您习惯于用普通的 `def` 定义普通的仅计算路径操作函数,以获得微小的性能增益(大约100纳秒),请注意,在 FastAPI 中,效果将完全相反。在这些情况下,最好使用 `async def`,除非路径操作函数内使用执行阻塞 <abbr title="输入/输出:磁盘读写,网络通讯.">I/O</abbr> 的代码。
在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](/#performance){.internal-link target=_blank}。
### 依赖
这同样适用于[依赖](/tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。
### 子依赖
你可以拥有多个相互依赖的依赖以及[子依赖](/tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。
### 其他函数
您可直接调用通过 `def``async def` 创建的任何其他函数,FastAPI 不会影响您调用它们的方式。
这与 FastAPI 为您调用*路径操作函数*和依赖项的逻辑相反。
如果你的函数是通过 `def` 声明的,它将被直接调用(在代码中编写的地方),而不会在线程池中,如果这个函数通过 `async def` 声明,当在代码中调用时,你就应该使用 `await` 等待函数的结果。
---
再次提醒,这些是非常技术性的细节,如果你来搜索它可能对你有用。
否则,您最好应该遵守的指导原则<a href="#_1">赶时间吗?</a>.

214
docs/zh/docs/tutorial/security/simple-oauth2.md

@ -1,94 +1,98 @@
# 使用密码和 Bearer 的简单 OAuth2
# OAuth2 实现简单的 Password 和 Bearer 验证
现在让我们接着上一章继续开发,并添加缺少的部分以实现一个完整的安全性流程
本章添加上一章示例中欠缺的部分,实现完整的安全流
## 获取 `username``password`
我们将使用 **FastAPI** 的安全性实用工具来获取 `username``password`
首先,使用 **FastAPI** 安全工具获取 `username``password`
OAuth2 规定在使用(我们打算用的)「password 流程」时,客户端/用户必须将 `username``password` 字段作为表单数据发送
OAuth2 规范要求使用**密码流**时,客户端或用户必须以表单数据形式发送 `username``password` 字段。
而且规范明确了字段必须这样命名。因此 `user-name``email` 是行不通的
并且,这两个字段必须命名为 `username``password` ,不能使用 `user-name``email` 等其它名称
不过不用担心,你可以在前端按照你的想法将它展示给最终用户
不过也不用担心,前端仍可以显示终端用户所需的名称
而且你的数据库模型也可以使用你想用的任何其他名称。
数据库模型也可以使用所需的名称。
是对于登录*路径操作*,我们需要使用这些名称来与规范兼容(以具备例如使用集成的 API 文档系统的能力)。
对于登录*路径操作*,则要使用兼容规范的 `username``password`,(例如,实现与 API 文档集成)。
规范还写明了 `username``password` 必须作为表单数据发送(因此,此处不能使用 JSON)
该规范要求必须以表单数据形式发送 `username``password`,因此,不能使用 JSON 对象
### `scope`
### `Scope`(作用域)
规范还提到客户端可以发送另一个表单字段「`scope`」
OAuth2 还支持客户端发送**`scope`**表单字段
这个表单字段的名称为 `scope`(单数形式),但实际上它是一个由空格分隔的「作用域」组成的长字符串。
虽然表单字段的名称是 `scope`(单数),但实际上,它是以空格分隔的,由多个**scope**组成的长字符串。
每个「作用域」只是一个字符串(中间没有空格)
**作用域**只是不带空格的字符串
它们通常用于声明特定的安全权限,例如:
常用于声明指定安全权限,例如:
* `users:read` 或者 `users:write` 是常见的例子。
* Facebook / Instagram 使用 `instagram_basic`
* Google 使用了 `https://www.googleapis.com/auth/drive`
* 常见用例为,`users:read` 或 `users:write`
* 脸书和 Instagram 使用 `instagram_basic`
* 谷歌使用 `https://www.googleapis.com/auth/drive`
!!! info
在 OAuth2 中「作用域」只是一个声明所需特定权限的字符串。
!!! info "说明"
它有没有 `:` 这样的其他字符或者是不是 URL 都没有关系
OAuth2 中,**作用域**只是声明指定权限的字符串
这些细节是具体的实现
是否使用冒号 `:` 等符号,或是不是 URL 并不重要
对 OAuth2 来说它们就只是字符串而已。
这些细节只是特定的实现方式。
对 OAuth2 来说,都只是字符串而已。
## 获取 `username``password` 的代码
现在,让我们使用 **FastAPI** 提供的实用工具来处理此问题
接下来,使用 **FastAPI** 工具获取用户名与密码
### `OAuth2PasswordRequestForm`
首先,导入 `OAuth2PasswordRequestForm`,然后`token` 的*路径操作*中通过 `Depends` 将其作为依赖项使用
首先,导入 `OAuth2PasswordRequestForm`,然后,在 `/token` *路径操作* 中,用 `Depends` 把该类作为依赖项
```Python hl_lines="4 76"
{!../../../docs_src/security/tutorial003.py!}
```
`OAuth2PasswordRequestForm` 是一个类依赖项,声明了如下的请求表单:
`OAuth2PasswordRequestForm` 是用以下几项内容声明表单请求体的类依赖项:
* `username`
* `password`
* 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串
* 可选的 `grant_type`
* `username`
* `password`
* 一个可选的 `scope` 字段,是一个由空格分隔的字符串组成的大字符串。
* 一个可选的 `grant_type`.
!!! tip "提示"
!!! tip
OAuth2 规范实际上*要求* `grant_type` 字段使用一个固定的值 `password`,但是 `OAuth2PasswordRequestForm` 没有作强制约束。
实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。
果你需要强制要求这一点,请使用 `OAuth2PasswordRequestFormStrict` 而不是 `OAuth2PasswordRequestForm`
需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`
* 一个可选的 `client_id`(我们的示例不需要它)。
* 一个可选的 `client_secret`我们的示例不需要它)。
* 可选的 `client_id`(本例未使用)
* 可选的 `client_secret`本例未使用)
!!! info
`OAuth2PasswordRequestForm` 并不像 `OAuth2PasswordBearer` 一样是 FastAPI 的一个特殊的类。
!!! info "说明"
`OAuth2PasswordBearer` 使得 **FastAPI** 明白它是一个安全方案。所以它得以通过这种方式添加到 OpenAPI 中
`OAuth2PasswordRequestForm``OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类
`OAuth2PasswordRequestForm` 只是一个你可以自己编写的类依赖项,或者你也可以直接声明 `Form` 参数
**FastAPI**`OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI
但是由于这是一种常见的使用场景,因此 FastAPI 出于简便直接提供了它。
`OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。
但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。
### 使用表单数据
!!! tip
类依赖项 `OAuth2PasswordRequestForm` 的实例不会有用空格分隔的长字符串属性 `scope`,而是具有一个 `scopes` 属性,该属性将包含实际被发送的每个作用域字符串组成的列表。
!!! tip "提示"
`OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。
在此示例中我们没有使用 `scopes`,但如果你需要的话可以使用该功能
本例没有使用 `scopes`,但开发者也可以根据需要使用该属性
现在,使用表单字段中的 `username` 从(伪)数据库中获取用户数据。
现在,即可使用表单字段 `username`从(伪)数据库中获取用户数据。
如果没有这个用户,我们将返回一个错误消息,提示「用户名或密码错误」
如果不存在指定用户,则返回错误消息,提示**用户名或密码错误**
对于这个错误,我们使用 `HTTPException` 异常:
本例使用 `HTTPException` 异常显示此错误
```Python hl_lines="3 77-79"
{!../../../docs_src/security/tutorial003.py!}
@ -96,27 +100,27 @@ OAuth2 规定在使用(我们打算用的)「password 流程」时,客户
### 校验密码
目前我们已经从数据库中获取了用户数据,但尚未校验密码。
至此,我们已经从数据库中获取了用户数据,但尚未校验密码。
让我们首先将这些数据放入 Pydantic `UserInDB` 模型中
接下来,首先将数据放入 Pydantic 的 `UserInDB` 模型
永远不要保存明文密码,因此,我们将使用(伪)哈希密码系统。
注意:永远不要保存明文密码,本例暂时先使用(伪)哈希密码系统。
如果密码不匹配,我们将返回同一个错误。
如果密码不匹配,则返回与上面相同的错误。
#### 哈希密码
#### 密码哈希
「哈希」的意思是:将某些内容(在本例中为密码)转换为看起来像乱码的字节序列(只是一个字符串)。
**哈希**是指,将指定内容(本例中为密码)转换为形似乱码的字节序列(其实就是字符串)。
每次传入完全相同的内容(完全相同的密码)时,你都会得到完全相同的乱码。
每次传入完全相同的内容(比如,完全相同的密码)时,得到的都是完全相同的乱码。
是你不能从乱码转换回密码。
这个乱码无法转换回传入的密码。
##### 为什么使用哈希密码
##### 为什么使用密码哈希
如果你的数据库被盗,小偷将无法获得用户的明文密码,只有哈希值。
原因很简单,假如数据库被盗,窃贼无法获取用户的明文密码,得到的只是哈希值。
因此,小偷将无法尝试在另一个系统中使用这些相同的密码(由于许多用户在任何地方都使用相同的密码,因此这很危险)
这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大
```Python hl_lines="80-83"
{!../../../docs_src/security/tutorial003.py!}
@ -124,9 +128,9 @@ OAuth2 规定在使用(我们打算用的)「password 流程」时,客户
#### 关于 `**user_dict`
`UserInDB(**user_dict)` 表示
`UserInDB(**user_dict)` 是指
*直接`user_dict` 的键和值作为关键字参数传递,等同于:*
*直接`user_dict` 的键与值当作关键字参数传递,等效于:*
```Python
UserInDB(
@ -138,75 +142,79 @@ UserInDB(
)
```
!!! info
有关 `user_dict` 的更完整说明,请参阅[**额外的模型**文档](../extra-models.md#about-user_indict){.internal-link target=_blank}。
!!! info "说明"
## 返回令牌
`user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#about-user_indict){.internal-link target=_blank}。
`token` 端点的响应必须是一个 JSON 对象。
## 返回 Token
它应该有一个 `token_type`。在我们的例子中,由于我们使用的是「Bearer」令牌,因此令牌类型应为「`bearer`」
`token` 端点的响应必须是 JSON 对象
并且还应该有一个 `access_token` 字段,它是一个包含我们的访问令牌的字符串
响应返回的内容应该包含 `token_type`。本例中用的是**Bearer**Token,因此, Token 类型应为**`bearer`**
对于这个简单的示例,我们将极其不安全地返回相同的 `username` 作为令牌
返回内容还应包含 `access_token` 字段,它是包含权限 Token 的字符串
!!! tip
在下一章中,你将看到一个真实的安全实现,使用了哈希密码和 <abbr title="JSON Web Tokens">JWT</abbr> 令牌。
本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。
但现在,让我们仅关注我们需要的特定细节。
!!! tip "提示"
下一章介绍使用哈希密码和 <abbr title="JSON Web Tokens">JWT</abbr> Token 的真正安全机制。
但现在,仅关注所需的特定细节。
```Python hl_lines="85"
{!../../../docs_src/security/tutorial003.py!}
```
!!! tip
根据规范,你应该像本示例一样,返回一个带有 `access_token``token_type` 的 JSON。
!!! tip "提示"
这是你必须在代码中自行完成的工作,并且要确保使用了这些 JSON 字段
按规范的要求,应像本示例一样,返回带有 `access_token``token_type` 的 JSON 对象
几乎是唯一的你需要自己记住并正确地执行以符合规范的事情
是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键
其余的,**FastAPI** 都会为你处理。
这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。
**FastAPI** 则负责处理其它的工作。
## 更新依赖项
现在我们将更新我们的依赖项。
接下来,更新依赖项。
我们想要仅当此用户处于启用状态时才能获取 `current_user`
使之仅在当前用户为激活状态时,才能获取 `current_user`
因此,我们创建了一个额外的依赖项 `get_current_active_user`,而该依赖项又以 `get_current_user` 作为依赖项
为此,要再创建一个依赖项 `get_current_active_user`,此依赖项以 `get_current_user` 依赖项为基础
如果用户不存在或处于未启用状态,则这两个依赖项都将仅返回 HTTP 错误。
如果用户不存在,或状态为未激活,这两个依赖项都会返回 HTTP 错误。
因此,在我们的端点中,只有当用户存在,身份认证通过且处于启用状态时,我们才能获得该用户:
因此,在端点中,只有当用户存在、通过身份验证、且状态为激活时,才能获得该用户:
```Python hl_lines="58-67 69-72 90"
{!../../../docs_src/security/tutorial003.py!}
```
!!! info
我们在此处返回的值为 `Bearer` 的额外响应头 `WWW-Authenticate` 也是规范的一部分。
!!! info "说明"
此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。
任何的 401「未认证」HTTP(错误)状态码都应该返回 `WWW-Authenticate` 响应头。
任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。
对于 bearer 令牌(我们的例子),该响应头的值应为 `Bearer`
本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`
实际上你可以忽略这个额外的响应头,不会有什么问题。
实际上,忽略这个附加响应头,也不会有什么问题。
但此处提供了它以符合规范
之所以在此提供这个附加响应头,是为了符合规范的要求
而且,(现在或将来)可能会有工具期望得到并使用它,然后对你或你的用户有用处
说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上
这就是遵循标准的好处...
这就是遵循标准的好处……
## 实际效果
打开交互式文档:<a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>
打开 API 文档:<a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>
### 身份
### 身份
点击「Authorize」按钮。
点击**Authorize**按钮。
使用以下凭证:
@ -216,15 +224,15 @@ UserInDB(
<img src="https://fastapi.tiangolo.com/img/tutorial/security/image04.png">
在系统中进行身份认证后,你将看到
通过身份验证后,显示下图所示的内容
<img src="https://fastapi.tiangolo.com/img/tutorial/security/image05.png">
### 获取本人的用户数据
### 获取当前用户数据
现在执行 `/users/me` 路径的 `GET` 操作。
使用 `/users/me` 路径的 `GET` 操作。
你将获得你的用户数据,如
可以提取如下当前用户数据
```JSON
{
@ -238,7 +246,7 @@ UserInDB(
<img src="https://fastapi.tiangolo.com/img/tutorial/security/image06.png">
如果你点击锁定图标并注销,然后再次尝试同一操作,则会得到 HTTP 401 错误:
点击小锁图标,注销后,再执行同样的操作,则会得到 HTTP 401 错误:
```JSON
{
@ -246,17 +254,17 @@ UserInDB(
}
```
### 未启用的用户
### 未激活用户
现在尝试使用未启用的用户,并通过以下方式进行身份认证:
测试未激活用户,输入以下信息,进行身份验证:
用户名:`alice`
密码:`secret2`
然后尝试执行 `/users/me` 路径的 `GET` 操作。
然后执行 `/users/me` 路径的 `GET` 操作。
你将得到一个「未启用的用户」错误,如
显示下列**未激活用户**错误信息
```JSON
{
@ -264,12 +272,12 @@ UserInDB(
}
```
##
##
现在你掌握了为你的 API 实现一个基于 `username``password` 的完整安全系统的工具
使用本章的工具实现基于 `username``password` 的完整 API 安全系统。
使用这些工具,你可以使安全系统与任何数据库以及任何用户或数据模型兼容
这些工具让安全系统兼容任何数据库、用户及数据模型
唯一缺少的细节是它实际上还并不「安全」
唯一欠缺的是,它仍然不是真的**安全**
在下一章中,你将看到如何使用一个安全的哈希密码库和 <abbr title="JSON Web Tokens">JWT</abbr> 令牌。
下一章,介绍使用密码哈希支持库与 <abbr title="JSON Web Tokens">JWT</abbr> 令牌实现真正的安全机制

2
fastapi/__init__.py

@ -1,6 +1,6 @@
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
__version__ = "0.103.1"
__version__ = "0.103.2"
from starlette import status as status

14
fastapi/_compat.py

@ -58,9 +58,15 @@ if PYDANTIC_V2:
from pydantic_core import CoreSchema as CoreSchema
from pydantic_core import PydanticUndefined, PydanticUndefinedType
from pydantic_core import Url as Url
from pydantic_core.core_schema import (
general_plain_validator_function as general_plain_validator_function,
)
try:
from pydantic_core.core_schema import (
with_info_plain_validator_function as with_info_plain_validator_function,
)
except ImportError: # pragma: no cover
from pydantic_core.core_schema import (
general_plain_validator_function as with_info_plain_validator_function, # noqa: F401
)
Required = PydanticUndefined
Undefined = PydanticUndefined
@ -348,7 +354,7 @@ else:
class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef]
pass
def general_plain_validator_function( # type: ignore[misc]
def with_info_plain_validator_function( # type: ignore[misc]
function: Callable[..., Any],
*,
ref: Union[str, None] = None,

4
fastapi/datastructures.py

@ -5,7 +5,7 @@ from fastapi._compat import (
CoreSchema,
GetJsonSchemaHandler,
JsonSchemaValue,
general_plain_validator_function,
with_info_plain_validator_function,
)
from starlette.datastructures import URL as URL # noqa: F401
from starlette.datastructures import Address as Address # noqa: F401
@ -49,7 +49,7 @@ class UploadFile(StarletteUploadFile):
def __get_pydantic_core_schema__(
cls, source: Type[Any], handler: Callable[[Any], CoreSchema]
) -> CoreSchema:
return general_plain_validator_function(cls._validate)
return with_info_plain_validator_function(cls._validate)
class DefaultPlaceholder:

4
fastapi/openapi/models.py

@ -7,7 +7,7 @@ from fastapi._compat import (
GetJsonSchemaHandler,
JsonSchemaValue,
_model_rebuild,
general_plain_validator_function,
with_info_plain_validator_function,
)
from fastapi.logger import logger
from pydantic import AnyUrl, BaseModel, Field
@ -52,7 +52,7 @@ except ImportError: # pragma: no cover
def __get_pydantic_core_schema__(
cls, source: Type[Any], handler: Callable[[Any], CoreSchema]
) -> CoreSchema:
return general_plain_validator_function(cls._validate)
return with_info_plain_validator_function(cls._validate)
class Contact(BaseModel):

2
tests/test_compat.py

@ -24,7 +24,7 @@ def test_model_field_default_required():
@needs_pydanticv1
def test_upload_file_dummy_general_plain_validator_function():
def test_upload_file_dummy_with_info_plain_validator_function():
# For coverage
assert UploadFile.__get_pydantic_core_schema__(str, lambda x: None) == {}

4
tests/test_filter_pydantic_sub_model_pv2.py

@ -12,7 +12,7 @@ from .utils import needs_pydanticv2
@pytest.fixture(name="client")
def get_client():
from pydantic import BaseModel, FieldValidationInfo, field_validator
from pydantic import BaseModel, ValidationInfo, field_validator
app = FastAPI()
@ -28,7 +28,7 @@ def get_client():
foo: ModelB
@field_validator("name")
def lower_username(cls, name: str, info: FieldValidationInfo):
def lower_username(cls, name: str, info: ValidationInfo):
if not name.endswith("A"):
raise ValueError("name must end in A")
return name

6
tests/test_openapi_separate_input_output_schemas.py

@ -4,19 +4,23 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
from .utils import needs_pydanticv2
from .utils import PYDANTIC_V2, needs_pydanticv2
class SubItem(BaseModel):
subname: str
sub_description: Optional[str] = None
tags: List[str] = []
if PYDANTIC_V2:
model_config = {"json_schema_serialization_defaults_required": True}
class Item(BaseModel):
name: str
description: Optional[str] = None
sub: Optional[SubItem] = None
if PYDANTIC_V2:
model_config = {"json_schema_serialization_defaults_required": True}
def get_app_client(separate_input_output_schemas: bool = True) -> TestClient:

38
tests/test_tutorial/test_body_updates/test_tutorial001.py

@ -52,9 +52,7 @@ def test_openapi_schema(client: TestClient):
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item-Output"
}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
@ -86,9 +84,7 @@ def test_openapi_schema(client: TestClient):
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item-Output"
}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
@ -116,7 +112,7 @@ def test_openapi_schema(client: TestClient):
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item-Input"}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
@ -126,35 +122,9 @@ def test_openapi_schema(client: TestClient):
},
"components": {
"schemas": {
"Item-Input": {
"title": "Item",
"Item": {
"type": "object",
"properties": {
"name": {
"title": "Name",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"price": {
"title": "Price",
"anyOf": [{"type": "number"}, {"type": "null"}],
},
"tax": {"title": "Tax", "type": "number", "default": 10.5},
"tags": {
"title": "Tags",
"type": "array",
"items": {"type": "string"},
"default": [],
},
},
},
"Item-Output": {
"title": "Item",
"type": "object",
"required": ["name", "description", "price", "tax", "tags"],
"properties": {
"name": {
"anyOf": [{"type": "string"}, {"type": "null"}],

38
tests/test_tutorial/test_body_updates/test_tutorial001_py310.py

@ -55,9 +55,7 @@ def test_openapi_schema(client: TestClient):
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item-Output"
}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
@ -89,9 +87,7 @@ def test_openapi_schema(client: TestClient):
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item-Output"
}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
@ -119,7 +115,7 @@ def test_openapi_schema(client: TestClient):
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item-Input"}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
@ -129,35 +125,9 @@ def test_openapi_schema(client: TestClient):
},
"components": {
"schemas": {
"Item-Input": {
"title": "Item",
"Item": {
"type": "object",
"properties": {
"name": {
"title": "Name",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"price": {
"title": "Price",
"anyOf": [{"type": "number"}, {"type": "null"}],
},
"tax": {"title": "Tax", "type": "number", "default": 10.5},
"tags": {
"title": "Tags",
"type": "array",
"items": {"type": "string"},
"default": [],
},
},
},
"Item-Output": {
"title": "Item",
"type": "object",
"required": ["name", "description", "price", "tax", "tags"],
"properties": {
"name": {
"anyOf": [{"type": "string"}, {"type": "null"}],

38
tests/test_tutorial/test_body_updates/test_tutorial001_py39.py

@ -55,9 +55,7 @@ def test_openapi_schema(client: TestClient):
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item-Output"
}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
@ -89,9 +87,7 @@ def test_openapi_schema(client: TestClient):
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item-Output"
}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
@ -119,7 +115,7 @@ def test_openapi_schema(client: TestClient):
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item-Input"}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
@ -129,35 +125,9 @@ def test_openapi_schema(client: TestClient):
},
"components": {
"schemas": {
"Item-Input": {
"title": "Item",
"Item": {
"type": "object",
"properties": {
"name": {
"title": "Name",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"price": {
"title": "Price",
"anyOf": [{"type": "number"}, {"type": "null"}],
},
"tax": {"title": "Tax", "type": "number", "default": 10.5},
"tags": {
"title": "Tags",
"type": "array",
"items": {"type": "string"},
"default": [],
},
},
},
"Item-Output": {
"title": "Item",
"type": "object",
"required": ["name", "description", "price", "tax", "tags"],
"properties": {
"name": {
"anyOf": [{"type": "string"}, {"type": "null"}],

22
tests/test_tutorial/test_dataclasses/test_tutorial003.py

@ -79,9 +79,7 @@ def test_openapi_schema():
"schema": {
"title": "Items",
"type": "array",
"items": {
"$ref": "#/components/schemas/Item-Input"
},
"items": {"$ref": "#/components/schemas/Item"},
}
}
},
@ -136,14 +134,14 @@ def test_openapi_schema():
"schemas": {
"Author": {
"title": "Author",
"required": ["name", "items"],
"required": ["name"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"items": {
"title": "Items",
"type": "array",
"items": {"$ref": "#/components/schemas/Item-Output"},
"items": {"$ref": "#/components/schemas/Item"},
},
},
},
@ -158,27 +156,15 @@ def test_openapi_schema():
}
},
},
"Item-Input": {
"Item": {
"title": "Item",
"required": ["name"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
},
},
"Item-Output": {
"title": "Item",
"required": ["name", "description"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
},
},

32
tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py

@ -34,9 +34,7 @@ def test_openapi_schema():
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item-Output"
}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
@ -57,7 +55,7 @@ def test_openapi_schema():
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item-Input"}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
@ -67,7 +65,7 @@ def test_openapi_schema():
},
"components": {
"schemas": {
"Item-Input": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
@ -91,30 +89,6 @@ def test_openapi_schema():
},
},
},
"Item-Output": {
"title": "Item",
"required": ["name", "description", "price", "tax", "tags"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {
"title": "Description",
"anyOf": [{"type": "string"}, {"type": "null"}],
},
"price": {"title": "Price", "type": "number"},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
},
"tags": {
"title": "Tags",
"uniqueItems": True,
"type": "array",
"items": {"type": "string"},
"default": [],
},
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],

32
tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py

@ -34,9 +34,7 @@ def test_openapi_schema():
"description": "The created item",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item-Output"
}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
@ -57,7 +55,7 @@ def test_openapi_schema():
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item-Input"}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
@ -67,7 +65,7 @@ def test_openapi_schema():
},
"components": {
"schemas": {
"Item-Input": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
@ -91,30 +89,6 @@ def test_openapi_schema():
},
},
},
"Item-Output": {
"title": "Item",
"required": ["name", "description", "price", "tax", "tags"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Description",
},
"price": {"title": "Price", "type": "number"},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
},
"tags": {
"title": "Tags",
"uniqueItems": True,
"type": "array",
"items": {"type": "string"},
"default": [],
},
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],

32
tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py

@ -41,9 +41,7 @@ def test_openapi_schema(client: TestClient):
"description": "The created item",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item-Output"
}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
@ -64,7 +62,7 @@ def test_openapi_schema(client: TestClient):
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item-Input"}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
@ -74,7 +72,7 @@ def test_openapi_schema(client: TestClient):
},
"components": {
"schemas": {
"Item-Input": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
@ -98,30 +96,6 @@ def test_openapi_schema(client: TestClient):
},
},
},
"Item-Output": {
"title": "Item",
"required": ["name", "description", "price", "tax", "tags"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Description",
},
"price": {"title": "Price", "type": "number"},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
},
"tags": {
"title": "Tags",
"uniqueItems": True,
"type": "array",
"items": {"type": "string"},
"default": [],
},
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],

32
tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py

@ -41,9 +41,7 @@ def test_openapi_schema(client: TestClient):
"description": "The created item",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item-Output"
}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
@ -64,7 +62,7 @@ def test_openapi_schema(client: TestClient):
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item-Input"}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
@ -74,7 +72,7 @@ def test_openapi_schema(client: TestClient):
},
"components": {
"schemas": {
"Item-Input": {
"Item": {
"title": "Item",
"required": ["name", "price"],
"type": "object",
@ -98,30 +96,6 @@ def test_openapi_schema(client: TestClient):
},
},
},
"Item-Output": {
"title": "Item",
"required": ["name", "description", "price", "tax", "tags"],
"type": "object",
"properties": {
"name": {"title": "Name", "type": "string"},
"description": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Description",
},
"price": {"title": "Price", "type": "number"},
"tax": {
"title": "Tax",
"anyOf": [{"type": "number"}, {"type": "null"}],
},
"tags": {
"title": "Tags",
"uniqueItems": True,
"type": "array",
"items": {"type": "string"},
"default": [],
},
},
},
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],

4
tests/test_tutorial/test_path_params/test_tutorial005.py

@ -33,9 +33,9 @@ def test_get_enums_invalid():
{
"type": "enum",
"loc": ["path", "model_name"],
"msg": "Input should be 'alexnet','resnet' or 'lenet'",
"msg": "Input should be 'alexnet', 'resnet' or 'lenet'",
"input": "foo",
"ctx": {"expected": "'alexnet','resnet' or 'lenet'"},
"ctx": {"expected": "'alexnet', 'resnet' or 'lenet'"},
}
]
}

20
tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py

@ -48,9 +48,7 @@ def test_openapi_schema(client: TestClient) -> None:
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/Item-Output"
},
"items": {"$ref": "#/components/schemas/Item"},
"type": "array",
"title": "Response Read Items Items Get",
}
@ -65,7 +63,7 @@ def test_openapi_schema(client: TestClient) -> None:
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item-Input"}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
@ -102,7 +100,7 @@ def test_openapi_schema(client: TestClient) -> None:
"type": "object",
"title": "HTTPValidationError",
},
"Item-Input": {
"Item": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {
@ -114,18 +112,6 @@ def test_openapi_schema(client: TestClient) -> None:
"required": ["name"],
"title": "Item",
},
"Item-Output": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Description",
},
},
"type": "object",
"required": ["name", "description"],
"title": "Item",
},
"ValidationError": {
"properties": {
"loc": {

20
tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py

@ -51,9 +51,7 @@ def test_openapi_schema(client: TestClient) -> None:
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/Item-Output"
},
"items": {"$ref": "#/components/schemas/Item"},
"type": "array",
"title": "Response Read Items Items Get",
}
@ -68,7 +66,7 @@ def test_openapi_schema(client: TestClient) -> None:
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item-Input"}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
@ -105,7 +103,7 @@ def test_openapi_schema(client: TestClient) -> None:
"type": "object",
"title": "HTTPValidationError",
},
"Item-Input": {
"Item": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {
@ -117,18 +115,6 @@ def test_openapi_schema(client: TestClient) -> None:
"required": ["name"],
"title": "Item",
},
"Item-Output": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Description",
},
},
"type": "object",
"required": ["name", "description"],
"title": "Item",
},
"ValidationError": {
"properties": {
"loc": {

20
tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py

@ -51,9 +51,7 @@ def test_openapi_schema(client: TestClient) -> None:
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/Item-Output"
},
"items": {"$ref": "#/components/schemas/Item"},
"type": "array",
"title": "Response Read Items Items Get",
}
@ -68,7 +66,7 @@ def test_openapi_schema(client: TestClient) -> None:
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item-Input"}
"schema": {"$ref": "#/components/schemas/Item"}
}
},
"required": True,
@ -105,7 +103,7 @@ def test_openapi_schema(client: TestClient) -> None:
"type": "object",
"title": "HTTPValidationError",
},
"Item-Input": {
"Item": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {
@ -117,18 +115,6 @@ def test_openapi_schema(client: TestClient) -> None:
"required": ["name"],
"title": "Item",
},
"Item-Output": {
"properties": {
"name": {"type": "string", "title": "Name"},
"description": {
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "Description",
},
},
"type": "object",
"required": ["name", "description"],
"title": "Item",
},
"ValidationError": {
"properties": {
"loc": {

Loading…
Cancel
Save