From dc2fdd56af0fc9f98179486151650c522530a7e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 20 Dec 2023 18:05:37 +0100 Subject: [PATCH 001/217] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20(#10567)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/github_sponsors.yml | 97 ++++++++++----------- docs/en/data/people.yml | 142 +++++++++++++++++-------------- 2 files changed, 124 insertions(+), 115 deletions(-) diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index b9d74ea7b1db3..43b4b8c6b3280 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -1,5 +1,8 @@ sponsors: -- - login: bump-sh +- - login: codacy + avatarUrl: https://avatars.githubusercontent.com/u/1834093?v=4 + url: https://github.com/codacy + - login: bump-sh avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 url: https://github.com/bump-sh - login: cryptapi @@ -11,9 +14,6 @@ sponsors: - login: fern-api avatarUrl: https://avatars.githubusercontent.com/u/102944815?v=4 url: https://github.com/fern-api - - login: nanram22 - avatarUrl: https://avatars.githubusercontent.com/u/116367316?v=4 - url: https://github.com/nanram22 - - login: nihpo avatarUrl: https://avatars.githubusercontent.com/u/1841030?u=0264956d7580f7e46687a762a7baa629f84cf97c&v=4 url: https://github.com/nihpo @@ -32,12 +32,12 @@ sponsors: - login: deepset-ai avatarUrl: https://avatars.githubusercontent.com/u/51827949?v=4 url: https://github.com/deepset-ai + - login: databento + avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4 + url: https://github.com/databento - 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 @@ -65,10 +65,7 @@ sponsors: - login: Trivie avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4 url: https://github.com/Trivie -- - login: moellenbeck - avatarUrl: https://avatars.githubusercontent.com/u/169372?v=4 - url: https://github.com/moellenbeck - - login: birkjernstrom +- - login: birkjernstrom avatarUrl: https://avatars.githubusercontent.com/u/281715?u=4be14b43f76b4bd497b1941309bb390250b405e6&v=4 url: https://github.com/birkjernstrom - login: yasyf @@ -83,15 +80,15 @@ sponsors: - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries + - login: deployplex + avatarUrl: https://avatars.githubusercontent.com/u/57115726?v=4 + url: https://github.com/deployplex - - login: povilasb avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 url: https://github.com/povilasb - login: primer-io avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4 url: https://github.com/primer-io -- - login: NateXVI - avatarUrl: https://avatars.githubusercontent.com/u/48195620?u=4bc8751ae50cb087c40c1fe811764aa070b9eea6&v=4 - url: https://github.com/NateXVI - - login: Kludex avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex @@ -125,12 +122,12 @@ sponsors: - login: tcsmith avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 url: https://github.com/tcsmith - - login: mrkmcknz - avatarUrl: https://avatars.githubusercontent.com/u/1089376?u=2b9b8a8c25c33a4f6c220095638bd821cdfd13a3&v=4 - url: https://github.com/mrkmcknz - login: mickaelandrieu avatarUrl: https://avatars.githubusercontent.com/u/1247388?u=599f6e73e452a9453f2bd91e5c3100750e731ad4&v=4 url: https://github.com/mickaelandrieu + - login: knallgelb + avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4 + url: https://github.com/knallgelb - login: Shark009 avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4 url: https://github.com/Shark009 @@ -174,7 +171,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/6152183?u=c485eefca5c6329600cae63dd35e4f5682ce6924&v=4 url: https://github.com/iwpnd - login: FernandoCelmer - avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=ab6108a843a2fb9df0934f482375d2907609f3ff&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4 url: https://github.com/FernandoCelmer - login: simw avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 @@ -188,6 +185,9 @@ sponsors: - login: wdwinslow avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 url: https://github.com/wdwinslow + - login: drcat101 + avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 + url: https://github.com/drcat101 - login: jsoques avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4 url: https://github.com/jsoques @@ -212,9 +212,6 @@ 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 @@ -269,9 +266,12 @@ sponsors: - login: pyt3h avatarUrl: https://avatars.githubusercontent.com/u/99658549?v=4 url: https://github.com/pyt3h -- - login: SebTota - avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 - url: https://github.com/SebTota + - login: apitally + avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4 + url: https://github.com/apitally +- - login: getsentry + avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4 + url: https://github.com/getsentry - - login: pawamoy avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 url: https://github.com/pawamoy @@ -299,6 +299,9 @@ sponsors: - login: securancy avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 url: https://github.com/securancy + - login: natehouk + avatarUrl: https://avatars.githubusercontent.com/u/805439?u=d8e4be629dc5d7efae7146157e41ee0bd129d9bc&v=4 + url: https://github.com/natehouk - login: browniebroke avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 url: https://github.com/browniebroke @@ -323,9 +326,9 @@ sponsors: - login: anthonycorletti avatarUrl: https://avatars.githubusercontent.com/u/3477132?v=4 url: https://github.com/anthonycorletti - - login: nikeee - avatarUrl: https://avatars.githubusercontent.com/u/4068864?u=bbe73151f2b409c120160d032dc9aa6875ef0c4b&v=4 - url: https://github.com/nikeee + - login: erhan + avatarUrl: https://avatars.githubusercontent.com/u/3872888?u=cd9a20fcd33c5598d9d7797a78dedfc9148592f6&v=4 + url: https://github.com/erhan - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa @@ -366,7 +369,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/8574425?u=aad2a9674273c9275fe414d99269b7418d144089&v=4 url: https://github.com/albertkun - login: xncbf - avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=866a1311e4bd3ec5ae84185c4fcc99f397c883d7&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=05cb2d7c797a02f666805ad4639d9582f31d432c&v=4 url: https://github.com/xncbf - login: DMantis avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 @@ -398,9 +401,6 @@ sponsors: - login: jangia 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=264d7db95c28156363760229c30ee1116efd4eeb&v=4 - url: https://github.com/timzaz - login: shuheng-liu avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4 url: https://github.com/shuheng-liu @@ -419,15 +419,15 @@ 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 - login: mertguvencli avatarUrl: https://avatars.githubusercontent.com/u/29762151?u=16a906d90df96c8cff9ea131a575c4bc171b1523&v=4 url: https://github.com/mertguvencli + - login: White-Mask + avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 + url: https://github.com/White-Mask - login: HosamAlmoghraby avatarUrl: https://avatars.githubusercontent.com/u/32025281?u=aa1b09feabccbf9dc506b81c71155f32d126cefa&v=4 url: https://github.com/HosamAlmoghraby @@ -435,14 +435,11 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 url: https://github.com/engineerjoe440 - login: bnkc - avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=1a104991a2ea90bfe304bc0b9ef191c7e4891a0e&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=ea88e4bd668c984cff1bca3e71ab2deb37fafdc4&v=4 url: https://github.com/bnkc - login: declon avatarUrl: https://avatars.githubusercontent.com/u/36180226?v=4 url: https://github.com/declon - - 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 @@ -458,9 +455,6 @@ sponsors: - login: ArtyomVancyan avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 url: https://github.com/ArtyomVancyan - - login: josehenriqueroveda - avatarUrl: https://avatars.githubusercontent.com/u/46685746?u=2e672057a7dbe1dba47e57c378fc0cac336022eb&v=4 - url: https://github.com/josehenriqueroveda - login: hgalytoby avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4 url: https://github.com/hgalytoby @@ -473,12 +467,18 @@ sponsors: - login: 0417taehyun avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 url: https://github.com/0417taehyun + - login: fernandosmither + avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=a76a037b5d674938a75d2cff862fb6dfd63ec214&v=4 + url: https://github.com/fernandosmither - login: romabozhanovgithub avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 url: https://github.com/romabozhanovgithub - login: mbukeRepo avatarUrl: https://avatars.githubusercontent.com/u/70356088?u=d2eb23e2b222a3b316c4183b05a3236b32819dc2&v=4 url: https://github.com/mbukeRepo + - login: PelicanQ + avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 + url: https://github.com/PelicanQ - - login: ssbarnea avatarUrl: https://avatars.githubusercontent.com/u/102495?u=b4bf6818deefe59952ac22fec6ed8c76de1b8f7c&v=4 url: https://github.com/ssbarnea @@ -491,18 +491,15 @@ sponsors: - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu - - login: samnimoh - avatarUrl: https://avatars.githubusercontent.com/u/33413170?u=147bc516be6cb647b28d7e3b3fea3a018a331145&v=4 - url: https://github.com/samnimoh + - login: msniezynski + avatarUrl: https://avatars.githubusercontent.com/u/27588547?u=0e3be5ac57dcfdf124f470bcdf74b5bf79af1b6c&v=4 + url: https://github.com/msniezynski - login: danburonline avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=2cad4388c1544e539ecb732d656e42fb07b4ff2d&v=4 url: https://github.com/danburonline - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd - - 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 + - login: IvanReyesO7 + avatarUrl: https://avatars.githubusercontent.com/u/74359151?u=4b2c368f71e1411b462a8c2290c920ad35dc1af8&v=4 + url: https://github.com/IvanReyesO7 diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index db06cbdafcc6e..2e84f11285cbc 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,12 +1,12 @@ maintainers: - login: tiangolo - answers: 1868 - prs: 496 + answers: 1870 + prs: 508 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 501 + count: 512 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu @@ -26,21 +26,21 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 url: https://github.com/JarroVGIT - login: jgould22 - count: 168 + count: 186 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: euri10 count: 153 avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 url: https://github.com/euri10 +- login: iudeen + count: 126 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen - login: phy25 count: 126 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 -- login: iudeen - count: 122 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen - login: raphaelauv count: 83 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 @@ -61,14 +61,14 @@ experts: count: 49 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen +- login: yinziyan1206 + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 - login: acidjunk count: 45 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk -- login: insomnes - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 - url: https://github.com/insomnes - login: Dustyposa count: 45 avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 @@ -77,18 +77,18 @@ experts: 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 - url: https://github.com/odiseo0 +- login: insomnes + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 + url: https://github.com/insomnes - login: frankie567 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 url: https://github.com/frankie567 +- login: odiseo0 + count: 43 + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 + url: https://github.com/odiseo0 - login: includeamin count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 @@ -101,14 +101,14 @@ experts: count: 37 avatarUrl: https://avatars.githubusercontent.com/u/5167622?u=de8f597c81d6336fcebc37b32dfd61a3f877160c&v=4 url: https://github.com/STeveShary +- login: n8sty + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - 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 @@ -137,18 +137,22 @@ experts: count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf -- login: JavierSanchezCastro +- login: chris-allnutt count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro + avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 + url: https://github.com/chris-allnutt +- login: ebottos94 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 - login: nsidnev count: 20 avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 url: https://github.com/nsidnev -- login: chris-allnutt +- login: JavierSanchezCastro count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 - url: https://github.com/chris-allnutt + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: chrisK824 count: 19 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 @@ -161,10 +165,10 @@ experts: count: 18 avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 url: https://github.com/retnikt -- login: ebottos94 +- login: nymous count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous - login: Hultner count: 17 avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4 @@ -181,39 +185,47 @@ experts: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 url: https://github.com/caeser1996 -- login: nymous +- login: dstlny count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous + avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 + url: https://github.com/dstlny - login: jonatasoli count: 16 avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 url: https://github.com/jonatasoli -- login: dstlny - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 - url: https://github.com/dstlny - login: abhint count: 15 avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 url: https://github.com/abhint last_month_active: +- login: jgould22 + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: Kludex - count: 8 + count: 10 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex +- login: White-Mask + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 + url: https://github.com/White-Mask - login: n8sty - count: 7 + count: 4 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty -- login: chrisK824 +- login: hasansezertasan count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: danielfcollier + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=e389634d494d503cca867f76c2d00cacc273a46e&v=4 + url: https://github.com/hasansezertasan +- login: pythonweb2 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/38995330?u=5799be795fc310f75f3a5fe9242307d59b194520&v=4 - url: https://github.com/danielfcollier + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: ebottos94 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 top_contributors: - login: waynerv count: 25 @@ -349,17 +361,17 @@ top_contributors: url: https://github.com/rostik1410 top_reviewers: - login: Kludex - count: 139 + count: 145 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex +- login: BilalAlpaslan + count: 82 + avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 + url: https://github.com/BilalAlpaslan - 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: iudeen count: 54 avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 @@ -376,14 +388,14 @@ top_reviewers: count: 47 avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4 url: https://github.com/Laineyzhang55 +- login: Xewus + count: 47 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus - login: ycd 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 @@ -412,14 +424,14 @@ top_reviewers: count: 26 avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 url: https://github.com/lsglucas +- login: Ryandaydev + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=ba0eea19429e7cf77cf2ab8ad2f3d3af202bc1cf&v=4 + url: https://github.com/Ryandaydev - login: LorhanSohaky count: 24 avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 url: https://github.com/LorhanSohaky -- login: Ryandaydev - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=809f3d1074d04bbc28012a7f17f06ea56f5bd71a&v=4 - url: https://github.com/Ryandaydev - login: dmontagu count: 23 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 @@ -476,14 +488,14 @@ top_reviewers: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 url: https://github.com/delhi09 +- login: peidrao + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 + url: https://github.com/peidrao - login: sh0nk count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 url: https://github.com/sh0nk -- login: peidrao - 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 From e7756ae7dcffa0b73767d354ca158fd6b7bc87ed Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 20 Dec 2023 17:06:01 +0000 Subject: [PATCH 002/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 835df984ce4c1..b8b6f9ae947ee 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +* 👥 Update FastAPI People. PR [#10567](https://github.com/tiangolo/fastapi/pull/10567) by [@tiangolo](https://github.com/tiangolo). + ## 0.105.0 ### Features From a4aa79e0b4cacc6b428d415d04d234a8c77af9d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 25 Dec 2023 18:57:35 +0100 Subject: [PATCH 003/217] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20raisi?= =?UTF-8?q?ng=20exceptions=20(including=20`HTTPException`)=20in=20dependen?= =?UTF-8?q?cies=20with=20`yield`=20in=20the=20exit=20code,=20do=20not=20su?= =?UTF-8?q?pport=20them=20in=20background=20tasks=20(#10831)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ♻ Refactor dependency AsyncExitStack logic, exit dependencies after creating the response, before sending it * ✅ Update tests for dependencies exit, check they are finished before the response is sent * 🔥 Remove ExitAsyncStackMiddleware as it's no longer needed * 📝 Update docs for dependencies with yield * 📝 Update release notes * 📝 Add source examples for new dependencies with yield raising * ✅ Add tests for new dependencies raising after yield * 📝 Update release notes --- docs/en/docs/release-notes.md | 102 ++++++++ .../dependencies/dependencies-with-yield.md | 95 ++++--- docs_src/dependencies/tutorial008b.py | 30 +++ docs_src/dependencies/tutorial008b_an.py | 31 +++ docs_src/dependencies/tutorial008b_an_py39.py | 32 +++ fastapi/applications.py | 52 ---- fastapi/concurrency.py | 1 - fastapi/dependencies/utils.py | 9 +- fastapi/middleware/asyncexitstack.py | 25 -- fastapi/routing.py | 231 ++++++++++-------- pyproject.toml | 9 + tests/test_dependency_contextmanager.py | 20 +- .../test_dependencies/test_tutorial008b.py | 23 ++ .../test_dependencies/test_tutorial008b_an.py | 23 ++ .../test_tutorial008b_an_py39.py | 23 ++ 15 files changed, 492 insertions(+), 214 deletions(-) create mode 100644 docs_src/dependencies/tutorial008b.py create mode 100644 docs_src/dependencies/tutorial008b_an.py create mode 100644 docs_src/dependencies/tutorial008b_an_py39.py delete mode 100644 fastapi/middleware/asyncexitstack.py create mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008b.py create mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008b_an.py create mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b8b6f9ae947ee..12bc12d260e32 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,108 @@ hide: ## Latest Changes +### Dependencies with `yield`, `HTTPException` and Background Tasks + +Dependencies with `yield` now can raise `HTTPException` and other exceptions after `yield`. 🎉 + +Read the new docs here: [Dependencies with `yield` and `HTTPException`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception). + +```Python +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Onwer error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item +``` + +--- + +Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} would have already run. + +This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished. + +Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0. + +Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection). + +If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`. + +For example, instead of using the same database session, you would create a new database session inside of the background task, and you would obtain the objects from the database using this new session. And then instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object and then obtain the object again inside the background task function. + +The sequence of execution before FastAPI 0.106.0 was like this diagram: + +Time flows from top to bottom. And each column is one of the parts interacting or executing code. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise HTTPException + dep -->> handler: Auto forward exception + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + dep -->> handler: Auto forward exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +The new execution flow can be found in the docs: [Execution of dependencies with `yield`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#execution-of-dependencies-with-yield). + +### Internal + * 👥 Update FastAPI People. PR [#10567](https://github.com/tiangolo/fastapi/pull/10567) by [@tiangolo](https://github.com/tiangolo). ## 0.105.0 diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index fe18f1f1d9afe..4ead4682cba9a 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -1,8 +1,8 @@ # Dependencies with yield -FastAPI supports dependencies that do some extra steps after finishing. +FastAPI supports dependencies that do some extra steps after finishing. -To do this, use `yield` instead of `return`, and write the extra steps after. +To do this, use `yield` instead of `return`, and write the extra steps (code) after. !!! tip Make sure to use `yield` one single time. @@ -21,7 +21,7 @@ To do this, use `yield` instead of `return`, and write the extra steps after. For example, you could use this to create a database session and close it after finishing. -Only the code prior to and including the `yield` statement is executed before sending a response: +Only the code prior to and including the `yield` statement is executed before creating a response: ```Python hl_lines="2-4" {!../../../docs_src/dependencies/tutorial007.py!} @@ -40,7 +40,7 @@ The code following the `yield` statement is executed after the response has been ``` !!! tip - You can use `async` or normal functions. + You can use `async` or regular functions. **FastAPI** will do the right thing with each, the same as with normal dependencies. @@ -114,7 +114,7 @@ And, in turn, `dependency_b` needs the value from `dependency_a` (here named `de {!> ../../../docs_src/dependencies/tutorial008.py!} ``` -The same way, you could have dependencies with `yield` and `return` mixed. +The same way, you could have some dependencies with `yield` and some other dependencies with `return`, and have some of those depend on some of the others. And you could have a single dependency that requires several other dependencies with `yield`, etc. @@ -131,24 +131,38 @@ You can have any combinations of dependencies that you want. You saw that you can use dependencies with `yield` and have `try` blocks that catch exceptions. -It might be tempting to raise an `HTTPException` or similar in the exit code, after the `yield`. But **it won't work**. +The same way, you could raise an `HTTPException` or similar in the exit code, after the `yield`. -The exit code in dependencies with `yield` is executed *after* the response is sent, so [Exception Handlers](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} will have already run. There's nothing catching exceptions thrown by your dependencies in the exit code (after the `yield`). +!!! tip -So, if you raise an `HTTPException` after the `yield`, the default (or any custom) exception handler that catches `HTTPException`s and returns an HTTP 400 response won't be there to catch that exception anymore. + This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*. -This is what allows anything set in the dependency (e.g. a DB session) to, for example, be used by background tasks. + But it's there for you if you need it. 🀓 -Background tasks are run *after* the response has been sent. So there's no way to raise an `HTTPException` because there's not even a way to change the response that is *already sent*. +=== "Python 3.9+" -But if a background task creates a DB error, at least you can rollback or cleanly close the session in the dependency with `yield`, and maybe log the error or report it to a remote tracking system. + ```Python hl_lines="18-22 31" + {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} + ``` -If you have some code that you know could raise an exception, do the most normal/"Pythonic" thing and add a `try` block in that section of the code. +=== "Python 3.8+" -If you have custom exceptions that you would like to handle *before* returning the response and possibly modifying the response, maybe even raising an `HTTPException`, create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + ```Python hl_lines="17-21 30" + {!> ../../../docs_src/dependencies/tutorial008b_an.py!} + ``` -!!! tip - You can still raise exceptions including `HTTPException` *before* the `yield`. But not after. +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="16-20 29" + {!> ../../../docs_src/dependencies/tutorial008b.py!} + ``` + +An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is ot create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +## Execution of dependencies with `yield` The sequence of execution is more or less like this diagram. Time flows from top to bottom. And each column is one of the parts interacting or executing code. @@ -161,34 +175,30 @@ participant dep as Dep with yield participant operation as Path Operation participant tasks as Background tasks - Note over client,tasks: Can raise exception for dependency, handled after response is sent - Note over client,operation: Can raise HTTPException and can change the response + Note over client,operation: Can raise exceptions, including HTTPException client ->> dep: Start request Note over dep: Run code up to yield - opt raise - dep -->> handler: Raise HTTPException + opt raise Exception + dep -->> handler: Raise Exception handler -->> client: HTTP error response - dep -->> dep: Raise other exception end dep ->> operation: Run dependency, e.g. DB session opt raise - operation -->> dep: Raise HTTPException - dep -->> handler: Auto forward exception + operation -->> dep: Raise Exception (e.g. HTTPException) + opt handle + dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception + dep -->> handler: Auto forward exception + end handler -->> client: HTTP error response - operation -->> dep: Raise other exception - dep -->> handler: Auto forward exception end + operation ->> client: Return response to client Note over client,operation: Response is already sent, can't change it anymore opt Tasks operation -->> tasks: Send background tasks end opt Raise other exception - tasks -->> dep: Raise other exception - end - Note over dep: After yield - opt Handle other exception - dep -->> dep: Handle exception, can't change response. E.g. close DB session. + tasks -->> tasks: Handle exceptions in the background task code end ``` @@ -198,10 +208,33 @@ participant tasks as Background tasks After one of those responses is sent, no other response can be sent. !!! tip - This diagram shows `HTTPException`, but you could also raise any other exception for which you create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + This diagram shows `HTTPException`, but you could also raise any other exception that you catch in a dependency with `yield` or with a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`, and then **again** to the exception handlers. If there's no exception handler for that exception, it will then be handled by the default internal `ServerErrorMiddleware`, returning a 500 HTTP status code, to let the client know that there was an error in the server. +## Dependencies with `yield`, `HTTPException` and Background Tasks + +!!! warning + You most probably don't need these technical details, you can skip this section and continue below. + + These details are useful mainly if you were using a version of FastAPI prior to 0.106.0 and used resources from dependencies with `yield` in background tasks. + +Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} would have already run. + +This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished. + +Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0. + +!!! tip + + Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection). + + So, this way you will probably have cleaner code. + +If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`. + +For example, instead of using the same database session, you would create a new database session inside of the background task, and you would obtain the objects from the database using this new session. And then instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object and then obtain the object again inside the background task function. + ## Context Managers ### What are "Context Managers" @@ -220,7 +253,7 @@ Underneath, the `open("./somefile.txt")` creates an object that is a called a "C When the `with` block finishes, it makes sure to close the file, even if there were exceptions. -When you create a dependency with `yield`, **FastAPI** will internally convert it to a context manager, and combine it with some other related tools. +When you create a dependency with `yield`, **FastAPI** will internally create a context manager for it, and combine it with some other related tools. ### Using context managers in dependencies with `yield` diff --git a/docs_src/dependencies/tutorial008b.py b/docs_src/dependencies/tutorial008b.py new file mode 100644 index 0000000000000..4a1a70dcfcda9 --- /dev/null +++ b/docs_src/dependencies/tutorial008b.py @@ -0,0 +1,30 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Onwer error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/docs_src/dependencies/tutorial008b_an.py b/docs_src/dependencies/tutorial008b_an.py new file mode 100644 index 0000000000000..3a0f1399a98f4 --- /dev/null +++ b/docs_src/dependencies/tutorial008b_an.py @@ -0,0 +1,31 @@ +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Onwer error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/docs_src/dependencies/tutorial008b_an_py39.py b/docs_src/dependencies/tutorial008b_an_py39.py new file mode 100644 index 0000000000000..30c9cdc699c2e --- /dev/null +++ b/docs_src/dependencies/tutorial008b_an_py39.py @@ -0,0 +1,32 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Onwer error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/fastapi/applications.py b/fastapi/applications.py index 3021d75937d1c..597c60a56788f 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -22,7 +22,6 @@ ) from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger -from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, @@ -37,8 +36,6 @@ from starlette.exceptions import HTTPException from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware -from starlette.middleware.errors import ServerErrorMiddleware -from starlette.middleware.exceptions import ExceptionMiddleware from starlette.requests import Request from starlette.responses import HTMLResponse, JSONResponse, Response from starlette.routing import BaseRoute @@ -966,55 +963,6 @@ class Item(BaseModel): self.middleware_stack: Union[ASGIApp, None] = None self.setup() - def build_middleware_stack(self) -> ASGIApp: - # Duplicate/override from Starlette to add AsyncExitStackMiddleware - # inside of ExceptionMiddleware, inside of custom user middlewares - debug = self.debug - error_handler = None - exception_handlers = {} - - for key, value in self.exception_handlers.items(): - if key in (500, Exception): - error_handler = value - else: - exception_handlers[key] = value - - middleware = ( - [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)] - + self.user_middleware - + [ - Middleware( - ExceptionMiddleware, handlers=exception_handlers, debug=debug - ), - # Add FastAPI-specific AsyncExitStackMiddleware for dependencies with - # contextvars. - # This needs to happen after user middlewares because those create a - # new contextvars context copy by using a new AnyIO task group. - # The initial part of dependencies with 'yield' is executed in the - # FastAPI code, inside all the middlewares. However, the teardown part - # (after 'yield') is executed in the AsyncExitStack in this middleware. - # If the AsyncExitStack lived outside of the custom middlewares and - # contextvars were set in a dependency with 'yield' in that internal - # contextvars context, the values would not be available in the - # outer context of the AsyncExitStack. - # By placing the middleware and the AsyncExitStack here, inside all - # user middlewares, the code before and after 'yield' in dependencies - # with 'yield' is executed in the same contextvars context. Thus, all values - # set in contextvars before 'yield' are still available after 'yield,' as - # expected. - # Additionally, by having this AsyncExitStack here, after the - # ExceptionMiddleware, dependencies can now catch handled exceptions, - # e.g. HTTPException, to customize the teardown code (e.g. DB session - # rollback). - Middleware(AsyncExitStackMiddleware), - ] - ) - - app = self.router - for cls, options in reversed(middleware): - app = cls(app=app, **options) - return app - def openapi(self) -> Dict[str, Any]: """ Generate the OpenAPI schema of the application. This is called by FastAPI diff --git a/fastapi/concurrency.py b/fastapi/concurrency.py index 754061c862dad..894bd3ed11873 100644 --- a/fastapi/concurrency.py +++ b/fastapi/concurrency.py @@ -1,4 +1,3 @@ -from contextlib import AsyncExitStack as AsyncExitStack # noqa from contextlib import asynccontextmanager as asynccontextmanager from typing import AsyncGenerator, ContextManager, TypeVar diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 4e88410a5ec1f..b73473484159c 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -1,5 +1,5 @@ import inspect -from contextlib import contextmanager +from contextlib import AsyncExitStack, contextmanager from copy import deepcopy from typing import ( Any, @@ -46,7 +46,6 @@ ) from fastapi.background import BackgroundTasks from fastapi.concurrency import ( - AsyncExitStack, asynccontextmanager, contextmanager_in_threadpool, ) @@ -529,6 +528,7 @@ async def solve_dependencies( response: Optional[Response] = None, dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, + async_exit_stack: AsyncExitStack, ) -> Tuple[ Dict[str, Any], List[Any], @@ -575,6 +575,7 @@ async def solve_dependencies( response=response, dependency_overrides_provider=dependency_overrides_provider, dependency_cache=dependency_cache, + async_exit_stack=async_exit_stack, ) ( sub_values, @@ -590,10 +591,8 @@ async def solve_dependencies( if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): - stack = request.scope.get("fastapi_astack") - assert isinstance(stack, AsyncExitStack) solved = await solve_generator( - call=call, stack=stack, sub_values=sub_values + call=call, stack=async_exit_stack, sub_values=sub_values ) elif is_coroutine_callable(call): solved = await call(**sub_values) diff --git a/fastapi/middleware/asyncexitstack.py b/fastapi/middleware/asyncexitstack.py deleted file mode 100644 index 30a0ae626c26c..0000000000000 --- a/fastapi/middleware/asyncexitstack.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Optional - -from fastapi.concurrency import AsyncExitStack -from starlette.types import ASGIApp, Receive, Scope, Send - - -class AsyncExitStackMiddleware: - def __init__(self, app: ASGIApp, context_name: str = "fastapi_astack") -> None: - self.app = app - self.context_name = context_name - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - dependency_exception: Optional[Exception] = None - async with AsyncExitStack() as stack: - scope[self.context_name] = stack - try: - await self.app(scope, receive, send) - except Exception as e: - dependency_exception = e - raise e - if dependency_exception: - # This exception was possibly handled by the dependency but it should - # still bubble up so that the ServerErrorMiddleware can return a 500 - # or the ExceptionMiddleware can catch and handle any other exceptions - raise dependency_exception diff --git a/fastapi/routing.py b/fastapi/routing.py index 54d53bbbfb812..589ecca2aaf73 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -216,95 +216,124 @@ def get_request_handler( actual_response_class = response_class async def app(request: Request) -> Response: - try: - body: Any = None - if body_field: - if is_body_form: - body = await request.form() - stack = request.scope.get("fastapi_astack") - assert isinstance(stack, AsyncExitStack) - stack.push_async_callback(body.close) + exception_to_reraise: Optional[Exception] = None + response: Union[Response, None] = None + async with AsyncExitStack() as async_exit_stack: + # TODO: remove this scope later, after a few releases + # This scope fastapi_astack is no longer used by FastAPI, kept for + # compatibility, just in case + request.scope["fastapi_astack"] = async_exit_stack + try: + body: Any = None + if body_field: + if is_body_form: + body = await request.form() + async_exit_stack.push_async_callback(body.close) + else: + body_bytes = await request.body() + if body_bytes: + json_body: Any = Undefined + content_type_value = request.headers.get("content-type") + if not content_type_value: + json_body = await request.json() + else: + message = email.message.Message() + message["content-type"] = content_type_value + if message.get_content_maintype() == "application": + subtype = message.get_content_subtype() + if subtype == "json" or subtype.endswith("+json"): + json_body = await request.json() + if json_body != Undefined: + body = json_body + else: + body = body_bytes + except json.JSONDecodeError as e: + validation_error = RequestValidationError( + [ + { + "type": "json_invalid", + "loc": ("body", e.pos), + "msg": "JSON decode error", + "input": {}, + "ctx": {"error": e.msg}, + } + ], + body=e.doc, + ) + exception_to_reraise = validation_error + raise validation_error from e + except HTTPException as e: + exception_to_reraise = e + raise + except Exception as e: + http_error = HTTPException( + status_code=400, detail="There was an error parsing the body" + ) + exception_to_reraise = http_error + raise http_error from e + try: + solved_result = await solve_dependencies( + request=request, + dependant=dependant, + body=body, + dependency_overrides_provider=dependency_overrides_provider, + async_exit_stack=async_exit_stack, + ) + values, errors, background_tasks, sub_response, _ = solved_result + except Exception as e: + exception_to_reraise = e + raise e + if errors: + validation_error = RequestValidationError( + _normalize_errors(errors), body=body + ) + exception_to_reraise = validation_error + raise validation_error + else: + try: + raw_response = await run_endpoint_function( + dependant=dependant, values=values, is_coroutine=is_coroutine + ) + except Exception as e: + exception_to_reraise = e + raise e + if isinstance(raw_response, Response): + if raw_response.background is None: + raw_response.background = background_tasks + response = raw_response else: - body_bytes = await request.body() - if body_bytes: - json_body: Any = Undefined - content_type_value = request.headers.get("content-type") - if not content_type_value: - json_body = await request.json() - else: - message = email.message.Message() - message["content-type"] = content_type_value - if message.get_content_maintype() == "application": - subtype = message.get_content_subtype() - if subtype == "json" or subtype.endswith("+json"): - json_body = await request.json() - if json_body != Undefined: - body = json_body - else: - body = body_bytes - except json.JSONDecodeError as e: - raise RequestValidationError( - [ - { - "type": "json_invalid", - "loc": ("body", e.pos), - "msg": "JSON decode error", - "input": {}, - "ctx": {"error": e.msg}, - } - ], - body=e.doc, - ) from e - except HTTPException: - raise - except Exception as e: - raise HTTPException( - status_code=400, detail="There was an error parsing the body" - ) from e - solved_result = await solve_dependencies( - request=request, - dependant=dependant, - body=body, - dependency_overrides_provider=dependency_overrides_provider, - ) - values, errors, background_tasks, sub_response, _ = solved_result - if errors: - raise RequestValidationError(_normalize_errors(errors), body=body) - else: - raw_response = await run_endpoint_function( - dependant=dependant, values=values, is_coroutine=is_coroutine - ) - - if isinstance(raw_response, Response): - if raw_response.background is None: - raw_response.background = background_tasks - return raw_response - response_args: Dict[str, Any] = {"background": background_tasks} - # If status_code was set, use it, otherwise use the default from the - # response class, in the case of redirect it's 307 - current_status_code = ( - status_code if status_code else sub_response.status_code - ) - if current_status_code is not None: - response_args["status_code"] = current_status_code - if sub_response.status_code: - response_args["status_code"] = sub_response.status_code - content = await serialize_response( - field=response_field, - response_content=raw_response, - include=response_model_include, - exclude=response_model_exclude, - by_alias=response_model_by_alias, - exclude_unset=response_model_exclude_unset, - exclude_defaults=response_model_exclude_defaults, - exclude_none=response_model_exclude_none, - is_coroutine=is_coroutine, - ) - response = actual_response_class(content, **response_args) - if not is_body_allowed_for_status_code(response.status_code): - response.body = b"" - response.headers.raw.extend(sub_response.headers.raw) - return response + response_args: Dict[str, Any] = {"background": background_tasks} + # If status_code was set, use it, otherwise use the default from the + # response class, in the case of redirect it's 307 + current_status_code = ( + status_code if status_code else sub_response.status_code + ) + if current_status_code is not None: + response_args["status_code"] = current_status_code + if sub_response.status_code: + response_args["status_code"] = sub_response.status_code + content = await serialize_response( + field=response_field, + response_content=raw_response, + include=response_model_include, + exclude=response_model_exclude, + by_alias=response_model_by_alias, + exclude_unset=response_model_exclude_unset, + exclude_defaults=response_model_exclude_defaults, + exclude_none=response_model_exclude_none, + is_coroutine=is_coroutine, + ) + response = actual_response_class(content, **response_args) + if not is_body_allowed_for_status_code(response.status_code): + response.body = b"" + response.headers.raw.extend(sub_response.headers.raw) + # This exception was possibly handled by the dependency but it should + # still bubble up so that the ServerErrorMiddleware can return a 500 + # or the ExceptionMiddleware can catch and handle any other exceptions + if exception_to_reraise: + raise exception_to_reraise + assert response is not None, "An error occurred while generating the request" + return response return app @@ -313,16 +342,22 @@ def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: - solved_result = await solve_dependencies( - request=websocket, - dependant=dependant, - dependency_overrides_provider=dependency_overrides_provider, - ) - values, errors, _, _2, _3 = solved_result - if errors: - raise WebSocketRequestValidationError(_normalize_errors(errors)) - assert dependant.call is not None, "dependant.call must be a function" - await dependant.call(**values) + async with AsyncExitStack() as async_exit_stack: + # TODO: remove this scope later, after a few releases + # This scope fastapi_astack is no longer used by FastAPI, kept for + # compatibility, just in case + websocket.scope["fastapi_astack"] = async_exit_stack + solved_result = await solve_dependencies( + request=websocket, + dependant=dependant, + dependency_overrides_provider=dependency_overrides_provider, + async_exit_stack=async_exit_stack, + ) + values, errors, _, _2, _3 = solved_result + if errors: + raise WebSocketRequestValidationError(_normalize_errors(errors)) + assert dependant.call is not None, "dependant.call must be a function" + await dependant.call(**values) return app diff --git a/pyproject.toml b/pyproject.toml index e67486ae31bf8..fa072e59523da 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -84,6 +84,12 @@ module = "fastapi.tests.*" ignore_missing_imports = true check_untyped_defs = true +[[tool.mypy.overrides]] +module = "docs_src.*" +disallow_incomplete_defs = false +disallow_untyped_defs = false +disallow_untyped_calls = false + [tool.pytest.ini_options] addopts = [ "--strict-config", @@ -167,6 +173,9 @@ ignore = [ "docs_src/security/tutorial005_an_py39.py" = ["B904"] "docs_src/security/tutorial005_py310.py" = ["B904"] "docs_src/security/tutorial005_py39.py" = ["B904"] +"docs_src/dependencies/tutorial008b.py" = ["B904"] +"docs_src/dependencies/tutorial008b_an.py" = ["B904"] +"docs_src/dependencies/tutorial008b_an_py39.py" = ["B904"] [tool.ruff.isort] diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py index 03ef56c4d7e5b..b07f9aa5b6c6b 100644 --- a/tests/test_dependency_contextmanager.py +++ b/tests/test_dependency_contextmanager.py @@ -1,7 +1,9 @@ +import json from typing import Dict import pytest from fastapi import BackgroundTasks, Depends, FastAPI +from fastapi.responses import StreamingResponse from fastapi.testclient import TestClient app = FastAPI() @@ -200,6 +202,13 @@ async def bg(state: dict): return state +@app.middleware("http") +async def middleware(request, call_next): + response: StreamingResponse = await call_next(request) + response.headers["x-state"] = json.dumps(state.copy()) + return response + + client = TestClient(app) @@ -274,9 +283,13 @@ def test_background_tasks(): assert data["context_b"] == "started b" assert data["context_a"] == "started a" assert data["bg"] == "not set" + middleware_state = json.loads(response.headers["x-state"]) + assert middleware_state["context_b"] == "finished b with a: started a" + assert middleware_state["context_a"] == "finished a" + assert middleware_state["bg"] == "not set" assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" - assert state["bg"] == "bg set - b: started b - a: started a" + assert state["bg"] == "bg set - b: finished b with a: started a - a: finished a" def test_sync_raise_raises(): @@ -382,4 +395,7 @@ def test_sync_background_tasks(): assert data["sync_bg"] == "not set" assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" - assert state["sync_bg"] == "sync_bg set - b: started b - a: started a" + assert ( + state["sync_bg"] + == "sync_bg set - b: finished b with a: started a - a: finished a" + ) diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b.py b/tests/test_tutorial/test_dependencies/test_tutorial008b.py new file mode 100644 index 0000000000000..ed4f4aaca8cd3 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b.py @@ -0,0 +1,23 @@ +from fastapi.testclient import TestClient + +from docs_src.dependencies.tutorial008b import app + +client = TestClient(app) + + +def test_get_no_item(): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found"} + + +def test_owner_error(): + response = client.get("/items/plumbus") + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Onwer error: Rick"} + + +def test_get_item(): + response = client.get("/items/portal-gun") + assert response.status_code == 200, response.text + assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py new file mode 100644 index 0000000000000..aa76ad6afc940 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py @@ -0,0 +1,23 @@ +from fastapi.testclient import TestClient + +from docs_src.dependencies.tutorial008b_an import app + +client = TestClient(app) + + +def test_get_no_item(): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found"} + + +def test_owner_error(): + response = client.get("/items/plumbus") + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Onwer error: Rick"} + + +def test_get_item(): + response = client.get("/items/portal-gun") + assert response.status_code == 200, response.text + assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py new file mode 100644 index 0000000000000..aa76ad6afc940 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py @@ -0,0 +1,23 @@ +from fastapi.testclient import TestClient + +from docs_src.dependencies.tutorial008b_an import app + +client = TestClient(app) + + +def test_get_no_item(): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found"} + + +def test_owner_error(): + response = client.get("/items/plumbus") + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Onwer error: Rick"} + + +def test_get_item(): + response = client.get("/items/portal-gun") + assert response.status_code == 200, response.text + assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} From 678bed2fc9cbf38ba7a6ba9782e5be1a33d852c5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 25 Dec 2023 17:57:54 +0000 Subject: [PATCH 004/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 12bc12d260e32..bc6fd9d110142 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -107,6 +107,10 @@ participant tasks as Background tasks The new execution flow can be found in the docs: [Execution of dependencies with `yield`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#execution-of-dependencies-with-yield). +### Features + +* ✹ Add support for raising exceptions (including `HTTPException`) in dependencies with `yield` in the exit code, do not support them in background tasks. PR [#10831](https://github.com/tiangolo/fastapi/pull/10831) by [@tiangolo](https://github.com/tiangolo). + ### Internal * 👥 Update FastAPI People. PR [#10567](https://github.com/tiangolo/fastapi/pull/10567) by [@tiangolo](https://github.com/tiangolo). From bcd5a424cdca5973a2f4927de83c8eb2ca658011 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 25 Dec 2023 19:00:47 +0100 Subject: [PATCH 005/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bc6fd9d110142..a2424a383224f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,12 @@ hide: ## Latest Changes +### Breaking Changes + +Using resources from dependencies with `yield` in background tasks is no longer supported. + +This change is what supports the new features, read below. 🀓 + ### Dependencies with `yield`, `HTTPException` and Background Tasks Dependencies with `yield` now can raise `HTTPException` and other exceptions after `yield`. 🎉 From 91510db62012b817627833e896ddb579056c5922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 25 Dec 2023 19:01:26 +0100 Subject: [PATCH 006/217] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.10?= =?UTF-8?q?6.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a2424a383224f..fc38cb475f052 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.106.0 + ### Breaking Changes Using resources from dependencies with `yield` in background tasks is no longer supported. diff --git a/fastapi/__init__.py b/fastapi/__init__.py index dd16ea34db1eb..4348bd98e4dad 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.105.0" +__version__ = "0.106.0" from starlette import status as status From 5826c4f31f8b6e0d8a289d4c5a6c5a7f8ccb263a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 25 Dec 2023 19:06:04 +0100 Subject: [PATCH 007/217] =?UTF-8?q?=F0=9F=93=9D=20Tweak=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index fc38cb475f052..0c118e7c9edc0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -57,7 +57,7 @@ def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): --- -Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} would have already run. +Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers) would have already run. This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished. From 8b5843ebcd1ccc9582ef34b9dba0a9162140396b Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Tue, 26 Dec 2023 12:13:50 -0500 Subject: [PATCH 008/217] =?UTF-8?q?=F0=9F=93=9D=20Restructure=20Docs=20sec?= =?UTF-8?q?tion=20in=20Contributing=20page=20(#10844)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 📝 Restructure Docs section in Contributing page --- docs/en/docs/contributing.md | 58 ++++++++++++++++++++---------------- 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index cfdb607d772e0..35bc1c50197d4 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -150,32 +150,7 @@ For it to sort them correctly, you need to have FastAPI installed locally in you First, make sure you set up your environment as described above, that will install all the requirements. -The documentation uses MkDocs. - -And there are extra tools/scripts in place to handle translations in `./scripts/docs.py`. - -!!! tip - You don't need to see the code in `./scripts/docs.py`, you just use it in the command line. - -All the documentation is in Markdown format in the directory `./docs/en/`. - -Many of the tutorials have blocks of code. - -In most of the cases, these blocks of code are actual complete applications that can be run as is. - -In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs_src/` directory. - -And those Python files are included/injected in the documentation when generating the site. - -### Docs for tests - -Most of the tests actually run against the example source files in the documentation. - -This helps making sure that: - -* The documentation is up to date. -* The documentation examples can be run as is. -* Most of the features are covered by the documentation, ensured by test coverage. +### Docs live During local development, there is a script that builds the site and checks for any changes, live-reloading: @@ -229,6 +204,37 @@ Completion will take effect once you restart the terminal. +### Docs Structure + +The documentation uses MkDocs. + +And there are extra tools/scripts in place to handle translations in `./scripts/docs.py`. + +!!! tip + You don't need to see the code in `./scripts/docs.py`, you just use it in the command line. + +All the documentation is in Markdown format in the directory `./docs/en/`. + +Many of the tutorials have blocks of code. + +In most of the cases, these blocks of code are actual complete applications that can be run as is. + +In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs_src/` directory. + +And those Python files are included/injected in the documentation when generating the site. + +### Docs for tests + +Most of the tests actually run against the example source files in the documentation. + +This helps making sure that: + +* The documentation is up to date. +* The documentation examples can be run as is. +* Most of the features are covered by the documentation, ensured by test coverage. + + + ### Apps and docs at the same time If you run the examples with, e.g.: From 4de60e153a73ee51e6be3378b64fc16bbd251d8a Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 26 Dec 2023 17:14:13 +0000 Subject: [PATCH 009/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0c118e7c9edc0..b5fbdfa4581fd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Restructure Docs section in Contributing page. PR [#10844](https://github.com/tiangolo/fastapi/pull/10844) by [@alejsdev](https://github.com/alejsdev). + ## 0.106.0 ### Breaking Changes From 505ae06c0bb2ba745587731ca88e4165b64003a6 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Tue, 26 Dec 2023 12:23:20 -0500 Subject: [PATCH 010/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20docs:=20Node.js=20?= =?UTF-8?q?script=20alternative=20to=20update=20OpenAPI=20for=20generated?= =?UTF-8?q?=20clients=20(#10845)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/generate-clients.md | 14 ++++++++--- docs_src/generate_clients/tutorial004.js | 29 +++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 docs_src/generate_clients/tutorial004.js diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index e8d771f7123f4..3a810baee1957 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -229,9 +229,17 @@ But for the generated client we could **modify** the OpenAPI operation IDs right We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this: -```Python -{!../../../docs_src/generate_clients/tutorial004.py!} -``` +=== "Python" + + ```Python + {!> ../../../docs_src/generate_clients/tutorial004.py!} + ``` + +=== "Node.js" + + ```Python + {!> ../../../docs_src/generate_clients/tutorial004.js!} + ``` With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names. diff --git a/docs_src/generate_clients/tutorial004.js b/docs_src/generate_clients/tutorial004.js new file mode 100644 index 0000000000000..18dc38267bcde --- /dev/null +++ b/docs_src/generate_clients/tutorial004.js @@ -0,0 +1,29 @@ +import * as fs from "fs"; + +const filePath = "./openapi.json"; + +fs.readFile(filePath, (err, data) => { + const openapiContent = JSON.parse(data); + if (err) throw err; + + const paths = openapiContent.paths; + + Object.keys(paths).forEach((pathKey) => { + const pathData = paths[pathKey]; + Object.keys(pathData).forEach((method) => { + const operation = pathData[method]; + if (operation.tags && operation.tags.length > 0) { + const tag = operation.tags[0]; + const operationId = operation.operationId; + const toRemove = `${tag}-`; + if (operationId.startsWith(toRemove)) { + const newOperationId = operationId.substring(toRemove.length); + operation.operationId = newOperationId; + } + } + }); + }); + fs.writeFile(filePath, JSON.stringify(openapiContent, null, 2), (err) => { + if (err) throw err; + }); +}); From a751032c0929cdc4a891666240f0dc4849cf58a9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 26 Dec 2023 17:23:45 +0000 Subject: [PATCH 011/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b5fbdfa4581fd..f683b18020868 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add docs: Node.js script alternative to update OpenAPI for generated clients. PR [#10845](https://github.com/tiangolo/fastapi/pull/10845) by [@alejsdev](https://github.com/alejsdev). * 📝 Restructure Docs section in Contributing page. PR [#10844](https://github.com/tiangolo/fastapi/pull/10844) by [@alejsdev](https://github.com/alejsdev). ## 0.106.0 From d633953f13d70706daa3bbc03f6b3ab66648e02f Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 26 Dec 2023 20:03:07 +0100 Subject: [PATCH 012/217] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20Starlett?= =?UTF-8?q?e=20to=200.28.0=20(#9636)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index fa072e59523da..499d0e5dc8c12 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,7 +40,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.27.0,<0.28.0", + "starlette>=0.28.0,<0.29.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", # TODO: remove this pin after upgrading Starlette 0.31.1 From 9090bf4084ac3bd9527a938a5dc814b139740a6b Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 26 Dec 2023 19:03:31 +0000 Subject: [PATCH 013/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f683b18020868..d165ba52fbbc7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Upgrades + +* ⬆ Upgrade Starlette to 0.28.0. PR [#9636](https://github.com/tiangolo/fastapi/pull/9636) by [@adriangb](https://github.com/adriangb). + ### Docs * 📝 Add docs: Node.js script alternative to update OpenAPI for generated clients. PR [#10845](https://github.com/tiangolo/fastapi/pull/10845) by [@alejsdev](https://github.com/alejsdev). From f933fd6ff8db06ff77be8406ad56b6b07f13a532 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 26 Dec 2023 20:04:08 +0100 Subject: [PATCH 014/217] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.10?= =?UTF-8?q?7.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d165ba52fbbc7..f7b6207c243fa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.107.0 + ### Upgrades * ⬆ Upgrade Starlette to 0.28.0. PR [#9636](https://github.com/tiangolo/fastapi/pull/9636) by [@adriangb](https://github.com/adriangb). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 4348bd98e4dad..8a22b74b6759c 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.106.0" +__version__ = "0.107.0" from starlette import status as status From c55f90df32101006ad3ddd8060d30f24c8f44eb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 26 Dec 2023 21:12:34 +0100 Subject: [PATCH 015/217] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20Starlett?= =?UTF-8?q?e=20to=20`>=3D0.29.0,<0.33.0`,=20update=20docs=20and=20usage=20?= =?UTF-8?q?of=20templates=20with=20new=20Starlette=20arguments=20(#10846)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 📝 Update docs for compatibility with Starlette 0.29.0 and new template arguments * ⬆ Upgrade Starlette to >=0.29.0,<0.33.0 * 📌 Remove AnyIO pin --- docs/em/docs/advanced/templates.md | 2 +- docs/en/docs/advanced/templates.md | 10 ++++++---- docs_src/templates/tutorial001.py | 4 +++- pyproject.toml | 4 +--- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index 1fb57725af175..0a73a4f47e811 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -27,7 +27,7 @@ $ pip install jinja2 * 📣 `Request` 🔢 *➡ 🛠* 👈 🔜 📚 📄. * ⚙ `templates` 👆 ✍ ✍ & 📚 `TemplateResponse`, 🚶‍♀ `request` 1⃣ 🔑-💲 👫 Jinja2⃣ "🔑". -```Python hl_lines="4 11 15-16" +```Python hl_lines="4 11 15-18" {!../../../docs_src/templates/tutorial001.py!} ``` diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 38618aeeb09cd..583abda7fb0e4 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -25,14 +25,16 @@ $ pip install jinja2 * Import `Jinja2Templates`. * Create a `templates` object that you can re-use later. * Declare a `Request` parameter in the *path operation* that will return a template. -* Use the `templates` you created to render and return a `TemplateResponse`, passing the `request` as one of the key-value pairs in the Jinja2 "context". +* Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template. -```Python hl_lines="4 11 15-16" +```Python hl_lines="4 11 15-18" {!../../../docs_src/templates/tutorial001.py!} ``` !!! note - Notice that you have to pass the `request` as part of the key-value pairs in the context for Jinja2. So, you also have to declare it in your *path operation*. + Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. + + Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. !!! tip By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. @@ -58,7 +60,7 @@ It will show the `id` taken from the "context" `dict` you passed: ## Templates and static files -And you can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted. +You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted. ```jinja hl_lines="4" {!../../../docs_src/templates/templates/item.html!} diff --git a/docs_src/templates/tutorial001.py b/docs_src/templates/tutorial001.py index 245e7110b195d..81ccc8d4d0b3f 100644 --- a/docs_src/templates/tutorial001.py +++ b/docs_src/templates/tutorial001.py @@ -13,4 +13,6 @@ @app.get("/items/{id}", response_class=HTMLResponse) async def read_item(request: Request, id: str): - return templates.TemplateResponse("item.html", {"request": request, "id": id}) + return templates.TemplateResponse( + request=request, name="item.html", context={"id": id} + ) diff --git a/pyproject.toml b/pyproject.toml index 499d0e5dc8c12..38728d99e945b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,11 +40,9 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.28.0,<0.29.0", + "starlette>=0.29.0,<0.33.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", - # TODO: remove this pin after upgrading Starlette 0.31.1 - "anyio>=3.7.1,<4.0.0", ] dynamic = ["version"] From 43e2223804d79a4c7309660a411487f0fa47c1c7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 26 Dec 2023 20:12:59 +0000 Subject: [PATCH 016/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f7b6207c243fa..f82577e0cae10 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Upgrades + +* ⬆ Upgrade Starlette to `>=0.29.0,<0.33.0`, update docs and usage of templates with new Starlette arguments. PR [#10846](https://github.com/tiangolo/fastapi/pull/10846) by [@tiangolo](https://github.com/tiangolo). + ## 0.107.0 ### Upgrades From fe0249a23ebb294be183b3e2cab82addbd68c42c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 26 Dec 2023 21:17:18 +0100 Subject: [PATCH 017/217] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.10?= =?UTF-8?q?8.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f82577e0cae10..3c7936ea97624 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.108.0 + ### Upgrades * ⬆ Upgrade Starlette to `>=0.29.0,<0.33.0`, update docs and usage of templates with new Starlette arguments. PR [#10846](https://github.com/tiangolo/fastapi/pull/10846) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 8a22b74b6759c..02ac83b5e4aee 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.107.0" +__version__ = "0.108.0" from starlette import status as status From dd790c34ff6f92dba68bef0f46a4a18ba7015f94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 26 Dec 2023 21:37:34 +0100 Subject: [PATCH 018/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?dependencies=20with=20yield=20source=20examples=20(#10847)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs_src/dependencies/tutorial008b.py | 2 +- docs_src/dependencies/tutorial008b_an.py | 2 +- docs_src/dependencies/tutorial008b_an_py39.py | 2 +- tests/test_tutorial/test_dependencies/test_tutorial008b.py | 2 +- tests/test_tutorial/test_dependencies/test_tutorial008b_an.py | 2 +- .../test_dependencies/test_tutorial008b_an_py39.py | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs_src/dependencies/tutorial008b.py b/docs_src/dependencies/tutorial008b.py index 4a1a70dcfcda9..163e96600f9b3 100644 --- a/docs_src/dependencies/tutorial008b.py +++ b/docs_src/dependencies/tutorial008b.py @@ -17,7 +17,7 @@ def get_username(): try: yield "Rick" except OwnerError as e: - raise HTTPException(status_code=400, detail=f"Onwer error: {e}") + raise HTTPException(status_code=400, detail=f"Owner error: {e}") @app.get("/items/{item_id}") diff --git a/docs_src/dependencies/tutorial008b_an.py b/docs_src/dependencies/tutorial008b_an.py index 3a0f1399a98f4..84d8f12c14887 100644 --- a/docs_src/dependencies/tutorial008b_an.py +++ b/docs_src/dependencies/tutorial008b_an.py @@ -18,7 +18,7 @@ def get_username(): try: yield "Rick" except OwnerError as e: - raise HTTPException(status_code=400, detail=f"Onwer error: {e}") + raise HTTPException(status_code=400, detail=f"Owner error: {e}") @app.get("/items/{item_id}") diff --git a/docs_src/dependencies/tutorial008b_an_py39.py b/docs_src/dependencies/tutorial008b_an_py39.py index 30c9cdc699c2e..3b8434c816711 100644 --- a/docs_src/dependencies/tutorial008b_an_py39.py +++ b/docs_src/dependencies/tutorial008b_an_py39.py @@ -19,7 +19,7 @@ def get_username(): try: yield "Rick" except OwnerError as e: - raise HTTPException(status_code=400, detail=f"Onwer error: {e}") + raise HTTPException(status_code=400, detail=f"Owner error: {e}") @app.get("/items/{item_id}") diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b.py b/tests/test_tutorial/test_dependencies/test_tutorial008b.py index ed4f4aaca8cd3..86acba9e4ff95 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial008b.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b.py @@ -14,7 +14,7 @@ def test_get_no_item(): def test_owner_error(): response = client.get("/items/plumbus") assert response.status_code == 400, response.text - assert response.json() == {"detail": "Onwer error: Rick"} + assert response.json() == {"detail": "Owner error: Rick"} def test_get_item(): diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py index aa76ad6afc940..7f51fc52a5133 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py @@ -14,7 +14,7 @@ def test_get_no_item(): def test_owner_error(): response = client.get("/items/plumbus") assert response.status_code == 400, response.text - assert response.json() == {"detail": "Onwer error: Rick"} + assert response.json() == {"detail": "Owner error: Rick"} def test_get_item(): diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py index aa76ad6afc940..7f51fc52a5133 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py @@ -14,7 +14,7 @@ def test_get_no_item(): def test_owner_error(): response = client.get("/items/plumbus") assert response.status_code == 400, response.text - assert response.json() == {"detail": "Onwer error: Rick"} + assert response.json() == {"detail": "Owner error: Rick"} def test_get_item(): From 84d400b9164f0a1727322de154855023b5eee73c Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 26 Dec 2023 20:37:55 +0000 Subject: [PATCH 019/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3c7936ea97624..d17e624148edf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* ✏ Fix typo in dependencies with yield source examples. PR [#10847](https://github.com/tiangolo/fastapi/pull/10847) by [@tiangolo](https://github.com/tiangolo). + ## 0.108.0 ### Upgrades From 040ad986d48bb9a400de804f7f25abb856d85e1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 26 Dec 2023 21:47:18 +0100 Subject: [PATCH 020/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d17e624148edf..bb96bce6684b4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -63,7 +63,7 @@ def get_username(): try: yield "Rick" except OwnerError as e: - raise HTTPException(status_code=400, detail=f"Onwer error: {e}") + raise HTTPException(status_code=400, detail=f"Owner error: {e}") @app.get("/items/{item_id}") From 1780c21e7ad8f4db048c443cdf9b03edfd34a1a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 8 Jan 2024 22:49:53 +0400 Subject: [PATCH 021/217] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20GitHub?= =?UTF-8?q?=20Action=20label-approved=20(#10905)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/label-approved.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 2113c468ac835..1138e6043436d 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -13,6 +13,6 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: docker://tiangolo/label-approved:0.0.2 + - uses: docker://tiangolo/label-approved:0.0.3 with: token: ${{ secrets.FASTAPI_LABEL_APPROVED }} From 04016d3bf93927f0358a8ceaa7c6cf6669b709bd Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 8 Jan 2024 18:50:12 +0000 Subject: [PATCH 022/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bb96bce6684b4..4cae0c5a397b8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * ✏ Fix typo in dependencies with yield source examples. PR [#10847](https://github.com/tiangolo/fastapi/pull/10847) by [@tiangolo](https://github.com/tiangolo). +### Internal + +* ⬆ Upgrade GitHub Action label-approved. PR [#10905](https://github.com/tiangolo/fastapi/pull/10905) by [@tiangolo](https://github.com/tiangolo). + ## 0.108.0 ### Upgrades From 3c7685273f799ad1d931be0923343320bbb1ca33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 9 Jan 2024 18:21:10 +0400 Subject: [PATCH 023/217] =?UTF-8?q?=F0=9F=91=B7=20Upgrade=20GitHub=20Actio?= =?UTF-8?q?n=20label-approved=20(#10913)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/label-approved.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 1138e6043436d..62daf260805f2 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -3,6 +3,7 @@ name: Label Approved on: schedule: - cron: "0 12 * * *" + workflow_dispatch: jobs: label-approved: @@ -13,6 +14,6 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: docker://tiangolo/label-approved:0.0.3 + - uses: docker://tiangolo/label-approved:0.0.4 with: token: ${{ secrets.FASTAPI_LABEL_APPROVED }} From d5498274f924e7f3091928ff4962ae9992542c34 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 14:21:30 +0000 Subject: [PATCH 024/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4cae0c5a397b8..b33edba84c854 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Internal +* 👷 Upgrade GitHub Action label-approved. PR [#10913](https://github.com/tiangolo/fastapi/pull/10913) by [@tiangolo](https://github.com/tiangolo). * ⬆ Upgrade GitHub Action label-approved. PR [#10905](https://github.com/tiangolo/fastapi/pull/10905) by [@tiangolo](https://github.com/tiangolo). ## 0.108.0 From e9ffa20c8e916336bd37c4f1477e0ec04445e0ce Mon Sep 17 00:00:00 2001 From: Andrey Otto Date: Tue, 9 Jan 2024 21:28:58 +0700 Subject: [PATCH 025/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20code=20examples?= =?UTF-8?q?=20in=20docs=20for=20body,=20replace=20name=20`create=5Fitem`?= =?UTF-8?q?=20with=20`update=5Fitem`=20when=20appropriate=20(#5913)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs_src/body/tutorial003.py | 2 +- docs_src/body/tutorial003_py310.py | 2 +- docs_src/body/tutorial004.py | 2 +- docs_src/body/tutorial004_py310.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs_src/body/tutorial003.py b/docs_src/body/tutorial003.py index 89a6b833ce237..2f33cc0389694 100644 --- a/docs_src/body/tutorial003.py +++ b/docs_src/body/tutorial003.py @@ -15,5 +15,5 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item): +async def update_item(item_id: int, item: Item): return {"item_id": item_id, **item.dict()} diff --git a/docs_src/body/tutorial003_py310.py b/docs_src/body/tutorial003_py310.py index a936f28fdc65d..440b210e6b47a 100644 --- a/docs_src/body/tutorial003_py310.py +++ b/docs_src/body/tutorial003_py310.py @@ -13,5 +13,5 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item): +async def update_item(item_id: int, item: Item): return {"item_id": item_id, **item.dict()} diff --git a/docs_src/body/tutorial004.py b/docs_src/body/tutorial004.py index e2df0df2baa27..0671e0a278581 100644 --- a/docs_src/body/tutorial004.py +++ b/docs_src/body/tutorial004.py @@ -15,7 +15,7 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item, q: Union[str, None] = None): +async def update_item(item_id: int, item: Item, q: Union[str, None] = None): result = {"item_id": item_id, **item.dict()} if q: result.update({"q": q}) diff --git a/docs_src/body/tutorial004_py310.py b/docs_src/body/tutorial004_py310.py index 60cfd96109b9c..b352b70ab6010 100644 --- a/docs_src/body/tutorial004_py310.py +++ b/docs_src/body/tutorial004_py310.py @@ -13,7 +13,7 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item, q: str | None = None): +async def update_item(item_id: int, item: Item, q: str | None = None): result = {"item_id": item_id, **item.dict()} if q: result.update({"q": q}) From 136fe2b70fd631ed6c62216496255f27e9e12664 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 14:30:16 +0000 Subject: [PATCH 026/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b33edba84c854..18f5c50b6e06d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update code examples in docs for body, replace name `create_item` with `update_item` when appropriate. PR [#5913](https://github.com/tiangolo/fastapi/pull/5913) by [@OttoAndrey](https://github.com/OttoAndrey). * ✏ Fix typo in dependencies with yield source examples. PR [#10847](https://github.com/tiangolo/fastapi/pull/10847) by [@tiangolo](https://github.com/tiangolo). ### Internal From 57d4d938412c9ac0daf8f32eacb2adc8023375d4 Mon Sep 17 00:00:00 2001 From: Keshav Malik <33570148+theinfosecguy@users.noreply.github.com> Date: Tue, 9 Jan 2024 20:02:46 +0530 Subject: [PATCH 027/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20blog=20for=20FastA?= =?UTF-8?q?PI=20&=20Supabase=20(#6018)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 726e7eae7ec73..35c9b6718ed76 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ Articles: English: + - author: Keshav Malik + author_link: https://theinfosecguy.xyz/ + link: https://blog.theinfosecguy.xyz/building-a-crud-api-with-fastapi-and-supabase-a-step-by-step-guide + title: Building a CRUD API with FastAPI and Supabase - author: Adejumo Ridwan Suleiman author_link: https://www.linkedin.com/in/adejumoridwan/ link: https://medium.com/python-in-plain-english/build-an-sms-spam-classifier-serverless-database-with-faunadb-and-fastapi-23dbb275bc5b From 4491ea688201db4f32d294b8a73862b9df367d99 Mon Sep 17 00:00:00 2001 From: Moustapha Sall <58856327+s-mustafa@users.noreply.github.com> Date: Tue, 9 Jan 2024 09:35:33 -0500 Subject: [PATCH 028/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20example=20sourc?= =?UTF-8?q?e=20files=20for=20SQL=20databases=20with=20SQLAlchemy=20(#9508)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Marcelo Trylesinski --- docs_src/sql_databases/sql_app/models.py | 4 ++-- docs_src/sql_databases/sql_app_py310/models.py | 4 ++-- docs_src/sql_databases/sql_app_py39/models.py | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs_src/sql_databases/sql_app/models.py b/docs_src/sql_databases/sql_app/models.py index 62d8ab4aaac16..09ae2a8077f68 100644 --- a/docs_src/sql_databases/sql_app/models.py +++ b/docs_src/sql_databases/sql_app/models.py @@ -7,7 +7,7 @@ class User(Base): __tablename__ = "users" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean, default=True) @@ -18,7 +18,7 @@ class User(Base): class Item(Base): __tablename__ = "items" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) title = Column(String, index=True) description = Column(String, index=True) owner_id = Column(Integer, ForeignKey("users.id")) diff --git a/docs_src/sql_databases/sql_app_py310/models.py b/docs_src/sql_databases/sql_app_py310/models.py index 62d8ab4aaac16..09ae2a8077f68 100644 --- a/docs_src/sql_databases/sql_app_py310/models.py +++ b/docs_src/sql_databases/sql_app_py310/models.py @@ -7,7 +7,7 @@ class User(Base): __tablename__ = "users" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean, default=True) @@ -18,7 +18,7 @@ class User(Base): class Item(Base): __tablename__ = "items" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) title = Column(String, index=True) description = Column(String, index=True) owner_id = Column(Integer, ForeignKey("users.id")) diff --git a/docs_src/sql_databases/sql_app_py39/models.py b/docs_src/sql_databases/sql_app_py39/models.py index 62d8ab4aaac16..09ae2a8077f68 100644 --- a/docs_src/sql_databases/sql_app_py39/models.py +++ b/docs_src/sql_databases/sql_app_py39/models.py @@ -7,7 +7,7 @@ class User(Base): __tablename__ = "users" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean, default=True) @@ -18,7 +18,7 @@ class User(Base): class Item(Base): __tablename__ = "items" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) title = Column(String, index=True) description = Column(String, index=True) owner_id = Column(Integer, ForeignKey("users.id")) From ed628ddb92505234b026d8ce2e2e8d07178137ba Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 14:37:20 +0000 Subject: [PATCH 029/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 18f5c50b6e06d..d44600ab85277 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update example source files for SQL databases with SQLAlchemy. PR [#9508](https://github.com/tiangolo/fastapi/pull/9508) by [@s-mustafa](https://github.com/s-mustafa). * 📝 Update code examples in docs for body, replace name `create_item` with `update_item` when appropriate. PR [#5913](https://github.com/tiangolo/fastapi/pull/5913) by [@OttoAndrey](https://github.com/OttoAndrey). * ✏ Fix typo in dependencies with yield source examples. PR [#10847](https://github.com/tiangolo/fastapi/pull/10847) by [@tiangolo](https://github.com/tiangolo). From 897cde9fe2843655130bafb191764459456d0761 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 14:37:53 +0000 Subject: [PATCH 030/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d44600ab85277..6f96b0a3d9a6d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add blog for FastAPI & Supabase. PR [#6018](https://github.com/tiangolo/fastapi/pull/6018) by [@theinfosecguy](https://github.com/theinfosecguy). * 📝 Update example source files for SQL databases with SQLAlchemy. PR [#9508](https://github.com/tiangolo/fastapi/pull/9508) by [@s-mustafa](https://github.com/s-mustafa). * 📝 Update code examples in docs for body, replace name `create_item` with `update_item` when appropriate. PR [#5913](https://github.com/tiangolo/fastapi/pull/5913) by [@OttoAndrey](https://github.com/OttoAndrey). * ✏ Fix typo in dependencies with yield source examples. PR [#10847](https://github.com/tiangolo/fastapi/pull/10847) by [@tiangolo](https://github.com/tiangolo). From a1ea70804401625d50811e32840b08d94426805d Mon Sep 17 00:00:00 2001 From: Tristan Marion Date: Tue, 9 Jan 2024 15:44:08 +0100 Subject: [PATCH 031/217] =?UTF-8?q?=F0=9F=93=9D=20Replace=20HTTP=20code=20?= =?UTF-8?q?returned=20in=20case=20of=20existing=20user=20error=20in=20docs?= =?UTF-8?q?=20for=20testing=20(#4482)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs_src/app_testing/app_b/main.py | 2 +- docs_src/app_testing/app_b/test_main.py | 2 +- docs_src/app_testing/app_b_py310/main.py | 2 +- docs_src/app_testing/app_b_py310/test_main.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs_src/app_testing/app_b/main.py b/docs_src/app_testing/app_b/main.py index 11558b8e813f4..45a103378388a 100644 --- a/docs_src/app_testing/app_b/main.py +++ b/docs_src/app_testing/app_b/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b/test_main.py b/docs_src/app_testing/app_b/test_main.py index d186b8ecbacfa..4e2b98e237c3a 100644 --- a/docs_src/app_testing/app_b/test_main.py +++ b/docs_src/app_testing/app_b/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_py310/main.py b/docs_src/app_testing/app_b_py310/main.py index b4c72de5c9431..eccedcc7ce2ec 100644 --- a/docs_src/app_testing/app_b_py310/main.py +++ b/docs_src/app_testing/app_b_py310/main.py @@ -31,6 +31,6 @@ async def create_item(item: Item, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_py310/test_main.py b/docs_src/app_testing/app_b_py310/test_main.py index d186b8ecbacfa..4e2b98e237c3a 100644 --- a/docs_src/app_testing/app_b_py310/test_main.py +++ b/docs_src/app_testing/app_b_py310/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} From fe694766ae5d4f56d017cfc28ff358a3a6193dcf Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 14:45:35 +0000 Subject: [PATCH 032/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6f96b0a3d9a6d..8dfb1a9eaeef1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Replace HTTP code returned in case of existing user error in docs for testing. PR [#4482](https://github.com/tiangolo/fastapi/pull/4482) by [@TristanMarion](https://github.com/TristanMarion). * 📝 Add blog for FastAPI & Supabase. PR [#6018](https://github.com/tiangolo/fastapi/pull/6018) by [@theinfosecguy](https://github.com/theinfosecguy). * 📝 Update example source files for SQL databases with SQLAlchemy. PR [#9508](https://github.com/tiangolo/fastapi/pull/9508) by [@s-mustafa](https://github.com/s-mustafa). * 📝 Update code examples in docs for body, replace name `create_item` with `update_item` when appropriate. PR [#5913](https://github.com/tiangolo/fastapi/pull/5913) by [@OttoAndrey](https://github.com/OttoAndrey). From 78ff6e3efd8899918957f6176585be3610c8c730 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 9 Jan 2024 18:57:33 +0400 Subject: [PATCH 033/217] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20GitHub?= =?UTF-8?q?=20Action=20latest-changes=20(#10915)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/latest-changes.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index b9b550d5ea807..27e062d090546 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -34,7 +34,7 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: docker://tiangolo/latest-changes:0.2.0 + - uses: docker://tiangolo/latest-changes:0.3.0 # - uses: tiangolo/latest-changes@main with: token: ${{ secrets.GITHUB_TOKEN }} From 7fbb7963d31489fc157bf2de3e437d9084042080 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 14:57:58 +0000 Subject: [PATCH 034/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8dfb1a9eaeef1..a33c1bc7980f0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Internal +* ⬆ Upgrade GitHub Action latest-changes. PR [#10915](https://github.com/tiangolo/fastapi/pull/10915) by [@tiangolo](https://github.com/tiangolo). * 👷 Upgrade GitHub Action label-approved. PR [#10913](https://github.com/tiangolo/fastapi/pull/10913) by [@tiangolo](https://github.com/tiangolo). * ⬆ Upgrade GitHub Action label-approved. PR [#10905](https://github.com/tiangolo/fastapi/pull/10905) by [@tiangolo](https://github.com/tiangolo). From 423cdd24ccd38957e50be5016c6feb88a5bb3ba4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 9 Jan 2024 19:02:53 +0400 Subject: [PATCH 035/217] =?UTF-8?q?=F0=9F=91=B7=20Upgrade=20custom=20GitHu?= =?UTF-8?q?b=20Action=20comment-docs-preview-in-pr=20(#10916)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/actions/comment-docs-preview-in-pr/Dockerfile | 6 ++++-- .github/actions/comment-docs-preview-in-pr/app/main.py | 3 ++- .github/actions/comment-docs-preview-in-pr/requirements.txt | 4 ++++ 3 files changed, 10 insertions(+), 3 deletions(-) create mode 100644 .github/actions/comment-docs-preview-in-pr/requirements.txt diff --git a/.github/actions/comment-docs-preview-in-pr/Dockerfile b/.github/actions/comment-docs-preview-in-pr/Dockerfile index 14b0d026956fb..42627fe190ebf 100644 --- a/.github/actions/comment-docs-preview-in-pr/Dockerfile +++ b/.github/actions/comment-docs-preview-in-pr/Dockerfile @@ -1,6 +1,8 @@ -FROM python:3.9 +FROM python:3.10 -RUN pip install httpx "pydantic==1.5.1" pygithub +COPY ./requirements.txt /app/requirements.txt + +RUN pip install -r /app/requirements.txt COPY ./app /app diff --git a/.github/actions/comment-docs-preview-in-pr/app/main.py b/.github/actions/comment-docs-preview-in-pr/app/main.py index 68914fdb9a818..8cc119fe0af8c 100644 --- a/.github/actions/comment-docs-preview-in-pr/app/main.py +++ b/.github/actions/comment-docs-preview-in-pr/app/main.py @@ -6,7 +6,8 @@ import httpx from github import Github from github.PullRequest import PullRequest -from pydantic import BaseModel, BaseSettings, SecretStr, ValidationError +from pydantic import BaseModel, SecretStr, ValidationError +from pydantic_settings import BaseSettings github_api = "https://api.github.com" diff --git a/.github/actions/comment-docs-preview-in-pr/requirements.txt b/.github/actions/comment-docs-preview-in-pr/requirements.txt new file mode 100644 index 0000000000000..74a3631f48fa3 --- /dev/null +++ b/.github/actions/comment-docs-preview-in-pr/requirements.txt @@ -0,0 +1,4 @@ +PyGithub +pydantic>=2.5.3,<3.0.0 +pydantic-settings>=2.1.0,<3.0.0 +httpx From 635d1a2d6dcd7c26af9d8b7db19dd8c1f25a777a Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:04:35 +0000 Subject: [PATCH 036/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a33c1bc7980f0..ad11537eb5d39 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Internal +* 👷 Upgrade custom GitHub Action comment-docs-preview-in-pr. PR [#10916](https://github.com/tiangolo/fastapi/pull/10916) by [@tiangolo](https://github.com/tiangolo). * ⬆ Upgrade GitHub Action latest-changes. PR [#10915](https://github.com/tiangolo/fastapi/pull/10915) by [@tiangolo](https://github.com/tiangolo). * 👷 Upgrade GitHub Action label-approved. PR [#10913](https://github.com/tiangolo/fastapi/pull/10913) by [@tiangolo](https://github.com/tiangolo). * ⬆ Upgrade GitHub Action label-approved. PR [#10905](https://github.com/tiangolo/fastapi/pull/10905) by [@tiangolo](https://github.com/tiangolo). From 7111d69f285469a1fb2f9389e8dc2de41a5bd113 Mon Sep 17 00:00:00 2001 From: pablocm83 Date: Tue, 9 Jan 2024 10:08:24 -0500 Subject: [PATCH 037/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Spanish=20translat?= =?UTF-8?q?ion=20for=20`docs/es/docs/resources/index.md`=20(#10909)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/resources/index.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/es/docs/resources/index.md diff --git a/docs/es/docs/resources/index.md b/docs/es/docs/resources/index.md new file mode 100644 index 0000000000000..92898d319e6da --- /dev/null +++ b/docs/es/docs/resources/index.md @@ -0,0 +1,3 @@ +# Recursos + +Recursos adicionales, enlaces externos, artículos y más. ✈ From e10bdb82cc9199b47c7804bfda842990723c4a03 Mon Sep 17 00:00:00 2001 From: pablocm83 Date: Tue, 9 Jan 2024 10:09:12 -0500 Subject: [PATCH 038/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Spanish=20translat?= =?UTF-8?q?ion=20for=20`docs/es/docs/about/index.md`=20(#10908)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/es/docs/about/index.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/es/docs/about/index.md diff --git a/docs/es/docs/about/index.md b/docs/es/docs/about/index.md new file mode 100644 index 0000000000000..e83400a8dc100 --- /dev/null +++ b/docs/es/docs/about/index.md @@ -0,0 +1,3 @@ +# Acerca de + +Acerca de FastAPI, su diseño, inspiración y más. 🀓 From d1299103236eb88b37553b94996bcf74c8fe4485 Mon Sep 17 00:00:00 2001 From: pablocm83 Date: Tue, 9 Jan 2024 10:09:47 -0500 Subject: [PATCH 039/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Spanish=20translat?= =?UTF-8?q?ion=20for=20`docs/es/docs/help/index.md`=20(#10907)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/help/index.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/es/docs/help/index.md diff --git a/docs/es/docs/help/index.md b/docs/es/docs/help/index.md new file mode 100644 index 0000000000000..f6ce35e9c1b46 --- /dev/null +++ b/docs/es/docs/help/index.md @@ -0,0 +1,3 @@ +# Ayuda + +Ayuda y recibe ayuda, contribuye, involúcrate. 🀝 From 631601787b6bc8835edc0967653bfa6378686473 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:11:10 +0000 Subject: [PATCH 040/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ad11537eb5d39..872464de84b84 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,10 @@ hide: * 📝 Update code examples in docs for body, replace name `create_item` with `update_item` when appropriate. PR [#5913](https://github.com/tiangolo/fastapi/pull/5913) by [@OttoAndrey](https://github.com/OttoAndrey). * ✏ Fix typo in dependencies with yield source examples. PR [#10847](https://github.com/tiangolo/fastapi/pull/10847) by [@tiangolo](https://github.com/tiangolo). +### Translations + +* 🌐 Add Spanish translation for `docs/es/docs/resources/index.md`. PR [#10909](https://github.com/tiangolo/fastapi/pull/10909) by [@pablocm83](https://github.com/pablocm83). + ### Internal * 👷 Upgrade custom GitHub Action comment-docs-preview-in-pr. PR [#10916](https://github.com/tiangolo/fastapi/pull/10916) by [@tiangolo](https://github.com/tiangolo). From ca10d3927b7f16acf109a848769b27beb40251c2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:11:39 +0000 Subject: [PATCH 041/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 872464de84b84..8a80aa2958994 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Spanish translation for `docs/es/docs/about/index.md`. PR [#10908](https://github.com/tiangolo/fastapi/pull/10908) by [@pablocm83](https://github.com/pablocm83). * 🌐 Add Spanish translation for `docs/es/docs/resources/index.md`. PR [#10909](https://github.com/tiangolo/fastapi/pull/10909) by [@pablocm83](https://github.com/pablocm83). ### Internal From 5b63406aa5dcc0260a45c7bb0c86d607f3ff532c Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:12:19 +0000 Subject: [PATCH 042/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8a80aa2958994..4c380ed3f92ef 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Spanish translation for `docs/es/docs/help/index.md`. PR [#10907](https://github.com/tiangolo/fastapi/pull/10907) by [@pablocm83](https://github.com/pablocm83). * 🌐 Add Spanish translation for `docs/es/docs/about/index.md`. PR [#10908](https://github.com/tiangolo/fastapi/pull/10908) by [@pablocm83](https://github.com/pablocm83). * 🌐 Add Spanish translation for `docs/es/docs/resources/index.md`. PR [#10909](https://github.com/tiangolo/fastapi/pull/10909) by [@pablocm83](https://github.com/pablocm83). From 2090e9a3e258cc1517018ebdd6283171f334247c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Tue, 9 Jan 2024 18:14:23 +0300 Subject: [PATCH 043/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/newsletter.md`=20(#10550)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/newsletter.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/tr/docs/newsletter.md diff --git a/docs/tr/docs/newsletter.md b/docs/tr/docs/newsletter.md new file mode 100644 index 0000000000000..22ca1b1e2949e --- /dev/null +++ b/docs/tr/docs/newsletter.md @@ -0,0 +1,5 @@ +# FastAPI ve Arkadaşları BÃŒlteni + + + + From eecc7a81136eaa6617b9491cfc3c10930c90e30c Mon Sep 17 00:00:00 2001 From: David Takacs <44911031+takacs@users.noreply.github.com> Date: Tue, 9 Jan 2024 10:16:04 -0500 Subject: [PATCH 044/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Hungarian=20transl?= =?UTF-8?q?ation=20for=20`/docs/hu/docs/index.md`=20(#10812)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Peter Panko --- docs/hu/docs/index.md | 469 ++++++++++++++++++++++++++++++++++++++++++ docs/hu/mkdocs.yml | 1 + 2 files changed, 470 insertions(+) create mode 100644 docs/hu/docs/index.md create mode 100644 docs/hu/mkdocs.yml diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md new file mode 100644 index 0000000000000..29c3c05ac6271 --- /dev/null +++ b/docs/hu/docs/index.md @@ -0,0 +1,469 @@ +

+ FastAPI +

+

+ FastAPI keretrendszer, nagy teljesítmény, könnyen tanulható, gyorsan kódolható, productionre kész +

+

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

+ +--- + +**Dokumentáció**: https://fastapi.tiangolo.com + +**Forrás kód**: https://github.com/tiangolo/fastapi + +--- +A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python 3.8+-al, a Python szabványos típusjelöléseire építve. + + +Kulcs funkciók: + +* **Gyors**: Nagyon nagy teljesítmény, a **NodeJS**-el és a **Go**-val egyenrangú (a Starlettenek és a Pydantic-nek köszönhetően). [Az egyik leggyorsabb Python keretrendszer](#performance). +* **Gyorsan kódolható**: A funkciók fejlesztési sebességét 200-300 százalékkal megnöveli. * +* **Kevesebb hiba**: KörÃŒlbelÃŒl 40%-al csökkenti az emberi (fejlesztői) hibák számát. * +* **Intuitív**: Kiváló szerkesztő támogatás. Kiegészítés mindenhol. Kevesebb hibakereséssel töltött idő. +* **Egyszerű**: Egyszerű tanulásra és használatra tervezve. Kevesebb dokumentáció olvasással töltött idő. +* **Rövid**: Kód duplikáció minimalizálása. Több funkció minden paraméter deklarálásával. Kevesebb hiba. +* **Robosztus**: Production ready kód. Automatikus interaktív dokumentáció val. +* **Szabvány alapú**: Az API-ok nyílt szabványaira alapuló (és azokkal teljesen kompatibilis): OpenAPI (korábban Swagger néven ismert) és a JSON Schema. + +* Egy production alkalmazásokat építő belső fejlesztői csapat tesztjein alapuló becslés. + +## Szponzorok + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +További szponzorok + +## Vélemények + +"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_I’m over the moon excited about **FastAPI**. It’s so fun!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" + +"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, a CLI-ok FastAPI-ja + + + +Ha egy olyan CLI alkalmazást fejlesztesz amit a parancssorban kell használni webes API helyett, tekintsd meg: **Typer**. + +**Typer** a FastAPI kistestvére. A **CLI-k FastAPI-ja**. ⌚ 🚀 + +## Követelmények + +Python 3.8+ + +A FastAPI óriások vállán áll: + +* Starlette a webes részekhez. +* Pydantic az adat részekhez. + +## Telepítés + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +A production-höz egy ASGI szerverre is szÌkség lesz, mint például az Uvicorn vagy a Hypercorn. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## Példa + +### Hozd létre + +* Hozz létre a `main.py` fájlt a következő tartalommal: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+Vagy használd az async def-et... + +Ha a kódod `async` / `await`-et, használ `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Megjegyzés**: + +Ha nem tudod, tekintsd meg a _"Sietsz?"_ szekciót `async` és `await`-ről dokumentációba. + +
+ +### Futtasd le + +Indítsd el a szervert a következő paranccsal: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+A parancsról uvicorn main:app --reload... + +A `uvicorn main:app` parancs a következőre utal: + +* `main`: fájl `main.py` (a Python "modul"). +* `app`: a `main.py`-ban a `app = FastAPI()` sorral létrehozott objektum. +* `--reload`: kód változtatás esetén újra indítja a szervert. Csak fejlesztés közben használandó. + +
+ +### Ellenőrizd + +Nyisd meg a böngésződ a következő címen: http://127.0.0.1:8000/items/5?q=somequery. + +A következő JSON választ fogod látni: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Máris létrehoztál egy API-t ami: + +* HTTP kéréseket fogad a `/` és `/items/{item_id}` _útvonalakon_. +* Mindkét _útvonal_ a `GET` műveletet használja (másik elnevezés: HTTP _metódus_). +* A `/items/{item_id}` _útvonalnak_ van egy _path paramétere_, az `item_id`, aminek `int` típusúnak kell lennie. +* A `/items/{item_id}` _útvonalnak_ még van egy opcionális, `str` típusú _query paramétere_ is, a `q`. + +### Interaktív API dokumentáció + +Most nyisd meg a http://127.0.0.1:8000/docs címet. + +Az automatikus interaktív API dokumentációt fogod látni (amit a Swagger UI-al hozunk létre): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternatív API dokumentáció + +És most menj el a http://127.0.0.1:8000/redoc címre. + +Az alternatív automatikus dokumentációt fogod látni. (lásd ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Példa frissítése + +Módosítsuk a `main.py` fájlt, hogy `PUT` kérések esetén tudjon body-t fogadni. + +Deklaráld a body-t standard Python típusokkal, a Pydantic-nak köszönhetően. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +A szerver automatikusan újraindul (mert hozzáadtuk a --reload paramétert a fenti `uvicorn` parancshoz). + +### Interaktív API dokumentáció frissítése + +Most menj el a http://127.0.0.1:8000/docs címre. + +* Az interaktív API dokumentáció automatikusan frissÃŒlt így már benne van az új body. + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Kattints rá a "Try it out" gombra, ennek segítségével kitöltheted a paramétereket és közvetlen használhatod az API-t: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Ezután kattints az "Execute" gompra, a felhasználói felÃŒlet kommunikálni fog az API-oddal. ElkÃŒldi a paramétereket és a visszakapott választ megmutatja a képernyődön. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternatív API dokumentáció frissítés + +Most menj el a http://127.0.0.1:8000/redoc címre. + +* Az alternatív dokumentáció szintúgy tÃŒkrözni fogja az új kérési paraméter és body-t. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Összefoglalás + +ÖsszegzésÃŒl, deklarálod **egyszer** a paraméterek, body, stb típusát funkciós paraméterekként. + +Ezt standard modern Python típusokkal csinálod. + +Nem kell új szintaxist, vagy specifikus könyvtár mert metódósait, stb. megtanulnod. + +Csak standard **Python 3.8+**. + +Például egy `int`-nek: + +```Python +item_id: int +``` + +Egy komplexebb `Item` modellnek: + +```Python +item: Item +``` + +... És csupán egy deklarációval megkapod a: + +* Szerkesztő támogatást, beleértve: + * Szövegkiegészítés. + * Típus ellenőrzés. +* Adatok validációja: + * Automatikus és érthető hibák amikor az adatok hibásak. + * Validáció mélyen ágyazott objektumok esetén is. +* Bemeneti adatok átváltása : a hálózatról érkező Python adatokká és típusokká. Adatok olvasása következő forrásokból: + * JSON. + * Cím paraméterek. + * Query paraméterek. + * Cookie-k. + * Header-ök. + * Formok. + * Fájlok. +* Kimeneti adatok átváltása: Python adatok is típusokról hálózati adatokká: + * válts át Python típusokat (`str`, `int`, `float`, `bool`, `list`, etc). + * `datetime` csak objektumokat. + * `UUID` objektumokat. + * Adatbázis modelleket. + * ...És sok mást. +* Automatikus interaktív dokumentáció, beleértve két alternatív dokumentációt is: + * Swagger UI. + * ReDoc. + +--- + +Visszatérve az előző kód példához. A **FastAPI**: + +* Validálja hogy van egy `item_id` mező a `GET` és `PUT` kérésekben. +* Validálja hogy az `item_id` `int` típusú a `GET` és `PUT` kérésekben. + * Ha nem akkor látni fogunk egy tiszta hibát ezzel kapcsolatban. +* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. + * Mivel a `q` paraméter `= None`-al van deklarálva, ezért opcionális. + * `None` nélkÃŒl ez a mező kötelező lenne (mint például a body `PUT` kérések esetén). +* a `/items/{item_id}` címre érkező `PUT` kérések esetén, a JSON-t a következőképpen olvassa be: + * Ellenőrzi hogy létezik a kötelező `name` nevű attribútum és `string`. + * Ellenőrzi hogy létezik a kötelező `price` nevű attribútum és `float`. + * Ellenőrzi hogy létezik a `is_offer` nevű opcionális paraméter, ami ha létezik akkor `bool` + * Ez ágyazott JSON objektumokkal is működik +* JSONről való automatikus konvertálás. +* dokumentáljuk mindent OpenAPI-al amit használható: + * Interaktív dokumentációs rendszerekkel. + * Automatikus kliens kód generáló a rendszerekkel, több nyelven. +* Hozzá tartozik kettő interaktív dokumentációs web felÃŒlet. + +--- + +Eddig csak a felszínt kapargattuk, de a lényeg hogy most már könnyebben érthető hogyan működik. + +Próbáld kicserélni a következő sorban: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...ezt: + +```Python + ... "item_name": item.name ... +``` + +...erre: + +```Python + ... "item_price": item.price ... +``` + +... És figyeld meg hogy a szerkesztő automatikusan tudni fogja a típusokat és kiegészíti azokat: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Teljesebb példákért és funkciókért tekintsd meg a Tutorial - User Guide -t. + +**Spoiler veszély**: a Tutorial - User Guidehoz tartozik: + +* **Paraméterek** deklarációja kÃŒlönböző helyekről: **header-ök**, **cookie-k**, **form mezők** és **fájlok**. +* Hogyan állíts be **validációs feltételeket** mint a `maximum_length` vagy a `regex`. +* Nagyon hatékony és erős **FÃŒggőség Injekció** rendszerek. +* Biztonság és autentikáció beleértve, **OAuth2**, **JWT tokens** és **HTTP Basic** támogatást. +* Több haladó (de ugyanannyira könnyű) technika **mélyen ágyazott JSON modellek deklarációjára** (Pydantic-nek köszönhetően). +* **GraphQL** integráció Strawberry-vel és más könyvtárakkal. +* több extra funkció (Starlette-nek köszönhetően) pl.: + * **WebSockets** + * rendkívÃŒl könnyű tesztek HTTPX és `pytest` alapokra építve + * **CORS** + * **Cookie Sessions** + * ...és több. + +## Teljesítmény + +A fÃŒggetlen TechEmpower benchmarkok szerint az Uvicorn alatt futó **FastAPI** alkalmazások az egyik leggyorsabb Python keretrendszerek közé tartoznak, éppen lemaradva a Starlette és az Uvicorn (melyeket a FastAPI belsőleg használ) mögött.(*) + +Ezeknek a további megértéséhez: Benchmarks. + +## Opcionális követelmények + +Pydantic által használt: + +* email_validator - e-mail validációkra. +* pydantic-settings - Beállítások követésére. +* pydantic-extra-types - Extra típusok Pydantic-hoz. + +Starlette által használt: + +* httpx - Követelmény ha a `TestClient`-et akarod használni. +* jinja2 - Követelmény ha az alap template konfigurációt akarod használni. +* python-multipart - Követelmény ha "parsing"-ot akarsz támogatni, `request.form()`-al. +* itsdangerous - Követelmény `SessionMiddleware` támogatáshoz. +* pyyaml - Követelmény a Starlette `SchemaGenerator`-ának támogatásához (valószínűleg erre nincs szÃŒkség FastAPI használása esetén). +* ujson - Követelmény ha `UJSONResponse`-t akarsz használni. + +FastAPI / Starlette által használt + +* uvicorn - Szerverekhez amíg betöltik és szolgáltatják az applikációdat. +* orjson - Követelmény ha `ORJSONResponse`-t akarsz használni. + +Ezeket mind telepítheted a `pip install "fastapi[all]"` paranccsal. + +## Licensz +Ez a projekt az MIT license, licensz alatt fut diff --git a/docs/hu/mkdocs.yml b/docs/hu/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/hu/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml From f9cbaa5f39f2cb199948f5dfa6d15c48e465e7d1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:18:47 +0000 Subject: [PATCH 045/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4c380ed3f92ef..3a1a1b79470a7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/newsletter.md`. PR [#10550](https://github.com/tiangolo/fastapi/pull/10550) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Spanish translation for `docs/es/docs/help/index.md`. PR [#10907](https://github.com/tiangolo/fastapi/pull/10907) by [@pablocm83](https://github.com/pablocm83). * 🌐 Add Spanish translation for `docs/es/docs/about/index.md`. PR [#10908](https://github.com/tiangolo/fastapi/pull/10908) by [@pablocm83](https://github.com/pablocm83). * 🌐 Add Spanish translation for `docs/es/docs/resources/index.md`. PR [#10909](https://github.com/tiangolo/fastapi/pull/10909) by [@pablocm83](https://github.com/pablocm83). From ce9aba258e47e5128afb0947b75527c05b17d2f7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:22:55 +0000 Subject: [PATCH 046/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3a1a1b79470a7..734ab2d601599 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Hungarian translation for `/docs/hu/docs/index.md`. PR [#10812](https://github.com/tiangolo/fastapi/pull/10812) by [@takacs](https://github.com/takacs). * 🌐 Add Turkish translation for `docs/tr/docs/newsletter.md`. PR [#10550](https://github.com/tiangolo/fastapi/pull/10550) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Spanish translation for `docs/es/docs/help/index.md`. PR [#10907](https://github.com/tiangolo/fastapi/pull/10907) by [@pablocm83](https://github.com/pablocm83). * 🌐 Add Spanish translation for `docs/es/docs/about/index.md`. PR [#10908](https://github.com/tiangolo/fastapi/pull/10908) by [@pablocm83](https://github.com/pablocm83). From 3af6766e26607cfd1007cbf33f7440f3c879fe79 Mon Sep 17 00:00:00 2001 From: ArtemKhymenko Date: Tue, 9 Jan 2024 17:25:48 +0200 Subject: [PATCH 047/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/body-fields.md`=20(#10670)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Maksym Zavalniuk Co-authored-by: Rostyslav --- docs/uk/docs/tutorial/body-fields.md | 116 +++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 docs/uk/docs/tutorial/body-fields.md diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md new file mode 100644 index 0000000000000..eee993cbe3616 --- /dev/null +++ b/docs/uk/docs/tutorial/body-fields.md @@ -0,0 +1,116 @@ +# ТілП - ППля + +Так саЌП як вО ЌПжете вОзМачатО ЎПЎаткПву валіЎацію та ЌетаЎаМі у параЌетрах *фуМкції ПбрПбкО шляху* за ЎПпПЌПгПю `Query`, `Path` та `Body`, вО ЌПжете вОзМачатО валіЎацію та ЌетаЎаМі всереЎОМі ЌПЎелей Pydantic за ЎПпПЌПгПю `Field` віЎ Pydantic. + +## ІЌпПрт `Field` + +СпПчатку ваЌ пПтрібМП іЌпПртуватО це: + +=== "Python 3.10+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + ВартП кПрОстуватОсь `Annotated` версією, якщП це ЌПжлОвП. + + ```Python hl_lines="2" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + ВартП кПрОстуватОсь `Annotated` версією, якщП це ЌПжлОвП. + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` + +!!! warning + ЗверМіть увагу, щП `Field` іЌпПртується пряЌП з `pydantic`, а Ме з `fastapi`, як всі іМші (`Query`, `Path`, `Body` тПщП). + +## ОгПлПшеММя атрОбутів ЌПЎелі + +ВО ЌПжете вОкПрОстПвуватО `Field` з атрОбутаЌО ЌПЎелі: + +=== "Python 3.10+" + + ```Python hl_lines="11-14" + {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11-14" + {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12-15" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + ВартП кПрОстуватОсь `Annotated` версією, якщП це ЌПжлОвП.. + + ```Python hl_lines="9-12" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + ВартП кПрОстуватОсь `Annotated` версією, якщП це ЌПжлОвП.. + + ```Python hl_lines="11-14" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` + +`Field` працює так саЌП, як `Query`, `Path` і `Body`, у МьПгП такі саЌі параЌетрО тПщП. + +!!! note "ТехМічМі Ўеталі" + НасправЎі, `Query`, `Path` та іМші, щП вО пПбачОте Ўалі, ствПрюють Пб'єктО піЎкласів загальМПгП класу `Param`, кПтрОй саЌ є піЎкласПЌ класу `FieldInfo` з Pydantic. + + І `Field` віЎ Pydantic такПж пПвертає екзеЌпляр `FieldInfo`. + + `Body` такПж безпПсереЎМьП пПвертає Пб'єктО піЎкласу `FieldInfo`. І є іМші піЎкласО, які вО пПбачОте пізМіше, щП є піЎкласаЌО класу Body. + + ПаЌ'ятайте, щП кПлО вО іЌпПртуєте 'Query', 'Path' та іМше з 'fastapi', вПМО фактОчМП є фуМкціяЌО, які пПвертають спеціальМі класО. + +!!! tip + ЗверМіть увагу, щП кПжеМ атрОбут ЌПЎелі із тОпПЌ, зМачеММяЌ за заЌПвчуваММяЌ та `Field` Ќає ту саЌу структуру, щП й параЌетр *фуМкції ПбрПбкО шляху*, з `Field` заЌість `Path`, `Query` і `Body`. + +## ДПЎаваММя ЎПЎаткПвПї іМфПрЌації + +ВО ЌПжете вОзМачОтО ЎПЎаткПву іМфПрЌацію у `Field`, `Query`, `Body` тПщП. І вПМа буЎе включеМа у згеМерПваМу JSON схеЌу. + +ВО ЎізМаєтеся більше прП ЎПЎаваММя ЎПЎаткПвПї іМфПрЌації пізМіше у ЎПкуЌеМтації, кПлО вОвчатОЌете вОзМачеММя прОклаЎів. + +!!! warning + ДПЎаткПві ключі, переЎаМі в `Field`, такПж буЎуть прОсутМі у згеМерПваМій схеЌі OpenAPI Ўля вашПгП ЎПЎатка. + ОскількО ці ключі Ме ПбПв'язкПвП ЌПжуть бутО частОМПю спецОфікації OpenAPI, Ўеякі іМструЌеМтО OpenAPI, МапрОклаЎ, [OpenAPI валіЎатПр](https://validator.swagger.io/), ЌПжуть Ме працюватО з вашПю згеМерПваМПю схеЌПю. + +## ПіЎсуЌПк + +ВО ЌПжете вОкПрОстПвуватО `Field` з Pydantic Ўля вОзМачеММя ЎПЎаткПвОх перевірПк та ЌетаЎаМОх Ўля атрОбутів ЌПЎелі. + +ВО такПж ЌПжете вОкПрОстПвуватО ЎПЎаткПві іЌеМПваМі аргуЌеМтО Ўля переЎачі ЎПЎаткПвОх ЌетаЎаМОх JSON схеЌО. From 4fa251beb5546ea1b72b1c7bf3d3ed35324928a4 Mon Sep 17 00:00:00 2001 From: pablocm83 Date: Tue, 9 Jan 2024 10:26:26 -0500 Subject: [PATCH 048/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Spanish=20translat?= =?UTF-8?q?ion=20for=20`docs/es/docs/learn/index.md`=20(#10885)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/es/docs/learn/index.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/es/docs/learn/index.md diff --git a/docs/es/docs/learn/index.md b/docs/es/docs/learn/index.md new file mode 100644 index 0000000000000..b8d26cf34fdab --- /dev/null +++ b/docs/es/docs/learn/index.md @@ -0,0 +1,5 @@ +# Aprender + +Aquí están las secciones introductorias y los tutoriales para aprender **FastAPI**. + +Podrías considerar esto como un **libro**, un **curso**, la forma **oficial** y recomendada de aprender FastAPI. 😎 From 23ad8275975bc3474d5f7ed448db4b6c3a83f432 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Tue, 9 Jan 2024 18:28:47 +0300 Subject: [PATCH 049/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Turkish=20translat?= =?UTF-8?q?ion=20for=20`docs/tr/docs/external-links.md`=20(#10549)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/external-links.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 docs/tr/docs/external-links.md diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md new file mode 100644 index 0000000000000..78eaf1729d80b --- /dev/null +++ b/docs/tr/docs/external-links.md @@ -0,0 +1,33 @@ +# Harici Bağlantılar ve Makaleler + +**FastAPI** sÃŒrekli bÃŒyÃŒyen harika bir topluluğa sahiptir. + +**FastAPI** ile alakalı birçok yazı, makale, araç ve proje bulunmaktadır. + +Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır. + +!!! tip "Ä°pucu" + Eğer **FastAPI** ile alakalı henÃŒz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir Pull Request oluşturabilirsiniz. + +{% for section_name, section_content in external_links.items() %} + +## {{ section_name }} + +{% for lang_name, lang_content in section_content.items() %} + +### {{ lang_name }} + +{% for item in lang_content %} + +* {{ item.title }} by {{ item.author }}. + +{% endfor %} +{% endfor %} +{% endfor %} + +## Projeler + +`fastapi` konulu en son GitHub projeleri: + +
+
From 0a3dc7d107aebee308896c6e1d49a71067db5660 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:28:54 +0000 Subject: [PATCH 050/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 734ab2d601599..db3a4d4b22457 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-fields.md`. PR [#10670](https://github.com/tiangolo/fastapi/pull/10670) by [@ArtemKhymenko](https://github.com/ArtemKhymenko). * 🌐 Add Hungarian translation for `/docs/hu/docs/index.md`. PR [#10812](https://github.com/tiangolo/fastapi/pull/10812) by [@takacs](https://github.com/takacs). * 🌐 Add Turkish translation for `docs/tr/docs/newsletter.md`. PR [#10550](https://github.com/tiangolo/fastapi/pull/10550) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Spanish translation for `docs/es/docs/help/index.md`. PR [#10907](https://github.com/tiangolo/fastapi/pull/10907) by [@pablocm83](https://github.com/pablocm83). From 0f4b6294bf17741cb2399fb2584c4da924168b95 Mon Sep 17 00:00:00 2001 From: Royc30ne Date: Tue, 9 Jan 2024 23:29:37 +0800 Subject: [PATCH 051/217] =?UTF-8?q?=F0=9F=8C=90=20Update=20SQLAlchemy=20in?= =?UTF-8?q?struction=20in=20Chinese=20translation=20`docs/zh/docs/tutorial?= =?UTF-8?q?/sql-databases.md`=20(#9712)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/zh/docs/tutorial/sql-databases.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index 8b09dc6771a8f..a936eb27b4d6a 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -78,9 +78,23 @@ ORM 具有圚代码和数据库衚“*关系型”䞭的**对象**之闎 现圚让我们看看每䞪文件/暡块的䜜甚。 +## 安装 SQLAlchemy + +先䞋蜜`SQLAlchemy`所需芁的䟝赖 + +
+ +```console +$ pip install sqlalchemy + +---> 100% +``` + +
+ ## 创建 SQLAlchemy 郚件 -让我们涉及到文件`sql_app/database.py`。 +让我们蜬到文件`sql_app/database.py`。 ### 富入 SQLAlchemy 郚件 From d6b4c6c65c8ee8922940b7def38bf60ed1dfeb53 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:31:14 +0000 Subject: [PATCH 052/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index db3a4d4b22457..c3e1606cb80cc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Spanish translation for `docs/es/docs/learn/index.md`. PR [#10885](https://github.com/tiangolo/fastapi/pull/10885) by [@pablocm83](https://github.com/pablocm83). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-fields.md`. PR [#10670](https://github.com/tiangolo/fastapi/pull/10670) by [@ArtemKhymenko](https://github.com/ArtemKhymenko). * 🌐 Add Hungarian translation for `/docs/hu/docs/index.md`. PR [#10812](https://github.com/tiangolo/fastapi/pull/10812) by [@takacs](https://github.com/takacs). * 🌐 Add Turkish translation for `docs/tr/docs/newsletter.md`. PR [#10550](https://github.com/tiangolo/fastapi/pull/10550) by [@hasansezertasan](https://github.com/hasansezertasan). From 3256c3ff073fa24bcb1a1a089a78869f9b7de77e Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov Date: Tue, 9 Jan 2024 18:31:45 +0300 Subject: [PATCH 053/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/learn/index.md`=20(#10539)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/ru/docs/learn/index.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/ru/docs/learn/index.md diff --git a/docs/ru/docs/learn/index.md b/docs/ru/docs/learn/index.md new file mode 100644 index 0000000000000..b2e4cabc751a6 --- /dev/null +++ b/docs/ru/docs/learn/index.md @@ -0,0 +1,5 @@ +# ОбучеМОе + +ЗЎесь преЎставлеМы ввПЎМые разЎелы О учебМые пПсПбОя Ўля ОзучеМОя **FastAPI**. + +Вы ЌПжете счОтать этП **кМОгПй**, **курсПЌ**, **ПфОцОальМыЌ** О рекПЌеМЎуеЌыЌ спПсПбПЌ ОзучеМОя FastAPI. 😎 From 01b106c29089208507611e48d98409912f18ad80 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:31:54 +0000 Subject: [PATCH 054/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c3e1606cb80cc..f410e96e964f5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Turkish translation for `docs/tr/docs/external-links.md`. PR [#10549](https://github.com/tiangolo/fastapi/pull/10549) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Spanish translation for `docs/es/docs/learn/index.md`. PR [#10885](https://github.com/tiangolo/fastapi/pull/10885) by [@pablocm83](https://github.com/pablocm83). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-fields.md`. PR [#10670](https://github.com/tiangolo/fastapi/pull/10670) by [@ArtemKhymenko](https://github.com/ArtemKhymenko). * 🌐 Add Hungarian translation for `/docs/hu/docs/index.md`. PR [#10812](https://github.com/tiangolo/fastapi/pull/10812) by [@takacs](https://github.com/takacs). From cb53749798f5ccbc4016cb37827cf46f4c75f0ce Mon Sep 17 00:00:00 2001 From: KAZAMA-DREAM <73453137+KAZAMA-DREAM@users.noreply.github.com> Date: Tue, 9 Jan 2024 23:33:25 +0800 Subject: [PATCH 055/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/learn/index.md`=20(#10479)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: KAZAMA --- docs/zh/docs/learn/index.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/zh/docs/learn/index.md diff --git a/docs/zh/docs/learn/index.md b/docs/zh/docs/learn/index.md new file mode 100644 index 0000000000000..38696f6feae03 --- /dev/null +++ b/docs/zh/docs/learn/index.md @@ -0,0 +1,5 @@ +# å­Šä¹  + +以䞋是孊习 **FastAPI** 的介绍郚分和教皋。 + +悚可以讀䞺这是䞀本 **乊**䞀闚 **诟皋**是 **官方** 䞔掚荐的孊习FastAPI的方法。😎 From b4ad143e3753b19628e6f7f339184f95219b223c Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:33:53 +0000 Subject: [PATCH 056/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f410e96e964f5..188e09a8f06c0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Update SQLAlchemy instruction in Chinese translation `docs/zh/docs/tutorial/sql-databases.md`. PR [#9712](https://github.com/tiangolo/fastapi/pull/9712) by [@Royc30ne](https://github.com/Royc30ne). * 🌐 Add Turkish translation for `docs/tr/docs/external-links.md`. PR [#10549](https://github.com/tiangolo/fastapi/pull/10549) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Spanish translation for `docs/es/docs/learn/index.md`. PR [#10885](https://github.com/tiangolo/fastapi/pull/10885) by [@pablocm83](https://github.com/pablocm83). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-fields.md`. PR [#10670](https://github.com/tiangolo/fastapi/pull/10670) by [@ArtemKhymenko](https://github.com/ArtemKhymenko). From 1021152f0a35a78954b36c7e6b534c4eeb9ff45b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hasan=20Sezer=20Ta=C5=9Fan?= <13135006+hasansezertasan@users.noreply.github.com> Date: Tue, 9 Jan 2024 18:35:44 +0300 Subject: [PATCH 057/217] =?UTF-8?q?=F0=9F=8C=90=20Update=20Turkish=20trans?= =?UTF-8?q?lation=20for=20`docs/tr/docs/index.md`=20(#10444)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/tr/docs/index.md | 281 +++++++++++++++++++++--------------------- 1 file changed, 141 insertions(+), 140 deletions(-) diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index e61f5b82cdfdf..ac8830880b35d 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -2,45 +2,47 @@ FastAPI

- FastAPI framework, yÃŒksek performanslı, öğrenmesi kolay, geliştirmesi hızlı, kullanıma sunulmaya hazır. + FastAPI framework, yÃŒksek performanslı, öğrenmesi oldukça kolay, kodlaması hızlı, kullanıma hazır

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

--- -**dokÃŒmantasyon**: https://fastapi.tiangolo.com +**DokÃŒmantasyon**: https://fastapi.tiangolo.com -**Kaynak kodu**: https://github.com/tiangolo/fastapi +**Kaynak Kod**: https://github.com/tiangolo/fastapi --- -FastAPI, Python 3.8+'nın standart type hintlerine dayanan modern ve hızlı (yÃŒksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'ÃŒ. +FastAPI, Python 3.8+'nin standart tip belirteçlerine dayalı, modern ve hızlı (yÃŒksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tÃŒr. -Ana özellikleri: +Temel özellikleri şunlardır: -* **Hızlı**: çok yÃŒksek performanslı, **NodeJS** ve **Go** ile eşdeğer seviyede performans sağlıyor, (Starlette ve Pydantic sayesinde.) [Python'un en hızlı frameworklerinden bir tanesi.](#performans). -* **Kodlaması hızlı**: Yeni özellikler geliştirmek neredeyse %200 - %300 daha hızlı. * -* **Daha az bug**: Geliştirici (insan) kaynaklı hatalar neredeyse %40 azaltıldı. * -* **Sezgileri gÌçlÃŒ**: Editor (otomatik-tamamlama) desteği harika. Otomatik tamamlama her yerde. Debuglamak ile daha az zaman harcayacaksınız. -* **Kolay**: Öğrenmesi ve kullanması kolay olacak şekilde. DokÃŒman okumak için harcayacağınız sÃŒre azaltıldı. -* **Kısa**: Kod tekrarını minimuma indirdik. Fonksiyon parametrelerinin tiplerini belirtmede farklı yollar sunarak karşılaşacağınız bug'ları azalttık. -* **GÌçlÃŒ**: Otomatik dokÃŒmantasyon ile beraber, kullanıma hazır kod yaz. +* **Hızlı**: Çok yÃŒksek performanslı, **NodeJS** ve **Go** ile eşit dÃŒzeyde (Starlette ve Pydantic sayesinde). [En hızlı Python framework'lerinden bir tanesidir](#performans). +* **Kodlaması Hızlı**: Geliştirme hızını yaklaşık %200 ile %300 aralığında arttırır. * +* **Daha az hata**: Ä°nsan (geliştirici) kaynaklı hataları yaklaşık %40 azaltır. * +* **Sezgisel**: Muhteşem bir editör desteği. Her yerde otomatik tamamlama. Hata ayıklama ile daha az zaman harcayacaksınız. +* **Kolay**: Öğrenmesi ve kullanması kolay olacak şekilde tasarlandı. DokÃŒman okuma ile daha az zaman harcayacaksınız. +* **Kısa**: Kod tekrarı minimize edildi. Her parametre tanımlamasında birden fazla özellik ve daha az hatayla karşılaşacaksınız. +* **GÌçlÃŒ**: Otomatik ve etkileşimli dokÃŒmantasyon ile birlikte, kullanıma hazır kod elde edebilirsiniz. +* **Standard öncelikli**: API'lar için açık standartlara dayalı (ve tamamen uyumlu); OpenAPI (eski adıyla Swagger) ve JSON Schema. -* **Standartlar belirli**: Tamamiyle API'ların açık standartlara bağlı ve (tam uyumlululuk içerisinde); OpenAPI (eski adıyla Swagger) ve JSON Schema. +* ilgili kanılar, dahili geliştirme ekibinin geliştirdikleri ÃŒrÃŒnlere yaptıkları testlere dayanmaktadır. -* Bahsi geçen rakamsal ifadeler tamamiyle, geliştirme takımının kendi sundukları ÃŒrÃŒnÃŒ geliştirirken yaptıkları testlere dayanmakta. - -## Sponsors +## Sponsorlar @@ -55,63 +57,61 @@ Ana özellikleri: -Other sponsors +Diğer Sponsorlar ## GörÌşler - -"_[...] BugÃŒnlerde **FastAPI**'ı çok fazla kullanıyorum [...] Aslına bakarsanız **Microsoft'taki Machine Learning servislerimizin** hepsinde kullanmayı dÌşÌnÃŒyorum. FastAPI ile geliştirdiğimiz servislerin bazıları çoktan **Windows**'un ana ÃŒrÃŒnlerine ve **Office** ÃŒrÃŒnlerine entegre edilmeye başlandı bile._" +"_[...] BugÃŒnlerde **FastAPI**'ı çok fazla kullanıyorum. [...] Aslında bunu ekibimin **Microsoft'taki Machine Learning servislerinin** tamamında kullanmayı planlıyorum. Bunlardan bazıları **Windows**'un ana ÃŒrÃŒnlerine ve **Office** ÃŒrÃŒnlerine entegre ediliyor._"
Kabir Khan - Microsoft (ref)
--- - -"_**FastAPI**'ı **tahminlerimiz**'i sorgulanabilir hale getirmek için **REST** mimarisı ile beraber server ÃŒzerinde kullanmaya başladık._" - +"_**FastAPI**'ı **tahminlerimiz**'i sorgulanabilir hale getirecek bir **REST** sunucu oluşturmak için benimsedik/kullanmaya başladık._"
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
--- - -"_**Netflix** **kriz yönetiminde** orkestrasyon yapabilmek için geliştirdiği yeni framework'ÃŒ **Dispatch**'in, açık kaynak versiyonunu paylaşmaktan gurur duyuyor. [**FastAPI** ile yapıldı.]_" +"_**Netflix**, **kriz yönetiminde** orkestrasyon yapabilmek için geliştirdiği yeni framework'ÃŒ **Dispatch**'in, açık kaynak sÃŒrÃŒmÃŒnÃŒ paylaşmaktan gurur duyuyor. [**FastAPI** ile yapıldı.]_"
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
--- - "_**FastAPI** için ayın ÃŒzerindeymişcesine heyecanlıyım. Çok eğlenceli!_" -
Brian Okken - Python Bytes podcast host (ref)
--- -"_DÃŒrÃŒst olmak gerekirse, geliştirdiğin şey bir çok açıdan çok sağlam ve parlak gözÃŒkÃŒyor. Açıkcası benim **Hug**'ı tasarlarken yapmaya çalıştığım şey buydu - bunu birisinin başardığını görmek gerçekten çok ilham verici._" +"_DÃŒrÃŒst olmak gerekirse, inşa ettiğiniz şey gerçekten sağlam ve profesyonel görÃŒnÃŒyor. Birçok açıdan **Hug**'ın olmasını istediğim şey tam da bu - böyle bir şeyi inşa eden birini görmek gerçekten ilham verici._" -
Timothy Crosley - Hug'ın Yaratıcısı (ref)
+
Timothy Crosley - Hug'ın Yaratıcısı (ref)
--- -"_Eğer REST API geliştirmek için **modern bir framework** öğrenme arayışında isen, **FastAPI**'a bir göz at [...] Hızlı, kullanımı ve öğrenmesi kolay. [...]_" +"_Eğer REST API geliştirmek için **modern bir framework** öğrenme arayışında isen, **FastAPI**'a bir göz at [...] Hızlı, kullanımı ve öğrenmesi kolay. [...]_" + +"_**API** servislerimizi **FastAPI**'a taşıdık [...] Sizin de beğeneceğinizi dÌşÌnÃŒyoruz. [...]_" -"_Biz **API** servislerimizi **FastAPI**'a geçirdik [...] Sizin de beğeneceğinizi dÌşÌnÃŒyoruz. [...]_" +
Ines Montani - Matthew Honnibal - Explosion AI kurucuları - spaCy yaratıcıları (ref) - (ref)
+--- +"_Python ile kullanıma hazır bir API oluşturmak isteyen herhangi biri için, **FastAPI**'ı şiddetle tavsiye ederim. **Harika tasarlanmış**, **kullanımı kolay** ve **yÃŒksek ölçeklenebilir**, API odaklı geliştirme stratejimizin **ana bileşeni** haline geldi ve Virtual TAC Engineer gibi birçok otomasyon ve servisi yönetiyor._" -
Ines Montani - Matthew Honnibal - Explosion AI kurucuları - spaCy yaratıcıları (ref) - (ref)
+
Deon Pillsbury - Cisco (ref)
--- -## **Typer**, komut satırı uygulamalarının FastAPI'ı +## Komut Satırı Uygulamalarının FastAPI'ı: **Typer** -Eğer API yerine komut satırı uygulaması geliştiriyor isen **Typer**'a bir göz at. +Eğer API yerine, terminalde kullanılmak ÃŒzere bir komut satırı uygulaması geliştiriyorsanız **Typer**'a göz atabilirsiniz. -**Typer** kısaca FastAPI'ın kÌçÌk kız kardeşi. Komut satırı uygulamalarının **FastAPI'ı** olması hedeflendi. ⌚ 🚀 +**Typer** kısaca FastAPI'ın kÌçÌk kardeşi. Ve hedefi komut satırı uygulamalarının **FastAPI'ı** olmak. ⌚ 🚀 ## Gereksinimler @@ -122,7 +122,7 @@ FastAPI iki devin omuzları ÃŒstÃŒnde duruyor: * Web tarafı için Starlette. * Data tarafı için Pydantic. -## YÃŒkleme +## Kurulum
@@ -134,7 +134,7 @@ $ pip install fastapi
-Uygulamanı kullanılabilir hale getirmek için Uvicorn ya da Hypercorn gibi bir ASGI serverına ihtiyacın olacak. +Uygulamamızı kullanılabilir hale getirmek için Uvicorn ya da Hypercorn gibi bir ASGI sunucusuna ihtiyacımız olacak.
@@ -148,9 +148,9 @@ $ pip install "uvicorn[standard]" ## Örnek -### Şimdi dene +### Kodu Oluşturalım -* `main.py` adında bir dosya oluştur : +* `main.py` adında bir dosya oluşturup içine şu kodu yapıştıralım: ```Python from typing import Union @@ -173,9 +173,9 @@ def read_item(item_id: int, q: Union[str, None] = None):
Ya da async def... -Eğer kodunda `async` / `await` var ise, `async def` kullan: +Eğer kodunuzda `async` / `await` varsa, `async def` kullanalım: -```Python hl_lines="9 14" +```Python hl_lines="9 14" from typing import Union from fastapi import FastAPI @@ -195,13 +195,13 @@ async def read_item(item_id: int, q: Union[str, None] = None): **Not**: -Eğer ne olduğunu bilmiyor isen _"Acelen mi var?"_ kısmını oku `async` ve `await`. +Eğer bu konu hakkında bilginiz yoksa `async` ve `await` dokÃŒmantasyonundaki _"Aceleniz mi var?"_ kısmını kontrol edebilirsiniz.
-### Çalıştır +### Kodu Çalıştıralım -Serverı aşağıdaki komut ile çalıştır: +Sunucuyu aşağıdaki komutla çalıştıralım:
@@ -218,56 +218,56 @@ INFO: Application startup complete.
-Çalıştırdığımız uvicorn main:app --reload hakkında... +uvicorn main:app --reload komutuyla ilgili... -`uvicorn main:app` şunları ifade ediyor: +`uvicorn main:app` komutunu şu şekilde açıklayabiliriz: * `main`: dosya olan `main.py` (yani Python "modÃŒlÃŒ"). -* `app`: ise `main.py` dosyasının içerisinde oluşturduğumuz `app = FastAPI()` 'a denk geliyor. -* `--reload`: ise kodda herhangi bir değişiklik yaptığımızda serverın yapılan değişiklerileri algılayıp, değişiklikleri siz herhangi bir şey yapmadan uygulamasını sağlıyor. +* `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. +* `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız.
-### DokÃŒmantasyonu kontrol et +### Şimdi de Kontrol Edelim -Browserını aç ve şu linke git http://127.0.0.1:8000/items/5?q=somequery. +Tarayıcımızda şu bağlantıyı açalım http://127.0.0.1:8000/items/5?q=somequery. -Bir JSON yanıtı göreceksin: +Aşağıdaki gibi bir JSON yanıtıyla karşılaşacağız: ```JSON {"item_id": 5, "q": "somequery"} ``` -Az önce oluşturduğun API: +Az önce oluşturduğumuz API: -* `/` ve `/items/{item_id}` adreslerine HTTP talebi alabilir hale geldi. -* Ä°ki _adresde_ `GET` operasyonlarını (HTTP _metodları_ olarakta bilinen) yapabilir hale geldi. -* `/items/{item_id}` _adresi_ ayrıca bir `item_id` _adres parametresine_ sahip ve bu bir `int` olmak zorunda. -* `/items/{item_id}` _adresi_ opsiyonel bir `str` _sorgu paramtersine_ sahip bu da `q`. +* `/` ve `/items/{item_id}` _yollarına_ HTTP isteği alabilir. +* Ä°ki _yolda_ `GET` operasyonlarını (HTTP _metodları_ olarak da bilinen) kabul ediyor. +* `/items/{item_id}` _yolu_ `item_id` adında bir _yol parametresine_ sahip ve bu parametre `int` değer almak zorundadır. +* `/items/{item_id}` _yolu_ `q` adında bir _yol parametresine_ sahip ve bu parametre opsiyonel olmakla birlikte, `str` değer almak zorundadır. -### Ä°nteraktif API dokÃŒmantasyonu +### Etkileşimli API DokÃŒmantasyonu -Şimdi http://127.0.0.1:8000/docs adresine git. +Şimdi http://127.0.0.1:8000/docs bağlantısını açalım. -Senin için otomatik oluşturulmuş(Swagger UI tarafından sağlanan) interaktif bir API dokÃŒmanı göreceksin: +Swagger UI tarafından sağlanan otomatik etkileşimli bir API dokÃŒmantasyonu göreceğiz: ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) -### Alternatif API dokÃŒmantasyonu +### Alternatif API DokÃŒmantasyonu -Şimdi http://127.0.0.1:8000/redoc adresine git. +Şimdi http://127.0.0.1:8000/redoc bağlantısını açalım. -Senin için alternatif olarak (ReDoc tarafından sağlanan) bir API dokÃŒmantasyonu daha göreceksin: +ReDoc tarafından sağlanan otomatik dokÃŒmantasyonu göreceğiz: ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) -## Örnek bir değişiklik +## Örneği GÃŒncelleyelim -Şimdi `main.py` dosyasını değiştirelim ve body ile `PUT` talebi alabilir hale getirelim. +Şimdi `main.py` dosyasını, `PUT` isteğiyle birlikte bir gövde alacak şekilde değiştirelim. -Şimdi Pydantic sayesinde, Python'un standart tiplerini kullanarak bir body tanımlayacağız. +Gövdeyi Pydantic sayesinde standart python tiplerini kullanarak tanımlayalım. -```Python hl_lines="4 9 10 11 12 25 26 27" +```Python hl_lines="4 9-12 25-27" from typing import Union from fastapi import FastAPI @@ -297,41 +297,41 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -Server otomatik olarak yeniden başlamalı (çÌnkÃŒ yukarıda `uvicorn`'u çalıştırırken `--reload` parametresini kullandık.). +Sunucu otomatik olarak yeniden başlamış olmalı (çÌnkÃŒ yukarıda `uvicorn` komutuyla birlikte `--reload` parametresini kullandık). -### Ä°nteraktif API dokÃŒmantasyonu'nda değiştirme yapmak +### Etkileşimli API DokÃŒmantasyonundaki Değişimi Görelim -Şimdi http://127.0.0.1:8000/docs bağlantısına tekrar git. +Şimdi http://127.0.0.1:8000/docs bağlantısına tekrar gidelim. -* Ä°nteraktif API dokÃŒmantasyonu, yeni body ile beraber çoktan yenilenmiş olması lazım: +* Etkileşimli API dokÃŒmantasyonu, yeni gövdede dahil olmak ÃŒzere otomatik olarak gÃŒncellenmiş olacak: ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) -* "Try it out"a tıkla, bu senin API parametleri ÃŒzerinde deneme yapabilmene izin veriyor: +* "Try it out" butonuna tıklayalım, bu işlem API parametleri ÃŒzerinde değişiklik yapmamıza ve doğrudan API ile etkileşime geçmemize imkan sağlayacak: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) -* Şimdi "Execute" butonuna tıkla, kullanıcı arayÃŒzÃŒ otomatik olarak API'ın ile bağlantı kurarak ona bu parametreleri gönderecek ve sonucu karşına getirecek. +* Şimdi "Execute" butonuna tıklayalım, kullanıcı arayÃŒzÃŒ API'ımız ile bağlantı kurup parametreleri gönderecek ve sonucu ekranımıza getirecek: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) -### Alternatif API dokÃŒmantasyonunda değiştirmek +### Alternatif API DokÃŒmantasyonundaki Değişimi Görelim -Şimdi ise http://127.0.0.1:8000/redoc adresine git. +Şimdi ise http://127.0.0.1:8000/redoc bağlantısına tekrar gidelim. -* Alternatif dokÃŒmantasyonda koddaki değişimler ile beraber kendini yeni query ve body ile gÃŒncelledi. +* Alternatif dokÃŒmantasyonda yaptığımız değişiklikler ile birlikte yeni sorgu parametresi ve gövde bilgisi ile gÃŒncelemiş olacak: ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) ### Özet -Özetleyecek olursak, URL, sorgu veya request body'deki parametrelerini fonksiyon parametresi olarak kullanıyorsun. Bu parametrelerin veri tiplerini bir kere belirtmen yeterli. +Özetlemek gerekirse, parametrelerin, gövdenin, vb. veri tiplerini fonksiyon parametreleri olarak **bir kere** tanımlıyoruz. -Type-hinting işlemini Python dilindeki standart veri tipleri ile yapabilirsin +Bu işlemi standart modern Python tipleriyle yapıyoruz. -Yeni bir syntax'e alışmana gerek yok, metodlar ve classlar zaten spesifik kÃŒtÃŒphanelere ait. +Yeni bir sözdizimi yapısını, bir kÃŒtÃŒphane özel metod veya sınıfları öğrenmeye gerek yoktur. -Sadece standart **Python 3.8+**. +Hepsi sadece **Python 3.8+** standartlarına dayalıdır. Örnek olarak, `int` tanımlamak için: @@ -339,64 +339,64 @@ Sadece standart **Python 3.8+**. item_id: int ``` -ya da daha kompleks `Item` tipi: +ya da daha kompleks herhangi bir python modelini tanımlayabiliriz, örneğin `Item` modeli için: ```Python item: Item ``` -...sadece kısa bir parametre tipi belirtmekle beraber, sahip olacakların: +...ve sadece kısa bir parametre tipi belirterek elde ettiklerimiz: -* Editör desteği dahil olmak ÃŒzere: +* Editör desteğiyle birlikte: * Otomatik tamamlama. - * Tip sorguları. -* Datanın tipe uyumunun sorgulanması: - * Eğer data geçersiz ise, otomatik olarak hataları ayıklar. - * Çok derin JSON objelerinde bile veri tipi sorgusu yapar. -* Gelen verinin dönÌşÌmÃŒnÃŒ aşağıdaki veri tiplerini kullanarak gerçekleştirebiliyor. + * Tip kontrolÃŒ. +* Veri Doğrulama: + * Veri geçerli değilse, otomatik olarak açıklayıcı hatalar gösterir. + * Çok derin JSON nesnelerinde bile doğrulama yapar. +* Gelen verinin dönÌşÌmÃŒnÃŒ aşağıdaki veri tiplerini kullanarak gerçekleştirir: * JSON. - * Path parametreleri. - * Query parametreleri. - * Cookies. + * Yol parametreleri. + * Sorgu parametreleri. + * Çerezler. * Headers. - * Forms. - * Files. -* Giden verinin dönÌşÌmÃŒnÃŒ aşağıdaki veri tiplerini kullanarak gerçekleştirebiliyor (JSON olarak): - * Python tiplerinin (`str`, `int`, `float`, `bool`, `list`, vs) çevirisi. - * `datetime` objesi. - * `UUID` objesi. + * Formlar. + * Dosyalar. +* Giden verinin dönÌşÌmÃŒnÃŒ aşağıdaki veri tiplerini kullanarak gerçekleştirir (JSON olarak): + * Python tiplerinin (`str`, `int`, `float`, `bool`, `list`, vb) dönÌşÌmÃŒ. + * `datetime` nesnesi. + * `UUID` nesnesi. * Veritabanı modelleri. - * ve daha fazlası... -* 2 alternatif kullanıcı arayÃŒzÃŒ dahil olmak ÃŒzere, otomatik interaktif API dokÃŒmanu: + * ve çok daha fazlası... +* 2 alternatif kullanıcı arayÃŒzÃŒ dahil olmak ÃŒzere, otomatik etkileşimli API dokÃŒmantasyonu sağlar: * Swagger UI. * ReDoc. --- -Az önceki kod örneğine geri dönelim, **FastAPI**'ın yapacaklarına bir bakış atalım: +Az önceki örneğe geri dönelim, **FastAPI**'ın yapacaklarına bir bakış atalım: -* `item_id`'nin `GET` ve `PUT` talepleri içinde olup olmadığının doğruluğunu kontol edecek. -* `item_id`'nin tipinin `int` olduğunu `GET` ve `PUT` talepleri içinde olup olmadığının doğruluğunu kontol edecek. - * Eğer `GET` ve `PUT` içinde yok ise ve `int` değil ise, sebebini belirten bir hata mesajı gösterecek -* Opsiyonel bir `q` parametresinin `GET` talebi için (`http://127.0.0.1:8000/items/foo?q=somequery` içinde) olup olmadığını kontrol edecek +* `item_id`'nin `GET` ve `PUT` istekleri için, yolda olup olmadığının kontol edecek. +* `item_id`'nin `GET` ve `PUT` istekleri için, tipinin `int` olduğunu doğrulayacak. + * Eğer değilse, sebebini belirten bir hata mesajı gösterecek. +* Opsiyonel bir `q` parametresinin `GET` isteği içinde (`http://127.0.0.1:8000/items/foo?q=somequery` gibi) olup olmadığını kontrol edecek * `q` parametresini `= None` ile oluşturduğumuz için, opsiyonel bir parametre olacak. - * Eğer `None` olmasa zorunlu bir parametre olacak idi (bu yÃŒzden body'de `PUT` parametresi var). -* `PUT` talebi için `/items/{item_id}`'nin body'sini, JSON olarak okuyor: - * `name` adında bir parametetre olup olmadığını ve var ise onun `str` olup olmadığını kontol ediyor. - * `price` adında bir parametetre olup olmadığını ve var ise onun `float` olup olmadığını kontol ediyor. - * `is_offer` adında bir parametetre olup olmadığını ve var ise onun `bool` olup olmadığını kontol ediyor. - * Bunların hepsini en derin JSON modellerinde bile yapacaktır. -* BÃŒtÃŒn veri tiplerini otomatik olarak JSON'a çeviriyor veya tam tersi. -* Her şeyi dokÃŒmanlayıp, çeşitli yerlerde: - * Ä°nteraktif dokÃŒmantasyon sistemleri. - * Otomatik alıcı kodu ÃŒretim sistemlerinde ve çeşitli dillerde. -* Ä°ki ayrı web arayÃŒzÃŒyle direkt olarak interaktif bir dokÃŒmantasyon sunuyor. + * Eğer `None` olmasa zorunlu bir parametre olacaktı (`PUT` metodunun gövdesinde olduğu gibi). +* `PUT` isteği için `/items/{item_id}`'nin gövdesini, JSON olarak doğrulayıp okuyacak: + * `name` adında zorunlu bir parametre olup olmadığını ve varsa tipinin `str` olup olmadığını kontol edecek. + * `price` adında zorunlu bir parametre olup olmadığını ve varsa tipinin `float` olup olmadığını kontol edecek. + * `is_offer` adında opsiyonel bir parametre olup olmadığını ve varsa tipinin `float` olup olmadığını kontol edecek. + * Bunların hepsi en derin JSON nesnelerinde bile çalışacak. +* Verilerin JSON'a ve JSON'ın python nesnesine dönÌşÌmÃŒ otomatik olarak yapılacak. +* Her şeyi OpenAPI ile uyumlu bir şekilde otomatik olarak dokÃŒmanlayacak ve bunlarda aşağıdaki gibi kullanılabilecek: + * Etkileşimli dokÃŒmantasyon sistemleri. + * Bir çok programlama dili için otomatik istemci kodu ÃŒretim sistemleri. +* Ä°ki ayrı etkileşimli dokÃŒmantasyon arayÃŒzÃŒnÃŒ doğrudan sağlayacak. --- -HenÃŒz yÃŒzeysel bir bakış attık, fakat sen çoktan çalışma mantığını anladın. +Daha yeni başladık ama çalışma mantığını çoktan anlamış oldunuz. -Şimdi aşağıdaki satırı değiştirmeyi dene: +Şimdi aşağıdaki satırı değiştirmeyi deneyin: ```Python return {"item_name": item.name, "item_id": item_id} @@ -414,22 +414,22 @@ HenÃŒz yÃŒzeysel bir bakış attık, fakat sen çoktan çalışma mantığını ... "item_price": item.price ... ``` -...şimdi editör desteğinin nasıl veri tiplerini bildiğini ve otomatik tamamladığını gör: +...ve editörÃŒnÃŒn veri tiplerini bildiğini ve otomatik tamamladığını göreceksiniz: ![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) -Daha fazla örnek ve özellik için Tutorial - User Guide sayfasını git. +Daha fazal özellik içeren, daha eksiksiz bir örnek için Öğretici - Kullanıcı Rehberi sayfasını ziyaret edebilirsin. -**Spoiler**: Öğretici - Kullanıcı rehberi şunları içeriyor: +**Spoiler**: Öğretici - Kullanıcı rehberi şunları içerir: -* **Parameterlerini** nasıl **headers**, **cookies**, **form fields** ve **files** olarak deklare edebileceğini. -* `maximum_length` ya da `regex` gibi şeylerle nasıl **doğrulama** yapabileceğini. -* Çok gÌçlÃŒ ve kullanımı kolay **Zorunluluk Entegrasyonu** oluşturmayı. -* GÃŒvenlik ve kimlik doğrulama, **JWT tokenleri**'yle beraber **OAuth2** desteği, ve **HTTP Basic** doğrulaması. -* Ä°leri seviye fakat ona göre oldukça basit olan **derince oluşturulmuş JSON modelleri** (Pydantic sayesinde). +* **Parameterlerin**, **headers**, **çerezler**, **form alanları** ve **dosyalar** olarak tanımlanması. +* `maximum_length` ya da `regex` gibi **doğrulama kısıtlamalarının** nasıl yapılabileceği. +* Çok gÌçlÃŒ ve kullanımı kolay **Bağımlılık Enjeksiyonu** sistemi oluşturmayı. +* GÃŒvenlik ve kimlik doğrulama, **JWT tokenleri** ile **OAuth2** desteği, ve **HTTP Basic** doğrulaması. +* Ä°leri seviye fakat bir o kadarda basit olan **çok derin JSON modelleri** (Pydantic sayesinde). +* **GraphQL** entegrasyonu: Strawberry ve diğer kÃŒtÃŒphaneleri kullanarak. * Diğer ekstra özellikler (Starlette sayesinde): - * **WebSockets** - * **GraphQL** + * **WebSocketler** * HTTPX ve `pytest` sayesinde aşırı kolay testler. * **CORS** * **Cookie Sessions** @@ -437,33 +437,34 @@ Daha fazla örnek ve özellik için Python'un en hızlı frameworklerinden birisi , sadece Starlette ve Uvicorn'dan daha yavaş ki FastAPI bunların ÃŒzerine kurulu. +Bağımsız TechEmpower kıyaslamaları gösteriyor ki, Uvicorn ile çalıştırılan **FastAPI** uygulamaları en hızlı Python framework'lerinden birisi, sadece Starlette ve Uvicorn'dan yavaş, ki FastAPI bunların ÃŒzerine kurulu bir kÃŒtÃŒphanedir. -Daha fazla bilgi için, bu bölÃŒme bir göz at Benchmarks. +Daha fazla bilgi için, bu bölÃŒme bir göz at Kıyaslamalar. -## Opsiyonel gereksinimler +## Opsiyonel Gereksinimler Pydantic tarafında kullanılan: * email_validator - email doğrulaması için. +* pydantic-settings - ayar yönetimi için. +* pydantic-extra-types - Pydantic ile birlikte kullanılabilecek ek tipler için. Starlette tarafında kullanılan: -* httpx - Eğer `TestClient` kullanmak istiyorsan gerekli. -* jinja2 - Eğer kendine ait template konfigÃŒrasyonu oluşturmak istiyorsan gerekli -* python-multipart - Form kullanmak istiyorsan gerekli ("dönÌşÌmÃŒ"). +* httpx - Eğer `TestClient` yapısını kullanacaksanız gereklidir. +* jinja2 - Eğer varsayılan template konfigÃŒrasyonunu kullanacaksanız gereklidir. +* python-multipart - Eğer `request.form()` ile form dönÌşÌmÃŒ desteğini kullanacaksanız gereklidir. * itsdangerous - `SessionMiddleware` desteği için gerekli. * pyyaml - `SchemaGenerator` desteği için gerekli (Muhtemelen FastAPI kullanırken ihtiyacınız olmaz). -* graphene - `GraphQLApp` desteği için gerekli. -* ujson - `UJSONResponse` kullanmak istiyorsan gerekli. +* ujson - `UJSONResponse` kullanacaksanız gerekli. Hem FastAPI hem de Starlette tarafından kullanılan: -* uvicorn - oluşturduğumuz uygulamayı bir web sunucusuna servis etmek için gerekli -* orjson - `ORJSONResponse` kullanmak istiyor isen gerekli. +* uvicorn - oluşturduğumuz uygulamayı servis edecek web sunucusu görevini ÃŒstlenir. +* orjson - `ORJSONResponse` kullanacaksanız gereklidir. Bunların hepsini `pip install fastapi[all]` ile yÃŒkleyebilirsin. ## Lisans -Bu proje, MIT lisansı şartlarına göre lisanslanmıştır. +Bu proje, MIT lisansı şartları altında lisanslanmıştır. From c471c9311371d12b3dd2ed80a5d078e8991a4c19 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:36:04 +0000 Subject: [PATCH 058/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 188e09a8f06c0..8706abf0f6088 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/learn/index.md`. PR [#10539](https://github.com/tiangolo/fastapi/pull/10539) by [@AlertRED](https://github.com/AlertRED). * 🌐 Update SQLAlchemy instruction in Chinese translation `docs/zh/docs/tutorial/sql-databases.md`. PR [#9712](https://github.com/tiangolo/fastapi/pull/9712) by [@Royc30ne](https://github.com/Royc30ne). * 🌐 Add Turkish translation for `docs/tr/docs/external-links.md`. PR [#10549](https://github.com/tiangolo/fastapi/pull/10549) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Spanish translation for `docs/es/docs/learn/index.md`. PR [#10885](https://github.com/tiangolo/fastapi/pull/10885) by [@pablocm83](https://github.com/pablocm83). From 031000fc6e242fb4582fe2753f6a62eea2890ef3 Mon Sep 17 00:00:00 2001 From: fhabers21 <58401847+fhabers21@users.noreply.github.com> Date: Tue, 9 Jan 2024 16:36:32 +0100 Subject: [PATCH 059/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/first-steps.md`=20(#9530)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez Co-authored-by: Georg Wicke-Arndt --- docs/de/docs/tutorial/first-steps.md | 333 +++++++++++++++++++++++++++ 1 file changed, 333 insertions(+) create mode 100644 docs/de/docs/tutorial/first-steps.md diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md new file mode 100644 index 0000000000000..5997f138f0ac3 --- /dev/null +++ b/docs/de/docs/tutorial/first-steps.md @@ -0,0 +1,333 @@ +# Erste Schritte + +Die einfachste FastAPI-Datei könnte wie folgt aussehen: + +```Python +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Kopieren Sie dies in eine Datei `main.py`. + +Starten Sie den Live-Server: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +!!! note "Hinweis" + Der Befehl `uvicorn main:app` bezieht sich auf: + + * `main`: die Datei `main.py` (das sogenannte Python-„Modul“). + * `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. + * `--reload`: lÀsst den Server nach CodeÀnderungen neu starten. Verwenden Sie das nur wÀhrend der Entwicklung. + +In der Konsolenausgabe sollte es eine Zeile geben, die ungefÀhr so aussieht: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Diese Zeile zeigt die URL, unter der Ihre Anwendung auf Ihrem lokalen Computer bereitgestellt wird. + +### Testen Sie es + +Öffnen Sie Ihren Browser unter http://127.0.0.1:8000. + +Sie werden folgende JSON-Antwort sehen: + +```JSON +{"message": "Hello World"} +``` + +### Interaktive API-Dokumentation + +Gehen Sie als NÀchstes auf http://127.0.0.1:8000/docs . + +Sie werden die automatisch erzeugte, interaktive API-Dokumentation sehen (bereitgestellt durch Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternative API-Dokumentation + +Gehen Sie nun auf http://127.0.0.1:8000/redoc. + +Dort sehen Sie die alternative, automatische Dokumentation (bereitgestellt durch ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI** generiert ein „Schema“ mit all Ihren APIs unter Verwendung des **OpenAPI**-Standards zur Definition von APIs. + +#### „Schema“ + +Ein „Schema“ ist eine Definition oder Beschreibung von etwas. Nicht der eigentliche Code, der es implementiert, sondern lediglich eine abstrakte Beschreibung. + +#### API-„Schema“ + +In diesem Fall ist OpenAPI eine Spezifikation, die vorschreibt, wie ein Schema fÃŒr Ihre API zu definieren ist. + +Diese Schemadefinition enthÀlt Ihre API-Pfade, die möglichen Parameter, welche diese entgegennehmen, usw. + +#### Daten-„Schema“ + +Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z.B. einen JSON-Inhalt. + +In diesem Fall sind die JSON-Attribute und deren Datentypen, usw. gemeint. + +#### OpenAPI und JSON Schema + +OpenAPI definiert ein API-Schema fÃŒr Ihre API. Dieses Schema enthÀlt Definitionen (oder „Schemas“) der Daten, die von Ihrer API unter Verwendung von **JSON Schema**, dem Standard fÃŒr JSON-Datenschemata, gesendet und empfangen werden. + +#### ÜberprÃŒfen Sie die `openapi.json` + +Falls Sie wissen möchten, wie das rohe OpenAPI-Schema aussieht: FastAPI generiert automatisch ein JSON (Schema) mit den Beschreibungen Ihrer gesamten API. + +Sie können es direkt einsehen unter: http://127.0.0.1:8000/openapi.json. + +Es wird ein JSON angezeigt, welches ungefÀhr so aussieht: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### WofÃŒr OpenAPI gedacht ist + +Das OpenAPI-Schema ist die Grundlage fÃŒr die beiden enthaltenen interaktiven Dokumentationssysteme. + +Es gibt dutzende Alternativen, die alle auf OpenAPI basieren. Sie können jede dieser Alternativen problemlos zu Ihrer mit **FastAPI** erstellten Anwendung hinzufÃŒgen. + +Ebenfalls können Sie es verwenden, um automatisch Code fÃŒr Clients zu generieren, die mit Ihrer API kommunizieren. Zum Beispiel fÃŒr Frontend-, Mobile- oder IoT-Anwendungen. + +## RÃŒckblick, Schritt fÃŒr Schritt + +### Schritt 1: Importieren von `FastAPI` + +```Python hl_lines="1" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +`FastAPI` ist eine Python-Klasse, die die gesamte FunktionalitÀt fÃŒr Ihre API bereitstellt. + +!!! note "Technische Details" + `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. + + Sie können alle Starlette-FunktionalitÀten auch mit `FastAPI` nutzen. + +### Schritt 2: Erzeugen einer `FastAPI`-„Instanz“ + +```Python hl_lines="3" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +In diesem Beispiel ist die Variable `app` eine „Instanz“ der Klasse `FastAPI`. + +Dies wird der Hauptinteraktionspunkt fÃŒr die Erstellung all Ihrer APIs sein. + +Die Variable `app` ist dieselbe, auf die sich der Befehl `uvicorn` bezieht: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Wenn Sie Ihre Anwendung wie folgt erstellen: + +```Python hl_lines="3" +{!../../../docs_src/first_steps/tutorial002.py!} +``` + +Und in eine Datei `main.py` einfÃŒgen, dann wÃŒrden Sie `uvicorn` wie folgt aufrufen: + +
+ +```console +$ uvicorn main:my_awesome_api --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Schritt 3: Erstellen einer *Pfadoperation* + +#### Pfad + +„Pfad“ bezieht sich hier auf den letzten Teil der URL, beginnend mit dem ersten `/`. + +In einer URL wie: + +``` +https://example.com/items/foo +``` + +... wÀre der Pfad folglich: + +``` +/items/foo +``` + +!!! info + Ein „Pfad“ wird hÀufig auch als „Endpunkt“ oder „Route“ bezeichnet. + +Bei der Erstellung einer API ist der „Pfad“ die wichtigste Möglichkeit zur Trennung von „Anliegen“ und „Ressourcen“. + +#### Operation + +„Operation“ bezieht sich hier auf eine der HTTP-„Methoden“. + +Eine von diesen: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +... und die etwas Exotischeren: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +Im HTTP-Protokoll können Sie mit jedem Pfad ÃŒber eine (oder mehrere) dieser „Methoden“ kommunizieren. + +--- + +Bei der Erstellung von APIs verwenden Sie normalerweise diese spezifischen HTTP-Methoden, um eine bestimmte Aktion durchzufÃŒhren. + +Normalerweise verwenden Sie: + +* `POST`: um Daten zu erzeugen (create). +* `GET`: um Daten zu lesen (read). +* `PUT`: um Daten zu aktualisieren (update). +* `DELETE`: um Daten zu löschen (delete). + +In OpenAPI wird folglich jede dieser HTTP-Methoden als „Operation“ bezeichnet. + +Wir werden sie auch „**Operationen**“ nennen. + +#### Definieren eines *Pfadoperation-Dekorators* + +```Python hl_lines="6" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter fÃŒr die Bearbeitung von Anfragen zustÀndig ist, die an: + + * den Pfad `/` + * unter der Verwendung der get-Operation gehen + +!!! info "`@decorator` Information" + Diese `@something`-Syntax wird in Python „Dekorator“ genannt. + + Sie platzieren ihn ÃŒber einer Funktion. Wie ein hÃŒbscher, dekorativer Hut (daher kommt wohl der Begriff). + + Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit. + + In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhÀngt. + + Dies ist der „**Pfadoperation-Dekorator**“. + +Sie können auch die anderen Operationen verwenden: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +Oder die exotischeren: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +!!! tip "Tipp" + Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. + + **FastAPI** erzwingt keine bestimmte Bedeutung. + + Die hier aufgefÃŒhrten Informationen dienen als Leitfaden und sind nicht verbindlich. + + Wenn Sie beispielsweise GraphQL verwenden, fÃŒhren Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch. + +### Schritt 4: Definieren der **Pfadoperation-Funktion** + +Das ist unsere „**Pfadoperation-Funktion**“: + +* **Pfad**: ist `/`. +* **Operation**: ist `get`. +* **Funktion**: ist die Funktion direkt unter dem „Dekorator“ (unter `@app.get("/")`). + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Dies ist eine Python-Funktion. + +Sie wird von **FastAPI** immer dann aufgerufen, wenn sie eine Anfrage an die URL "`/`" mittels einer `GET`-Operation erhÀlt. + +In diesem Fall handelt es sich um eine `async`-Funktion. + +--- + +Sie könnten sie auch als normale Funktion anstelle von `async def` definieren: + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial003.py!} +``` + +!!! note "Hinweis" + Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}. + +### Schritt 5: den Inhalt zurÃŒckgeben + +```Python hl_lines="8" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurÃŒckgeben. + +Sie können auch Pydantic-Modelle zurÃŒckgeben (dazu spÀter mehr). + +Es gibt viele andere Objekte und Modelle, die automatisch zu JSON konvertiert werden (einschließlich ORMs usw.). Versuchen Sie, Ihre Lieblingsobjekte zu verwenden. Es ist sehr wahrscheinlich, dass sie bereits unterstÃŒtzt werden. + +## Zusammenfassung + +* Importieren Sie `FastAPI`. +* Erstellen Sie eine `app` Instanz. +* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z.B. `@app.get("/")`). +* Schreiben Sie eine **Pfadoperation-Funktion** (wie z.B. oben `def root(): ...`). +* Starten Sie den Entwicklungsserver (z.B. `uvicorn main:app --reload`). From 271b4f31440d29af4264c68c0376c44b790cc0a5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:37:13 +0000 Subject: [PATCH 060/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8706abf0f6088..e200823d05e1a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/learn/index.md`. PR [#10479](https://github.com/tiangolo/fastapi/pull/10479) by [@KAZAMA-DREAM](https://github.com/KAZAMA-DREAM). * 🌐 Add Russian translation for `docs/ru/docs/learn/index.md`. PR [#10539](https://github.com/tiangolo/fastapi/pull/10539) by [@AlertRED](https://github.com/AlertRED). * 🌐 Update SQLAlchemy instruction in Chinese translation `docs/zh/docs/tutorial/sql-databases.md`. PR [#9712](https://github.com/tiangolo/fastapi/pull/9712) by [@Royc30ne](https://github.com/Royc30ne). * 🌐 Add Turkish translation for `docs/tr/docs/external-links.md`. PR [#10549](https://github.com/tiangolo/fastapi/pull/10549) by [@hasansezertasan](https://github.com/hasansezertasan). From 152171e455cbd7f93214e014c441da39a26ae7ed Mon Sep 17 00:00:00 2001 From: xzmeng Date: Tue, 9 Jan 2024 23:37:29 +0800 Subject: [PATCH 061/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/deployment/index.md`=20(#10275)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: 后定焕 <108172295+wdh99@users.noreply.github.com> --- docs/zh/docs/deployment/index.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 docs/zh/docs/deployment/index.md diff --git a/docs/zh/docs/deployment/index.md b/docs/zh/docs/deployment/index.md new file mode 100644 index 0000000000000..1ec0c5c5b5976 --- /dev/null +++ b/docs/zh/docs/deployment/index.md @@ -0,0 +1,21 @@ +# 郚眲 + +郚眲 **FastAPI** 应甚皋序盞对容易。 + +## 郚眲是什么意思 + +**郚眲**应甚皋序意味着执行必芁的步骀以䜿其**可䟛甚户䜿甚**。 + +对于**Web API**来诎通垞涉及将䞊䌠到**云服务噚**䞭搭配䞀䞪性胜和皳定性郜䞍错的**服务噚皋序**以䟿䜠的**甚户**可以高效地**访问**䜠的应甚皋序而䞍䌚出现䞭断或其他问题。 + +这䞎**匀发**阶段圢成鲜明对比圚**匀发**阶段䜠䞍断曎改代码、砎坏代码、修倍代码, 来回停止和重启服务噚等。 + +## 郚眲策略 + +根据䜠的䜿甚场景和䜿甚的工具有倚种方法可以实现歀目的。 + +䜠可以䜿甚䞀些工具自行**郚眲服务噚**䜠也可以䜿甚胜䞺䜠完成郚分工䜜的**云服务**或其他可胜的选项。 + +我将向䜠展瀺圚郚眲 **FastAPI** 应甚皋序时䜠可胜应该记䜏的䞀些䞻芁抂念尜管其䞭倧郚分适甚于任䜕其他类型的 Web 应甚皋序。 + +圚接䞋来的郚分䞭䜠将看到曎倚需芁记䜏的细节以及䞀些技巧。 ✹ From 5eab5dbed659d4c97bb468bf29e99be57e122d05 Mon Sep 17 00:00:00 2001 From: xzmeng Date: Tue, 9 Jan 2024 23:38:25 +0800 Subject: [PATCH 062/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/deployment/https.md`=20(#10277)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Big Yellow Dog Co-authored-by: Lion <121552599+socket-socket@users.noreply.github.com> --- docs/zh/docs/deployment/https.md | 192 +++++++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 docs/zh/docs/deployment/https.md diff --git a/docs/zh/docs/deployment/https.md b/docs/zh/docs/deployment/https.md new file mode 100644 index 0000000000000..cf01a4585bec2 --- /dev/null +++ b/docs/zh/docs/deployment/https.md @@ -0,0 +1,192 @@ +# 关于 HTTPS + +人们埈容易讀䞺 HTTPS 仅仅是“启甚”或“未启甚”的䞜西。 + +䜆实际情况比这倍杂埗倚。 + +!!!提瀺 + 劂果䜠埈赶时闎或䞍圚乎请继续阅读䞋䞀郚分䞋䞀郚分䌚提䟛䞀䞪step-by-step的教皋告诉䜠怎么䜿甚䞍同技术来把䞀切郜配眮奜。 + +芁从甚户的视角**了解 HTTPS 的基础知识**请查看 https://howhttps.works/。 + +现圚从**匀发人员的视角**圚了解 HTTPS 时需芁记䜏以䞋几点 + +* 芁䜿甚 HTTPS**服务噚**需芁拥有由**第䞉方**生成的**"证乊(certificate)"**。 + * 这些证乊实际䞊是从第䞉方**获取**的而䞍是“生成”的。 +* 证乊有**生呜呚期**。 + * 它们䌚**过期**。 + * 然后它们需芁**曎新****再次从第䞉方获取**。 +* 连接的加密发生圚 **TCP 层**。 + * 这是 HTTP 协议**䞋面的䞀层**。 + * 因歀**证乊和加密**倄理是圚 **HTTP之前**完成的。 +* **TCP 䞍知道域名**。 仅仅知道 IP 地址。 + * 有关所请求的 **特定域名** 的信息䜍于 **HTTP 数据**䞭。 +* **HTTPS 证乊**“证明”**某䞪域名**䜆协议和加密发生圚 TCP 层圚知道正圚倄理哪䞪域名**之前**。 +* **默讀情况䞋**这意味着䜠**每䞪 IP 地址只胜拥有䞀䞪 HTTPS 证乊**。 + * 无论䜠的服务噚有倚倧或者服务噚䞊的每䞪应甚皋序有倚小。 + * 䞍过对歀有䞀䞪**解决方案**。 +* **TLS** 协议圚 HTTP 之䞋的TCP 层倄理加密的协议有䞀䞪**扩展**称䞺 **SNI**。 + * SNI 扩展允讞䞀台服务噚具有 **单䞪 IP 地址**拥有 **倚䞪 HTTPS 证乊** 并提䟛 **倚䞪 HTTPS 域名/应甚皋序**。 + * 䞺歀服务噚䞊䌚有**单独**的䞀䞪组件皋序䟊听**公共 IP 地址**这䞪组件必须拥有服务噚䞭的**所有 HTTPS 证乊**。 +* **获埗安党连接后**通信协议**仍然是HTTP**。 + * 内容是 **加密过的**即䜿它们是通过 **HTTP 协议** 发送的。 + +通垞的做法是圚服务噚䞊运行**䞀䞪皋序/HTTP 服务噚**并**管理所有 HTTPS 郚分**接收**加密的 HTTPS 请求** 将 **解密的 HTTP 请求** 发送到圚同䞀服务噚䞭运行的实际 HTTP 应甚皋序圚本䟋䞭䞺 **FastAPI** 应甚皋序从应甚皋序䞭获取 **HTTP 响应** 䜿甚适圓的 **HTTPS 证乊**对其进行加密并䜿甚 **HTTPS** 将其发送回客户端。 歀服务噚通垞被称䞺 **TLS 终止代理(TLS Termination Proxy)**。 + +䜠可以甚䜜 TLS 终止代理的䞀些选项包括 + +* Traefik也可以倄理证乊曎新 +* Caddy也可以倄理证乊曎新 +* Nginx +* HAProxy + +## Let's Encrypt + +圚 Let's Encrypt 之前这些 **HTTPS 证乊** 由受信任的第䞉方出售。 + +过去获埗这些证乊的过皋非垞繁琐需芁倧量的文乊工䜜而䞔证乊非垞昂莵。 + +䜆随后 **Let's Encrypt** 创建了。 + +它是 Linux 基金䌚的䞀䞪项目。 它以自劚方匏免莹提䟛 **HTTPS 证乊**。 这些证乊可以䜿甚所有笊合标准的安党加密并䞔有效期埈短倧纊 3 䞪月因歀**安党性实际䞊曎奜**因䞺它们的生呜呚期猩短了。 + +域可以被安党地验证并自劚生成证乊。 这还允讞自劚曎新这些证乊。 + +我们的想法是自劚获取和曎新这些证乊以䟿䜠可以氞远免莹拥有**安党的 HTTPS**。 + +## 面向匀发人员的 HTTPS + +这里有䞀䞪 HTTPS API 看起来是什么样的瀺䟋我们䌚分步诎明并䞔䞻芁关泚对匀发人员重芁的郚分。 + + +### 域名 + +第䞀步我们芁先**获取**䞀些**域名(Domain Name)**。 然后可以圚 DNS 服务噚可胜是䜠的同䞀家云服务商提䟛的䞭配眮它。 + +䜠可胜拥有䞀䞪云服务噚虚拟机或类䌌的䞜西并䞔它䌚有䞀䞪固定 **公共IP地址**。 + +圚 DNS 服务噚䞭䜠可以配眮䞀条记圕“A 记圕”以将 **䜠的域名** 指向䜠服务噚的公共 **IP 地址**。 + +这䞪操䜜䞀般只需芁圚最匀始执行䞀次。 + +!!! tip + 域名这郚分发生圚 HTTPS 之前由于这䞀切郜䟝赖于域名和 IP 地址所以先圚这里提䞀䞋。 + +### DNS + +现圚让我们关泚真正的 HTTPS 郚分。 + +銖先浏览噚将通过 **DNS 服务噚** 查询**域名的IP** 是什么圚本䟋䞭䞺 `someapp.example.com`。 + +DNS 服务噚䌚告诉浏览噚䜿甚某䞪特定的 **IP 地址**。 这将是䜠圚 DNS 服务噚䞭䞺䜠的服务噚配眮的公共 IP 地址。 + + + +### TLS 握手匀始 + +然后浏览噚将圚**端口 443**HTTPS 端口䞊䞎该 IP 地址进行通信。 + +通信的第䞀郚分只是建立客户端和服务噚之闎的连接并决定它们将䜿甚的加密密钥等。 + + + +客户端和服务噚之闎建立 TLS 连接的过皋称䞺 **TLS 握手**。 + +### 垊有 SNI 扩展的 TLS + +**服务噚䞭只有䞀䞪进皋**可以䟊听特定 **IP 地址**的特定 **端口**。 可胜有其他进皋圚同䞀 IP 地址的其他端口䞊䟊听䜆每䞪 IP 地址和端口组合只有䞀䞪进皋。 + +TLS (HTTPS) 默讀䜿甚端口`443`。 这就是我们需芁的端口。 + +由于只有䞀䞪进皋可以监听歀端口因歀监听端口的进皋将是 **TLS 终止代理**。 + +TLS 终止代理可以访问䞀䞪或倚䞪 **TLS 证乊**HTTPS 证乊。 + +䜿甚䞊面讚论的 **SNI 扩展**TLS 终止代理将检查应该甚于歀连接的可甚 TLS (HTTPS) 证乊并䜿甚䞎客户端期望的域名盞匹配的证乊。 + +圚这种情况䞋它将䜿甚`someapp.example.com`的证乊。 + + + +客户端已经**ä¿¡ä»»**生成该 TLS 证乊的实䜓圚本䟋䞭䞺 Let's Encrypt䜆我们皍后䌚看到因歀它可以**验证**该证乊是吊有效。 + +然后通过䜿甚证乊客户端和 TLS 终止代理 **决定劂䜕加密** **TCP 通信** 的其䜙郚分。 这就完成了 **TLS 握手** 郚分。 + +歀后客户端和服务噚就拥有了**加密的 TCP 连接**这就是 TLS 提䟛的功胜。 然后他们可以䜿甚该连接来启劚实际的 **HTTP 通信**。 + +这就是 **HTTPS**它只是 **安党 TLS 连接** 内的普通 **HTTP**而䞍是纯粹的未加密的TCP 连接。 + +!!! tip + 请泚意通信加密发生圚 **TCP 层**而䞍是 HTTP 层。 + +### HTTPS 请求 + +现圚客户端和服务噚特别是浏览噚和 TLS 终止代理具有 **加密的 TCP 连接**它们可以匀始 **HTTP 通信**。 + +接䞋来客户端发送䞀䞪 **HTTPS 请求**。 这其实只是䞀䞪通过 TLS 加密连接的 HTTP 请求。 + + + +### 解密请求 + +TLS 终止代理将䜿甚协商奜的加密算法**解密请求**并将**解密的HTTP 请求**䌠蟓到运行应甚皋序的进皋䟋劂运行 FastAPI 应甚的 Uvicorn 进皋。 + + + +### HTTP 响应 + +应甚皋序将倄理请求并向 TLS 终止代理发送**未加密HTTP 响应**。 + + + +### HTTPS 响应 + +然后TLS 终止代理将䜿甚之前协商的加密算法以`someapp.example.com`的证乊匀倎对响应进行加密并将其发送回浏览噚。 + +接䞋来浏览噚将验证响应是吊有效和是吊䜿甚了正确的加密密钥等。然后它䌚**解密响应**并倄理它。 + + + +客户端浏览噚将知道响应来自正确的服务噚因䞺它䜿甚了他们之前䜿甚 **HTTPS 证乊** 协商出的加密算法。 + +### 倚䞪应甚皋序 + +圚同䞀台或倚台服务噚䞭可胜存圚**倚䞪应甚皋序**䟋劂其他 API 皋序或数据库。 + +只有䞀䞪进皋可以倄理特定的 IP 和端口圚我们的瀺䟋䞭䞺 TLS 终止代理䜆其他应甚皋序/进皋也可以圚服务噚䞊运行只芁它们䞍尝试䜿甚盞同的 **公共 IP 和端口的组合**。 + + + +这样TLS 终止代理就可以䞺倚䞪应甚皋序倄理**倚䞪域名**的 HTTPS 和证乊然后圚每种情况䞋将请求䌠蟓到正确的应甚皋序。 + +### 证乊曎新 + +圚未来的某䞪时候每䞪证乊郜䌚**过期**倧纊圚获埗证乊后 3 䞪月。 + +然后䌚有及䞀䞪皋序圚某些情况䞋是及䞀䞪皋序圚某些情况䞋可胜是同䞀䞪 TLS 终止代理䞎 Let's Encrypt 通信并曎新证乊。 + + + +**TLS 证乊** **䞎域名盞关联**而䞍是䞎 IP 地址盞关联。 + +因歀芁曎新证乊曎新皋序需芁向权嚁机构Let's Encrypt**证明**它确实**“拥有”并控制该域名**。 + +有倚种方法可以做到这䞀点。 䞀些流行的方匏是 + +* **修改䞀些DNS记圕**。 + * 䞺歀续订皋序需芁支持 DNS 提䟛商的 API因歀芁看䜠䜿甚的 DNS 提䟛商是吊提䟛这䞀功胜。 +* **圚䞎域名关联的公共 IP 地址䞊䜜䞺服务噚运行**至少圚证乊获取过皋䞭。 + * 正劂我们䞊面所诎只有䞀䞪进皋可以监听特定的 IP 和端口。 + * 这就是圓同䞀䞪 TLS 终止代理还莟莣证乊续订过皋时它非垞有甚的原因之䞀。 + * 吊则䜠可胜需芁暂时停止 TLS 终止代理启劚续订皋序以获取证乊然后䜿甚 TLS 终止代理配眮它们然后重新启劚 TLS 终止代理。 这并䞍理想因䞺䜠的应甚皋序圚 TLS 终止代理关闭期闎将䞍可甚。 + +通过拥有䞀䞪**单独的系统来䜿甚 TLS 终止代理来倄理 HTTPS**, 而䞍是盎接将 TLS 证乊䞎应甚皋序服务噚䞀起䜿甚 䟋劂 Uvicorn,䜠可以圚 +曎新证乊的过皋䞭同时保持提䟛服务。 + +## 回顟 + +拥有**HTTPS** 非垞重芁并䞔圚倧倚数情况䞋盞圓**关键**。 䜜䞺匀发人员䜠囎绕 HTTPS 所做的倧郚分努力就是**理解这些抂念**以及它们的工䜜原理。 + +䞀旊䜠了解了**面向匀发人员的 HTTPS** 的基础知识䜠就可以蜻束组合和配眮䞍同的工具以垮助䜠以简单的方匏管理䞀切。 + +圚接䞋来的䞀些章节䞭我将向䜠展瀺几䞪䞺 **FastAPI** 应甚皋序讟眮 **HTTPS** 的具䜓瀺䟋。 🔒 From da9bd0ee4cf2b1eb63154d9ff45106a92e94b89b Mon Sep 17 00:00:00 2001 From: xzmeng Date: Tue, 9 Jan 2024 23:39:41 +0800 Subject: [PATCH 063/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/deployment/manually.md`=20(#10279)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Big Yellow Dog --- docs/zh/docs/deployment/manually.md | 148 ++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 docs/zh/docs/deployment/manually.md diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md new file mode 100644 index 0000000000000..15588043fecbb --- /dev/null +++ b/docs/zh/docs/deployment/manually.md @@ -0,0 +1,148 @@ +# 手劚运行服务噚 - Uvicorn + +圚远皋服务噚计算机䞊运行 **FastAPI** 应甚皋序所需的䞻芁䞜西是 ASGI 服务噚皋序䟋劂 **Uvicorn**。 + +有 3 䞪䞻芁可选方案 + +* Uvicorn高性胜 ASGI 服务噚。 +* Hypercorn䞎 HTTP/2 和 Trio 等兌容的 ASGI 服务噚。 +* Daphne䞺 Django Channels 构建的 ASGI 服务噚。 + +## 服务噚䞻机和服务噚皋序 + +关于名称有䞀䞪小细节需芁记䜏。 💡 + +“**服务噚**”䞀词通垞甚于指远皋/云计算机物理机或虚拟机以及圚该计算机䞊运行的皋序䟋劂 Uvicorn。 + +请记䜏圓悚䞀般读到“服务噚”这䞪名词时它可胜指的是这䞀者之䞀。 + +圓提到远皋䞻机时通垞将其称䞺**服务噚**䜆也称䞺**机噚**(machine)、**VM**虚拟机、**节点**。 这些郜是指某种类型的远皋计算机通垞运行 Linux悚可以圚其䞭运行皋序。 + + +## 安装服务噚皋序 + +悚可以䜿甚以䞋呜什安装 ASGI 兌容服务噚 + +=== "Uvicorn" + + * Uvicorn䞀䞪快劂闪电 ASGI 服务噚基于 uvloop 和 httptools 构建。 + +
+ + ```console + $ pip install "uvicorn[standard]" + + ---> 100% + ``` + +
+ + !!! tip + 通过添加`standard`Uvicorn 将安装并䜿甚䞀些掚荐的额倖䟝赖项。 + + 其䞭包括`uvloop`它是`asyncio`的高性胜替代品它提䟛了巚倧的并发性胜提升。 + +=== "Hypercorn" + + * Hypercorn䞀䞪也䞎 HTTP/2 兌容的 ASGI 服务噚。 + +
+ + ```console + $ pip install hypercorn + + ---> 100% + ``` + +
+ + ...或任䜕其他 ASGI 服务噚。 + + +## 运行服务噚皋序 + +悚可以按照之前教皋䞭的盞同方匏运行应甚皋序䜆䞍䜿甚`--reload`选项䟋劂 + +=== "Uvicorn" + +
+ + ```console + $ uvicorn main:app --host 0.0.0.0 --port 80 + + INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) + ``` + +
+ + +=== "Hypercorn" + +
+ + ```console + $ hypercorn main:app --bind 0.0.0.0:80 + + Running on 0.0.0.0:8080 over http (CTRL + C to quit) + ``` + +
+ +!!! warning + 劂果悚正圚䜿甚`--reload`选项请记䜏删陀它。 + + `--reload` 选项消耗曎倚资源并䞔曎䞍皳定。 + + 它圚**匀发**期闎有埈倧垮助䜆悚**䞍应该**圚**生产环境**䞭䜿甚它。 + +## Hypercorn with Trio + +Starlette 和 **FastAPI** 基于 AnyIO 所以它们才胜同时䞎 Python 的标准库 asyncio 和Trio 兌容。 + +尜管劂歀Uvicorn 目前仅䞎 asyncio 兌容并䞔通垞䜿甚 `uvloop`, 它是`asyncio`的高性胜替代品。 + +䜆劂果䜠想盎接䜿甚**Trio**那么䜠可以䜿甚**Hypercorn**因䞺它支持它。 ✹ + +### 安装具有 Trio 的 Hypercorn + +銖先悚需芁安装具有 Trio 支持的 Hypercorn + +
+ +```console +$ pip install "hypercorn[trio]" +---> 100% +``` + +
+ +### Run with Trio + +然后䜠可以䌠递倌`trio`给呜什行选项`--worker-class`: + +
+ +```console +$ hypercorn main:app --worker-class trio +``` + +
+ +这将通过悚的应甚皋序启劚 Hypercorn并䜿甚 Trio 䜜䞺后端。 + +现圚悚可以圚应甚皋序内郚䜿甚 Trio。 或者曎奜的是悚可以䜿甚 AnyIO䜿悚的代码䞎 Trio 和 asyncio 兌容。 🎉 + +## 郚眲抂念 + +这些瀺䟋运行服务噚皋序䟋劂 Uvicorn启劚**单䞪进皋**圚所有 IP`0.0.0.0`)䞊监听预定义端口䟋劂`80`)。 + +这是基本思路。 䜆悚可胜需芁倄理䞀些其他事情䟋劂 + +* 安党性 - HTTPS +* 启劚时运行 +* 重新启劚 +* Replication运行的进皋数 +* 内存 +* 匀始前的步骀 + +圚接䞋来的章节䞭我将向悚诊细介绍每䞪抂念、劂䜕思考它们以及䞀些具䜓瀺䟋以及倄理它们的策略。 🚀 From 623ee4460b92617919b974ff97b0927cd289de32 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:41:08 +0000 Subject: [PATCH 064/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e200823d05e1a..0f475a67d1a6b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Update Turkish translation for `docs/tr/docs/index.md`. PR [#10444](https://github.com/tiangolo/fastapi/pull/10444) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Chinese translation for `docs/zh/docs/learn/index.md`. PR [#10479](https://github.com/tiangolo/fastapi/pull/10479) by [@KAZAMA-DREAM](https://github.com/KAZAMA-DREAM). * 🌐 Add Russian translation for `docs/ru/docs/learn/index.md`. PR [#10539](https://github.com/tiangolo/fastapi/pull/10539) by [@AlertRED](https://github.com/AlertRED). * 🌐 Update SQLAlchemy instruction in Chinese translation `docs/zh/docs/tutorial/sql-databases.md`. PR [#9712](https://github.com/tiangolo/fastapi/pull/9712) by [@Royc30ne](https://github.com/Royc30ne). From d29709fee8565ae5403795c2ce2d5c1e7b5f1c2a Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:43:37 +0000 Subject: [PATCH 065/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0f475a67d1a6b..43e09a59a5824 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/first-steps.md`. PR [#9530](https://github.com/tiangolo/fastapi/pull/9530) by [@fhabers21](https://github.com/fhabers21). * 🌐 Update Turkish translation for `docs/tr/docs/index.md`. PR [#10444](https://github.com/tiangolo/fastapi/pull/10444) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Chinese translation for `docs/zh/docs/learn/index.md`. PR [#10479](https://github.com/tiangolo/fastapi/pull/10479) by [@KAZAMA-DREAM](https://github.com/KAZAMA-DREAM). * 🌐 Add Russian translation for `docs/ru/docs/learn/index.md`. PR [#10539](https://github.com/tiangolo/fastapi/pull/10539) by [@AlertRED](https://github.com/AlertRED). From 4023510e4c7a3c668e6b7c97934679a3378b8ebd Mon Sep 17 00:00:00 2001 From: xzmeng Date: Tue, 9 Jan 2024 23:44:17 +0800 Subject: [PATCH 066/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/deployment/cloud.md`=20(#10291)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Lion <121552599+socket-socket@users.noreply.github.com> --- docs/zh/docs/deployment/cloud.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 docs/zh/docs/deployment/cloud.md diff --git a/docs/zh/docs/deployment/cloud.md b/docs/zh/docs/deployment/cloud.md new file mode 100644 index 0000000000000..398f613728db6 --- /dev/null +++ b/docs/zh/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# 圚云䞊郚眲 FastAPI + +悚几乎可以䜿甚**任䜕云服务商**来郚眲 FastAPI 应甚皋序。 + +圚倧倚数情况䞋䞻芁的云服务商郜有郚眲 FastAPI 的指南。 + +## 云服务商 - 赞助商 + +䞀些云服务商 ✹ [**赞助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✚这确保了FastAPI 及其**生态系统**持续健康地**发展**。 + +这衚明了他们对 FastAPI 及其**瀟区**悚的真正承诺因䞺他们䞍仅想䞺悚提䟛**良奜的服务**而䞔还想确保悚拥有䞀䞪**良奜䞔健康的框架**FastAPI。 🙇 + +悚可胜想尝试他们的服务并阅读他们的指南 + +* Platform.sh +* Porter +* Deta From 179c8a07633f65481f161e891b99d9611d930d94 Mon Sep 17 00:00:00 2001 From: xzmeng Date: Tue, 9 Jan 2024 23:46:41 +0800 Subject: [PATCH 067/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/deployment/server-workers.md`=20(#102?= =?UTF-8?q?92)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Big Yellow Dog --- docs/zh/docs/deployment/server-workers.md | 184 ++++++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 docs/zh/docs/deployment/server-workers.md diff --git a/docs/zh/docs/deployment/server-workers.md b/docs/zh/docs/deployment/server-workers.md new file mode 100644 index 0000000000000..ee3de9b5da406 --- /dev/null +++ b/docs/zh/docs/deployment/server-workers.md @@ -0,0 +1,184 @@ +# Server Workers - Gunicorn with Uvicorn + +让我们回顟䞀䞋之前的郚眲抂念 + +* 安党性 - HTTPS +* 启劚时运行 +* 重新启劚 +* **倍制运行的进皋数** +* 内存 +* 启劚前的先前步骀 + +到目前䞺止通过文档䞭的所有教皋悚可胜已经圚**单䞪进皋**䞊运行了像 Uvicorn 这样的**服务噚皋序**。 + +郚眲应甚皋序时悚可胜垌望进行䞀些**进皋倍制**以利甚**倚栞**并胜借倄理曎倚请求。 + +正劂悚圚䞊䞀章有关[郚眲抂念](./concepts.md){.internal-link target=_blank}䞭看到的悚可以䜿甚倚种策略。 + +圚这里我将向悚展瀺劂䜕将 **Gunicorn** 侎 **Uvicorn worker 进皋** 䞀起䜿甚。 + +!!! info + 劂果悚正圚䜿甚容噚䟋劂 Docker 或 Kubernetes我将圚䞋䞀章䞭告诉悚曎倚盞关信息[容噚䞭的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 + + 特别是圓圚 **Kubernetes** 䞊运行时悚可胜**䞍想**䜿甚 Gunicorn而是运行 **每䞪容噚䞀䞪 Uvicorn 进皋**䜆我将圚本章后面告诉悚这䞀点。 + + + +## Gunicorn with Uvicorn Workers + +**Gunicorn**䞻芁是䞀䞪䜿甚**WSGI标准**的应甚服务噚。 这意味着 Gunicorn 可以䞺 Flask 和 Django 等应甚皋序提䟛服务。 Gunicorn 本身䞎 **FastAPI** 䞍兌容因䞺 FastAPI 䜿甚最新的 **ASGI 标准**。 + +䜆 Gunicorn 支持充圓 **进皋管理噚** 并允讞甚户告诉它芁䜿甚哪䞪特定的 **workerç±»**。 然后 Gunicorn 将䜿甚该类启劚䞀䞪或倚䞪 **worker进皋**。 + +**Uvicorn** 有䞀䞪 Gunicorn 兌容的worker类。 + +䜿甚这种组合Gunicorn 将充圓 **进皋管理噚**监听 **端口** 和 **IP**。 它䌚将通信**䌠蟓**到运行**Uvicornç±»**的worker进皋。 + +然后䞎Gunicorn兌容的**Uvicorn worker**类将莟莣将Gunicorn发送的数据蜬换䞺ASGI标准以䟛FastAPI䜿甚。 + +## 安装 Gunicorn 和 Uvicorn + +
+ +```console +$ pip install "uvicorn[standard]" gunicorn + +---> 100% +``` + +
+ +这将安装垊有`standard`扩展包以获埗高性胜的 Uvicorn 和 Gunicorn。 + +## Run Gunicorn with Uvicorn Workers + +接䞋来䜠可以通过以䞋呜什运行Gunicorn: + +
+ +```console +$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 + +[19499] [INFO] Starting gunicorn 20.1.0 +[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) +[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker +[19511] [INFO] Booting worker with pid: 19511 +[19513] [INFO] Booting worker with pid: 19513 +[19514] [INFO] Booting worker with pid: 19514 +[19515] [INFO] Booting worker with pid: 19515 +[19511] [INFO] Started server process [19511] +[19511] [INFO] Waiting for application startup. +[19511] [INFO] Application startup complete. +[19513] [INFO] Started server process [19513] +[19513] [INFO] Waiting for application startup. +[19513] [INFO] Application startup complete. +[19514] [INFO] Started server process [19514] +[19514] [INFO] Waiting for application startup. +[19514] [INFO] Application startup complete. +[19515] [INFO] Started server process [19515] +[19515] [INFO] Waiting for application startup. +[19515] [INFO] Application startup complete. +``` + +
+ + +让我们看看每䞪选项的含义 + +* `main:app`这䞎 Uvicorn 䜿甚的语法盞同`main` 衚瀺名䞺"`main`"的 Python 暡块因歀是文件 `main.py`。 `app` 是 **FastAPI** 应甚皋序的变量名称。 + * 䜠可以想象 `main:app` 盞圓于䞀䞪 Python `import` 语句䟋劂 + + ```Python + from main import app + ``` + + * 因歀`main:app` 䞭的冒号盞圓于 `from main import app` 侭的 Python `import` 郚分。 + +* `--workers`芁䜿甚的worker进皋数量每䞪进皋将运行䞀䞪 Uvicorn worker进皋圚本䟋䞭䞺 4 䞪worker进皋。 + +* `--worker-class`圚worker进皋䞭䜿甚的䞎 Gunicorn 兌容的工䜜类。 + * 这里我们䌠递了 Gunicorn 可以富入和䜿甚的类 + + ```Python + import uvicorn.workers.UvicornWorker + ``` + +* `--bind`这告诉 Gunicorn 芁监听的 IP 和端口䜿甚冒号 (`:`) 分隔 IP 和端口。 + * 劂果悚盎接运行 Uvicorn则可以䜿甚`--host 0.0.0.0`和`--port 80`而䞍是`--bind 0.0.0.0:80`Gunicorn 选项。 + + +圚蟓出䞭悚可以看到它星瀺了每䞪进皋的 **PID**进皋 ID它只是䞀䞪数字。 + +䜠可以看到 + +* Gunicorn **进皋管理噚** 以 PID `19499` 匀倎圚悚的情况䞋它将是䞀䞪䞍同的数字。 +* 然后它匀始`Listening at: http://0.0.0.0:80`。 +* 然后它检测到它必须䜿甚 `uvicorn.workers.UvicornWorker` 倄的worker类。 +* 然后它启劚**4䞪worker**每䞪郜有自己的PID`19511`、`19513`、`19514`和`19515`。 + +Gunicorn 还将莟莣管理**死进皋**和**重新启劚**新进皋劂果需芁保持worker数量。 因歀这圚䞀定皋床䞊有助于䞊面列衚䞭**重启**的抂念。 + +尜管劂歀悚可胜还垌望有䞀些倖郚的䞜西以确保圚必芁时**重新启劚 Gunicorn**并䞔**圚启劚时运行它**等。 + +## Uvicorn with Workers + +Uvicorn 也有䞀䞪选项可以启劚和运行倚䞪 **worker进皋**。 + +然而到目前䞺止Uvicorn 倄理worker进皋的胜力比 Gunicorn 曎有限。 因歀劂果悚想拥有这䞪级别Python 级别的进皋管理噚那么最奜尝试䜿甚 Gunicorn 䜜䞺进皋管理噚。 + +无论劂䜕悚郜可以像这样运行它 + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 +INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +这里唯䞀的新选项是 `--workers` 告诉 Uvicorn 启劚 4 䞪工䜜进皋。 + +悚还可以看到它星瀺了每䞪进皋的 **PID**父进皋这是 **进皋管理噚**的 PID 䞺`27365`每䞪工䜜进皋的 PID 䞺`27368`、`27369` `27370`和`27367`。 + +## 郚眲抂念 + +圚这里悚了解了劂䜕䜿甚 **Gunicorn**或 Uvicorn管理 **Uvicorn 工䜜进皋**来**并行**应甚皋序的执行利甚 CPU 侭的 **倚栞**并 胜借满足**曎倚请求**。 + +从䞊面的郚眲抂念列衚来看䜿甚worker䞻芁有助于**倍制**郚分并对**重新启劚**有䞀点垮助䜆悚仍然需芁照顟其他郚分 + +* **安党 - HTTPS** +* **启劚时运行** +* ***重新启劚*** +* 倍制运行的进皋数 +* **内存** +* **启劚之前的先前步骀** + +## 容噚和 Docker + +圚关于 [容噚䞭的 FastAPI - Docker](./docker.md){.internal-link target=_blank} 的䞋䞀章䞭我将介绍䞀些可甚于倄理其他 **郚眲抂念** 的策略。 + +我还将向悚展瀺 **官方 Docker 镜像**其䞭包括 **Gunicorn 和 Uvicorn worker** 以及䞀些对简单情况有甚的默讀配眮。 + +圚那里我还将向悚展瀺劂䜕 **从倎匀始构建自己的镜像** 以运行单䞪 Uvicorn 进皋没有 Gunicorn。 这是䞀䞪简单的过皋并䞔可胜是悚圚䜿甚像 **Kubernetes** 这样的分垃匏容噚管理系统时想芁做的事情。 + +## 回顟 + +悚可以䜿甚**Gunicorn**或Uvicorn䜜䞺Uvicorn工䜜进皋的进皋管理噚以利甚**倚栞CPU****并行运行倚䞪进皋**。 + +劂果悚芁讟眮**自己的郚眲系统**同时自己倄理其他郚眲抂念则可以䜿甚这些工具和想法。 + +请查看䞋䞀章了解垊有容噚䟋劂 Docker 和 Kubernetes的 **FastAPI**。 悚将看到这些工具也有简单的方法来解决其他**郚眲抂念**。 ✹ From fe620a6c127cf5134d520abe91914e205fcac605 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:46:50 +0000 Subject: [PATCH 068/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 43e09a59a5824..b292a818efc18 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/index.md`. PR [#10275](https://github.com/tiangolo/fastapi/pull/10275) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add German translation for `docs/de/docs/tutorial/first-steps.md`. PR [#9530](https://github.com/tiangolo/fastapi/pull/9530) by [@fhabers21](https://github.com/fhabers21). * 🌐 Update Turkish translation for `docs/tr/docs/index.md`. PR [#10444](https://github.com/tiangolo/fastapi/pull/10444) by [@hasansezertasan](https://github.com/hasansezertasan). * 🌐 Add Chinese translation for `docs/zh/docs/learn/index.md`. PR [#10479](https://github.com/tiangolo/fastapi/pull/10479) by [@KAZAMA-DREAM](https://github.com/KAZAMA-DREAM). From f27e818edb0fdd24680235b59298ba60b0c30fe0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:47:49 +0000 Subject: [PATCH 069/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b292a818efc18..b71ee8f13fcdd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/https.md`. PR [#10277](https://github.com/tiangolo/fastapi/pull/10277) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/index.md`. PR [#10275](https://github.com/tiangolo/fastapi/pull/10275) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add German translation for `docs/de/docs/tutorial/first-steps.md`. PR [#9530](https://github.com/tiangolo/fastapi/pull/9530) by [@fhabers21](https://github.com/fhabers21). * 🌐 Update Turkish translation for `docs/tr/docs/index.md`. PR [#10444](https://github.com/tiangolo/fastapi/pull/10444) by [@hasansezertasan](https://github.com/hasansezertasan). From c5bbcb8c9c323f23e0d97ce3d0dfc00772362b15 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 15:49:16 +0000 Subject: [PATCH 070/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b71ee8f13fcdd..e0b82fbcbf86d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/manually.md`. PR [#10279](https://github.com/tiangolo/fastapi/pull/10279) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/https.md`. PR [#10277](https://github.com/tiangolo/fastapi/pull/10277) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/index.md`. PR [#10275](https://github.com/tiangolo/fastapi/pull/10275) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add German translation for `docs/de/docs/tutorial/first-steps.md`. PR [#9530](https://github.com/tiangolo/fastapi/pull/9530) by [@fhabers21](https://github.com/fhabers21). From 933668b42e025f00b6d1de7b1e1ebf18f4f1f2ae Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov Date: Tue, 9 Jan 2024 18:51:54 +0300 Subject: [PATCH 071/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/request-files.md`=20(#10332)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Vladislav Kramorenko <85196001+Xewus@users.noreply.github.com> Co-authored-by: oubush --- docs/ru/docs/tutorial/request-files.md | 314 +++++++++++++++++++++++++ 1 file changed, 314 insertions(+) create mode 100644 docs/ru/docs/tutorial/request-files.md diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md new file mode 100644 index 0000000000000..00f8c8377059f --- /dev/null +++ b/docs/ru/docs/tutorial/request-files.md @@ -0,0 +1,314 @@ +# Загрузка файлПв + +ИспПльзуя класс `File`, Ќы ЌПжеЌ пПзвПлОть клОеМтаЌ загружать файлы. + +!!! info "ДПпПлМОтельМая ОМфПрЌацОя" + ЧтПбы пПлучать загружеММые файлы, сМачала устаМПвОте `python-multipart`. + + НапрОЌер: `pip install python-multipart`. + + ЭтП связаМП с теЌ, чтП загружаеЌые файлы переЎаются как ЎаММые фПрЌы. + +## ИЌпПрт `File` + +ИЌпПртОруйте `File` О `UploadFile` Оз ЌПЎуля `fastapi`: + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +## ОпреЎелОте параЌетры `File` + +СПзЎайте параЌетры `File` так же, как вы этП Ўелаете Ўля `Body` ОлО `Form`: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="8" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="7" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +!!! info "ДПпПлМОтельМая ОМфПрЌацОя" + `File` - этП класс, кПтПрый МаслеЎуется МепПсреЎствеММП Пт `Form`. + + НП пПЌМОте, чтП кПгЎа вы ОЌпПртОруете `Query`, `Path`, `File` О ЎругОе Оз `fastapi`, Ма саЌПЌ Ўеле этП фуМкцОО, кПтПрые вПзвращают спецОальМые классы. + +!!! tip "ППЎсказка" + Для ПбъявлеМОя тела файла МеПбхПЎОЌП ОспПльзПвать `File`, пПскПльку в прПтОвМПЌ случае параЌетры буЎут ОМтерпретОрПваться как параЌетры запрПса ОлО параЌетры тела (JSON). + +Ѐайлы буЎут загружеМы как ЎаММые фПрЌы. + +ЕслО вы ПбъявОте тОп параЌетра у *фуМкцОО ПперацОО путО* как `bytes`, тП **FastAPI** прПчОтает файл за вас, О вы пПлучОте егП сПЎержОЌПе в вОЎе `bytes`. + +СлеЎует ОЌеть в вОЎу, чтП все сПЎержОЌПе буЎет храМОться в паЌятО. ЭтП хПрПшП пПЎхПЎОт Ўля МебПльшОх файлПв. + +ОЎМакП вПзЌПжМы случаО, кПгЎа ОспПльзПваМОе `UploadFile` ЌПжет Пказаться пПлезМыЌ. + +## Загрузка файла с пПЌПщью `UploadFile` + +ОпреЎелОте параЌетр файла с тОпПЌ `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="14" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="13" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="12" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +ИспПльзПваМОе `UploadFile` ОЌеет ряЎ преОЌуществ переЎ `bytes`: + +* ИспПльзПвать `File()` в зМачеМОО параЌетра пП уЌПлчаМОю Ме ПбязательМП. +* ПрО этПЌ ОспПльзуется "буферМый" файл: + * Ѐайл, храМящОйся в паЌятО ЎП ЌаксОЌальМПгП преЎела разЌера, пПсле преПЎПлеМОя кПтПрПгП ПМ буЎет храМОться Ма ЎОске. +* ЭтП ПзМачает, чтП ПМ буЎет хПрПшП рабПтать с бПльшОЌО файлаЌО, такОЌО как ОзПбражеМОя, вОЎеП, бПльшОе бОМарМые файлы О т.ÐŽ., Ме пПтребляя прО этПЌ всю паЌять. +* Из загружеММПгП файла ЌПжМП пПлучОть ЌетаЎаММые. +* ОМ реалОзует file-like `async` ОМтерфейс. +* ОМ преЎПставляет реальМый Пбъект Python `SpooledTemporaryFile` кПтПрый вы ЌПжете переЎать МепПсреЎствеММП ЎругОЌ бОблОПтекаЌ, кПтПрые ПжОЎают файл в качестве Пбъекта. + +### `UploadFile` + +`UploadFile` ОЌеет слеЎующОе атрОбуты: + +* `filename`: СтрПка `str` с ОсхПЎМыЌ ОЌеМеЌ файла, кПтПрый был загружеМ (МапрОЌер, `myimage.jpg`). +* `content_type`: СтрПка `str` с тОпПЌ сПЎержОЌПгП (MIME type / media type) (МапрОЌер, `image/jpeg`). +* `file`: `SpooledTemporaryFile` (a file-like Пбъект). ЭтП фактОческОй файл Python, кПтПрый ЌПжМП переЎавать МепПсреЎствеММП ЎругОЌ фуМкцОяЌ ОлО бОблОПтекаЌ, ПжОЎающОЌ файл в качестве Пбъекта. + +`UploadFile` ОЌеет слеЎующОе ЌетПЎы `async`. Все ПМО вызывают сППтветствующОе файлПвые ЌетПЎы (ОспПльзуя вМутреММОй SpooledTemporaryFile). + +* `write(data)`: ЗапОсать ЎаММые `data` (`str` ОлО `bytes`) в файл. +* `read(size)`: ПрПчОтать кПлОчествП `size` (`int`) байт/сОЌвПлПв Оз файла. +* `seek(offset)`: ПерейтО к байту Ма пПзОцОО `offset` (`int`) в файле. + * НарОЌер, `await myfile.seek(0)` перейЎет к Мачалу файла. + * ЭтП ПсПбеММП уЎПбМП, еслО вы ПЎОМ раз выпПлМОлО кПЌаМЎу `await myfile.read()`, а затеЌ ваЌ МужМП прПчОтать сПЎержОЌПе файла еще раз. +* `close()`: Закрыть файл. + +ППскПльку все этО ЌетПЎы являются `async` ЌетПЎаЌО, ваЌ слеЎует ОспПльзПвать "await" вЌесте с МОЌО. + +НапрОЌер, вМутрО `async` *фуМкцОО ПперацОО путО* ЌПжМП пПлучОть сПЎержОЌПе с пПЌПщью: + +```Python +contents = await myfile.read() +``` + +ЕслО вы МахПЎОтесь вМутрО ПбычМПй `def` *фуМкцОО ПперацОО путО*, ЌПжМП пПлучОть пряЌПй ЎПступ к файлу `UploadFile.file`, МапрОЌер: + +```Python +contents = myfile.file.read() +``` + +!!! note "ТехМОческОе ЎеталО `async`" + ПрО ОспПльзПваМОО ЌетПЎПв `async` **FastAPI** запускает файлПвые ЌетПЎы в пуле пПтПкПв О ПжОЎает Ох. + +!!! note "ТехМОческОе ЎеталО Starlette" + **FastAPI** МаслеЎует `UploadFile` МепПсреЎствеММП Оз **Starlette**, МП ЎПбавляет МекПтПрые ЎеталО Ўля сПвЌестОЌПстО с **Pydantic** О ЎругОЌО частяЌО FastAPI. + +## ПрП ЎаММые фПрЌы ("Form Data") + +СпПсПб, кПтПрыЌ HTML-фПрЌы (`
`) Птправляют ЎаММые Ма сервер, ПбычМП ОспПльзует "спецОальМую" кПЎОрПвку Ўля этОх ЎаММых, ПтлОчМую Пт JSON. + +**FastAPI** пПзабПтОтся П тПЌ, чтПбы счОтать этО ЎаММые Оз МужМПгП Ќеста, а Ме Оз JSON. + +!!! note "ТехМОческОе ЎеталО" + ДаММые Оз фПрЌ ПбычМП кПЎОруются с ОспПльзПваМОеЌ "media type" `application/x-www-form-urlencoded` кПгЎа ПМ Ме включает файлы. + + НП кПгЎа фПрЌа включает файлы, ПМа кПЎОруется как multipart/form-data. ЕслО вы ОспПльзуете `File`, **FastAPI** буЎет зМать, чтП еЌу МужМП пПлучОть файлы Оз МужМПй частО тела. + + ЕслО вы хПтОте узМать бПльше Пб этОх кПЎОрПвках О пПлях фПрЌ, перейЎОте пП ссылке MDN web docs for POST. + +!!! warning "ВМОЌаМОе" + В ПперацОО *фуМкцОО ПперацОО путО* ЌПжМП ПбъявОть МескПлькП параЌетрПв `File` О `Form`, МП Мельзя также Пбъявлять пПля `Body`, кПтПрые преЎпПлагается пПлучОть в вОЎе JSON, пПскПльку телП запрПса буЎет закПЎОрПваМП с пПЌПщью `multipart/form-data`, а Ме `application/json`. + + ЭтП Ме является ПграМОчеМОеЌ **FastAPI**, этП часть прПтПкПла HTTP. + +## НеПбязательМая загрузка файлПв + +Вы ЌПжете сЎелать загрузку файла МеПбязательМПй, ОспПльзуя стаМЎартМые аММПтацОО тОпПв О устаМПвОв зМачеМОе пП уЌПлчаМОю `None`: + +=== "Python 3.10+" + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="10 18" + {!> ../../../docs_src/request_files/tutorial001_02_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="7 15" + {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02.py!} + ``` + +## `UploadFile` с ЎПпПлМОтельМыЌО ЌетаЎаММыЌО + +Вы также ЌПжете ОспПльзПвать `File()` вЌесте с `UploadFile`, МапрОЌер, Ўля устаМПвкО ЎПпПлМОтельМых ЌетаЎаММых: + +=== "Python 3.9+" + + ```Python hl_lines="9 15" + {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="8 14" + {!> ../../../docs_src/request_files/tutorial001_03_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="7 13" + {!> ../../../docs_src/request_files/tutorial001_03.py!} + ``` + +## Загрузка МескПлькОх файлПв + +МПжМП ПЎМПвреЌеММП загружать МескПлькП файлПв. + +ОМО буЎут связаМы с ПЎМОЌ О теЌ же "пПлеЌ фПрЌы", ПтправляеЌыЌ с пПЌПщью ЎаММых фПрЌы. + +Для этПгП МеПбхПЎОЌП ПбъявОть спОсПк `bytes` ОлО `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/request_files/tutorial002_an.py!} + ``` + +=== "Python 3.9+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="8 13" + {!> ../../../docs_src/request_files/tutorial002_py39.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002.py!} + ``` + +Вы пПлучОте, как О былП ПбъявлеМП, спОсПк `list` Оз `bytes` ОлО `UploadFile`. + +!!! note "Technical Details" + МПжМП также ОспПльзПвать `from starlette.responses import HTMLResponse`. + + **FastAPI** преЎПставляет тПт же `starlette.responses`, чтП О `fastapi.responses`, прПстП Ўля уЎПбства разрабПтчОка. ОЎМакП бПльшОМствП ЎПступМых ПтветПв пПступает МепПсреЎствеММП Оз Starlette. + +### Загрузка МескПлькОх файлПв с ЎПпПлМОтельМыЌО ЌетаЎаММыЌО + +Так же, как О раМьше, вы ЌПжете ОспПльзПвать `File()` Ўля заЎаМОя ЎПпПлМОтельМых параЌетрПв, Ўаже Ўля `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="11 18-20" + {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12 19-21" + {!> ../../../docs_src/request_files/tutorial003_an.py!} + ``` + +=== "Python 3.9+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="9 16" + {!> ../../../docs_src/request_files/tutorial003_py39.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="11 18" + {!> ../../../docs_src/request_files/tutorial003.py!} + ``` + +## РезюЌе + +ИспПльзуйте `File`, `bytes` О `UploadFile` Ўля рабПты с файлаЌО, кПтПрые буЎут загружаться О переЎаваться в вОЎе ЎаММых фПрЌы. From a64b2fed91fdda259e2363b9bd7ba83d3a8fee98 Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov Date: Tue, 9 Jan 2024 18:52:07 +0300 Subject: [PATCH 072/217] =?UTF-8?q?=F0=9F=8C=90=20Fix=20typos=20in=20Russi?= =?UTF-8?q?an=20translations=20for=20`docs/ru/docs/tutorial/background-tas?= =?UTF-8?q?ks.md`,=20`docs/ru/docs/tutorial/body-nested-models.md`,=20`doc?= =?UTF-8?q?s/ru/docs/tutorial/debugging.md`,=20`docs/ru/docs/tutorial/test?= =?UTF-8?q?ing.md`=20(#10311)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/tutorial/background-tasks.md | 2 +- docs/ru/docs/tutorial/body-nested-models.md | 2 +- docs/ru/docs/tutorial/debugging.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 7a3cf6d839f91..73ba860bc3dd9 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -71,7 +71,7 @@ В этПЌ прОЌере сППбщеМОя буЎут запОсаМы в `log.txt` *пПсле* тПгП, как Птвет сервера был ПтправлеМ. -ЕслО бы в запрПсе была ПчереЎь `q`, ПМа бы первПй запОсалась в `log.txt` фПМПвПй заЎачей (пПтПЌу чтП вызывается в завОсОЌПстО `get_query`). +ЕслО бы в запрПс был переЎаМ query-параЌетр `q`, ПМ бы первыЌО запОсался в `log.txt` фПМПвПй заЎачей (пПтПЌу чтП вызывается в завОсОЌПстО `get_query`). ППсле Ўругая фПМПвая заЎача, кПтПрая была сгеМерОрПваМа в фуМкцОО, запОшет сППбщеМОе Оз параЌетра `email`. diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index a6d123d30dc16..bbf9b768597c1 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -85,7 +85,7 @@ my_list: List[str] И в Python есть спецОальМый тОп ЎаММых Ўля ЌМПжеств уМОкальМых элеЌеМтПв - `set`. -ТПгЎа Ќы ЌПжет ПбьявОть пПле `tags` как ЌМПжествП стрПк: +ТПгЎа Ќы ЌПжеЌ ПбьявОть пПле `tags` как ЌМПжествП стрПк: === "Python 3.10+" diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 755d98cf20d28..38709e56df7c3 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -22,7 +22,7 @@ $ python myapp.py
-МП Ме вызывался, кПгЎа ЎругПй файл ОЌпПртОрует этП, МапрОЌер:: +МП Ме вызывался, кПгЎа ЎругПй файл ОЌпПртОрует этП, МапрОЌер: ```Python from myapp import app From 9f7902925a74419f7c3e439e31554c25fd9f3109 Mon Sep 17 00:00:00 2001 From: _Shuibei <33409883+ShuibeiC@users.noreply.github.com> Date: Tue, 9 Jan 2024 23:53:39 +0800 Subject: [PATCH 073/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/additional-responses.md`=20(?= =?UTF-8?q?#10325)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: unknown Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/zh/docs/advanced/additional-responses.md | 219 ++++++++++++++++++ 1 file changed, 219 insertions(+) create mode 100644 docs/zh/docs/advanced/additional-responses.md diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md new file mode 100644 index 0000000000000..2a1e1ed891a79 --- /dev/null +++ b/docs/zh/docs/advanced/additional-responses.md @@ -0,0 +1,219 @@ +# OPENAPI 䞭的其他响应 + +悚可以声明附加响应包括附加状态代码、媒䜓类型、描述等。 + +这些额倖的响应将包含圚OpenAPI暡匏䞭因歀它们也将出现圚API文档䞭。 + +䜆是对于那些额倖的响应䜠必须确保䜠盎接返回䞀䞪像 `JSONResponse` 䞀样的 `Response` 并包含䜠的状态代码和内容。 + +## `model`附加响应 +悚可以向路埄操䜜装饰噚䌠递参数 `responses` 。 + +它接收䞀䞪 `dict`键是每䞪响应的状态代码劂`200`倌是包含每䞪响应信息的其他 `dict`。 + +每䞪响应字兞郜可以有䞀䞪关键暡型其䞭包含䞀䞪 `Pydantic` 暡型就像 `response_model` 䞀样。 + +**FastAPI**将采甚该暡型生成其`JSON Schema`并将其包含圚`OpenAPI`䞭的正确䜍眮。 + +䟋劂芁声明及䞀䞪具有状态码 `404` 和`Pydantic`æš¡åž‹ `Message` 的响应可以写 +```Python hl_lines="18 22" +{!../../../docs_src/additional_responses/tutorial001.py!} +``` + + +!!! Note + 请记䜏悚必须盎接返回 `JSONResponse` 。 + +!!! Info + `model` 密钥䞍是OpenAPI的䞀郚分。 + **FastAPI**将从那里获取`Pydantic`暡型生成` JSON Schema` 并将其攟圚正确的䜍眮。 + - 正确的䜍眮是 + - 圚键 `content` 䞭其具有及䞀䞪`JSON`对象 `dict` 䜜䞺倌该`JSON`对象包含 + - 媒䜓类型的密钥䟋劂 `application/json` 它包含及䞀䞪`JSON`对象䜜䞺倌该对象包含 + - 䞀䞪键` schema` 它的倌是来自暡型的`JSON Schema`正确的䜍眮圚这里。 + - **FastAPI**圚这里添加了对OpenAPI䞭及䞀䞪地方的党局JSON暡匏的匕甚而䞍是盎接包含它。这样其他应甚皋序和客户端可以盎接䜿甚这些JSON暡匏提䟛曎奜的代码生成工具等。 + + +**圚OpenAPI䞭䞺该路埄操䜜生成的响应将是** + +```json hl_lines="3-12" +{ + "responses": { + "404": { + "description": "Additional Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } +} + +``` +**暡匏被匕甚到OpenAPI暡匏䞭的及䞀䞪䜍眮** +```json hl_lines="4-16" +{ + "components": { + "schemas": { + "Message": { + "title": "Message", + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "title": "Message", + "type": "string" + } + } + }, + "Item": { + "title": "Item", + "required": [ + "id", + "value" + ], + "type": "object", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + } + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + } + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + } + } + } + } +} + +``` +## 䞻响应的其他媒䜓类型 + +悚可以䜿甚盞同的 `responses` 参数䞺盞同的䞻响应添加䞍同的媒䜓类型。 + +䟋劂悚可以添加䞀䞪额倖的媒䜓类型` image/png` 声明悚的路埄操䜜可以返回JSON对象媒䜓类型 `application/json` 或PNG囟像 + +```Python hl_lines="19-24 28" +{!../../../docs_src/additional_responses/tutorial002.py!} +``` + +!!! Note + - 请泚意悚必须盎接䜿甚 `FileResponse` 返回囟像。 + +!!! Info + - 陀非圚 `responses` 参数䞭明确指定䞍同的媒䜓类型吊则**FastAPI**将假定响应䞎䞻响应类具有盞同的媒䜓类型默讀䞺` application/json` 。 + - 䜆是劂果悚指定了䞀䞪自定义响应类并将 `None `䜜䞺其媒䜓类型**FastAPI**将䜿甚 `application/json` 䜜䞺具有关联暡型的任䜕其他响应。 + +## 组合信息 +悚还可以联合接收来自倚䞪䜍眮的响应信息包括 `response_model `、 `status_code` 和 `responses `参数。 + +悚可以䜿甚默讀的状态码 `200` 或者悚需芁的自定义状态码声明䞀䞪 `response_model `然后盎接圚OpenAPI暡匏䞭圚 `responses` 䞭声明盞同响应的其他信息。 + +**FastAPI**将保留来自 `responses` 的附加信息并将其䞎暡型䞭的JSON Schema结合起来。 + +䟋劂悚可以䜿甚状态码 `404` 声明响应该响应䜿甚`Pydantic`暡型并具有自定义的` description` 。 + +以及䞀䞪状态码䞺 `200` 的响应它䜿甚悚的 `response_model` 䜆包含自定义的 `example`  + +```Python hl_lines="20-31" +{!../../../docs_src/additional_responses/tutorial003.py!} +``` + +所有这些郜将被合并并包含圚悚的OpenAPI䞭并圚API文档䞭星瀺 + +## 联合预定义响应和自定义响应 + +悚可胜垌望有䞀些应甚于讞倚路埄操䜜的预定义响应䜆是䜠想将䞍同的路埄和自定义的盞应组合圚䞀块。 +对于这些情况䜠可以䜿甚Python的技术将 `dict` 侎 `**dict_to_unpack` 解包 +```Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +这里 new_dict 将包含来自 old_dict 的所有键倌对加䞊新的键倌对 +```python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` +悚可以䜿甚该技术圚路埄操䜜䞭重甚䞀些预定义的响应并将它们䞎其他自定义响应盞结合。 +**䟋劂** +```Python hl_lines="13-17 26" +{!../../../docs_src/additional_responses/tutorial004.py!} +``` +## 有关OpenAPI响应的曎倚信息 + +芁了解悚可以圚响应䞭包含哪些内容悚可以查看OpenAPI规范䞭的以䞋郚分 + + [OpenAPI响应对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responsesObject)它包括 Response Object 。 + + [OpenAPI响应对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responseObject)悚可以盎接圚 `responses` 参数䞭的每䞪响应䞭包含任䜕内容。包括 `description` 、 `headers` 、 `content` 其䞭是声明䞍同的媒䜓类型和JSON Schemas和 `links` 。 From 11a5993c8cf037611b87b8064c7c7d5e3adc9fb5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 16:01:13 +0000 Subject: [PATCH 074/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e0b82fbcbf86d..31c637fccc087 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/cloud.md`. PR [#10291](https://github.com/tiangolo/fastapi/pull/10291) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/manually.md`. PR [#10279](https://github.com/tiangolo/fastapi/pull/10279) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/https.md`. PR [#10277](https://github.com/tiangolo/fastapi/pull/10277) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/index.md`. PR [#10275](https://github.com/tiangolo/fastapi/pull/10275) by [@xzmeng](https://github.com/xzmeng). From 8f70f8c43b4ce046958fd846e82f5610ed4bf91a Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 16:03:03 +0000 Subject: [PATCH 075/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 31c637fccc087..c6e539ea40bb2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/server-workers.md`. PR [#10292](https://github.com/tiangolo/fastapi/pull/10292) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/cloud.md`. PR [#10291](https://github.com/tiangolo/fastapi/pull/10291) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/manually.md`. PR [#10279](https://github.com/tiangolo/fastapi/pull/10279) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/https.md`. PR [#10277](https://github.com/tiangolo/fastapi/pull/10277) by [@xzmeng](https://github.com/xzmeng). From d305a67a8101cab32dec71469cb6fd5923097802 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 16:07:49 +0000 Subject: [PATCH 076/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c6e539ea40bb2..69894b2a91d23 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-files.md`. PR [#10332](https://github.com/tiangolo/fastapi/pull/10332) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/server-workers.md`. PR [#10292](https://github.com/tiangolo/fastapi/pull/10292) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/cloud.md`. PR [#10291](https://github.com/tiangolo/fastapi/pull/10291) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/manually.md`. PR [#10279](https://github.com/tiangolo/fastapi/pull/10279) by [@xzmeng](https://github.com/xzmeng). From 9ddc71e317938176098722f9f80e335cfc0d0ba1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 16:08:31 +0000 Subject: [PATCH 077/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 69894b2a91d23..ea1652195806d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Fix typos in Russian translations for `docs/ru/docs/tutorial/background-tasks.md`, `docs/ru/docs/tutorial/body-nested-models.md`, `docs/ru/docs/tutorial/debugging.md`, `docs/ru/docs/tutorial/testing.md`. PR [#10311](https://github.com/tiangolo/fastapi/pull/10311) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-files.md`. PR [#10332](https://github.com/tiangolo/fastapi/pull/10332) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/server-workers.md`. PR [#10292](https://github.com/tiangolo/fastapi/pull/10292) by [@xzmeng](https://github.com/xzmeng). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/cloud.md`. PR [#10291](https://github.com/tiangolo/fastapi/pull/10291) by [@xzmeng](https://github.com/xzmeng). From cee422f073ddcc37bea3d8f9c0a4bf2d902fe4e5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 16:09:04 +0000 Subject: [PATCH 078/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ea1652195806d..83cae1ddaeca9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/additional-responses.md`. PR [#10325](https://github.com/tiangolo/fastapi/pull/10325) by [@ShuibeiC](https://github.com/ShuibeiC). * 🌐 Fix typos in Russian translations for `docs/ru/docs/tutorial/background-tasks.md`, `docs/ru/docs/tutorial/body-nested-models.md`, `docs/ru/docs/tutorial/debugging.md`, `docs/ru/docs/tutorial/testing.md`. PR [#10311](https://github.com/tiangolo/fastapi/pull/10311) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-files.md`. PR [#10332](https://github.com/tiangolo/fastapi/pull/10332) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Chinese translation for `docs/zh/docs/deployment/server-workers.md`. PR [#10292](https://github.com/tiangolo/fastapi/pull/10292) by [@xzmeng](https://github.com/xzmeng). From 60e1259ca4c69feb8698f65ffd9744ae92db0721 Mon Sep 17 00:00:00 2001 From: Sepehr Shirkhanlu Date: Tue, 9 Jan 2024 19:40:37 +0330 Subject: [PATCH 079/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`fastapi/routing.py`=20(#10520)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix: https://github.com/tiangolo/fastapi/discussions/10493 --- fastapi/routing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index 589ecca2aaf73..acebabfca0566 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -4328,7 +4328,7 @@ class Item(BaseModel): app = FastAPI() router = APIRouter() - @router.put("/items/{item_id}") + @router.trace("/items/{item_id}") def trace_item(item_id: str): return None From 7d8241acb95bb5094363d9e8abc243d3119ffaf0 Mon Sep 17 00:00:00 2001 From: Amir Khorasani Date: Tue, 9 Jan 2024 19:44:01 +0330 Subject: [PATCH 080/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Persian=20translat?= =?UTF-8?q?ion=20for=20`docs/fa/docs/features.md`=20(#5887)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez Co-authored-by: Amin Alaee --- docs/fa/docs/features.md | 206 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 docs/fa/docs/features.md diff --git a/docs/fa/docs/features.md b/docs/fa/docs/features.md new file mode 100644 index 0000000000000..3040ce3dd9065 --- /dev/null +++ b/docs/fa/docs/features.md @@ -0,0 +1,206 @@ +# ویژگی ها + +## ویژگی های FastAPI + +**FastAPI** موارد زیر را ØšÙ‡ ؎ما ارا؊ه میدهد: + +### ؚرٟایه استاندارد های ؚاز + +* OpenAPI ؚرای ساخت API, ؎امل م؎خص سازی path operation ها, ٟارامترها, body request ها, امنیت و غیره. +* مستندسازی خودکار data model ؚا JSON Schema (همانطور که OpenAPI خود نیز مؚتنی ؚر JSON Schema است). +* طراحی ؎ده ؚر اساس استاندارد هایی که ٟس از یک مطالعه دقیق ؚدست آمده اند ؚجای طرحی ناٟخته و ؚدون فکر. +* همچنین ØšÙ‡ ؎ما اجازه میدهد تا از تولید خودکار client code در ؚسیاری از زؚان ها استفاده کنید. + +### مستندات خودکار + +مستندات API تعاملی و ایجاد راؚط کارؚری وؚ. از آنجایی که این فریم ورک ؚرٟایه OpenAPI میؚا؎د، آٟ؎ن های متعددی وجود دارد که Û² مورد ؚصورت ٟی؎ فرض گنجانده ؎ده اند. + +* Swagger UI، ؚا کاو؎ تعاملی، API خود را مستقیما از طریق مرورگر صدازده و تست کنید. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* مستندات API جایگزین ؚا ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### فقط ٟایتون مدرن + +همه اینها ؚرٟایه type declaration های **ٟایتون Û³.Û¶** استاندارد (ØšÙ‡ لطف Pydantic) میؚا؎ند. سینتکس جدیدی درکار نیست. تنها ٟایتون مدرن استاندارد. + +اگر ØšÙ‡ یک یادآوری Û² دقیقه ای در مورد نحوه استفاده از تایٟ های ٟایتون دارید (حتی اگر از FastAPI استفاده نمیکنید) این آموز؎ کوتاه را ؚررسی کنید: [Python Types](python-types.md){.internal-link target=\_blank}. + +؎ما ٟایتون استاندارد را ؚا استفاده از تایٟ ها مینویسید: + +```Python +from datetime import date + +from pydantic import BaseModel + +# Declare a variable as a str +# and get editor support inside the function +def main(user_id: str): + return user_id + + +# A Pydantic model +class User(BaseModel): + id: int + name: str + joined: date +``` + +که سٟس میتوان ØšÙ‡ این ØŽÚ©Ù„ از آن استفاده کرد: + +```Python +my_user: User = User(id=3, name="John Doe", joined="2018-07-19") + +second_user_data = { + "id": 4, + "name": "Mary", + "joined": "2018-11-30", +} + +my_second_user: User = User(**second_user_data) +``` + +!!! info + `**second_user_data` یعنی: + + کلید ها و مقادیر دیک؎نری `second_user_data` را مستقیما ØšÙ‡ عنوان ارگومان های key-value ؚفرست، که معادل است ؚا : `User(id=4, name="Mary", joined="2018-11-30")` + +### ٟ؎تیؚانی ویرای؎گر + +تمام فریم ورک ØšÙ‡ گونه ای طراحی ؎ده که استفاده از آن آسان و ؎هودی ؚا؎د، تمام تصمیمات حتی Ù‚ØšÙ„ از ؎روع توسعه ؚر روی چندین ویرای؎گر آزمای؎ ؎ده اند، تا از ؚهترین تجرؚه توسعه اطمینان حاصل ؎ود. + +در آخرین ن؞رسنجی توسعه دهندگان ٟایتون کاملا م؎خص ؚود که ؚی؎ترین ویژگی مورد استفاده از "تکمیل خودکار" است. + +تمام فریم ورک **FastAPI** ؚرٟایه ای ؚرای ؚراورده کردن این نیاز نیز ایجاد گ؎ته است. تکمیل خودکار در همه جا کار میکند. + +؎ما ØšÙ‡ ندرت نیاز ØšÙ‡ ؚازگ؎ت ØšÙ‡ مستندات را خواهید دا؎ت. + +ؚؚینید که چگونه ویرای؎گر ؎ما ممکن است ØšÙ‡ ؎ما کمک کند: + +* در Visual Studio Code: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* در PyCharm: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +؎ما ٟی؎نهاد های تکمیل خودکاری را خواهید گرفت که حتی ممکن است قؚلا آن را غیرممکن تصور میکردید. ØšÙ‡ عنوان مثال کلید `price` در داخل ؚدنه JSON (که میتوانست تودرتو نیز ؚا؎د) که از یک درخواست آمده است. + +دیگر خؚری از تایٟ کلید ا؎تؚاهی، ؚرگ؎تن ØšÙ‡ مستندات یا ٟایین ؚالا رفتن ؚرای فهمیدن اینکه ؎ما از `username` یا `user_name` استفاده کرده اید نیست. + +### مختصر + +FastAPI **ٟی؎ فرض** های معقولی ؚرای همه چیز دارد، ؚا قاؚلیت تن؞یمات اختیاری در همه جا. تمام ٟارامترها را میتوانید ؚرای انجام انچه نیاز دارید و ؚرای تعریف API مورد نیاز خود ØšÙ‡ خوؚی تن؞یم کنید. + +اما ØšÙ‡ طور ٟی؎ فرض، همه چیز **کار میکند**. + +### اعتؚارسنجی + +* اعتؚارسنجی ؚرای ؚی؎تر (یا همه؟) **data type** های ٟایتون، ؎امل: + + * JSON objects (`dict`) + * آرایه های (‍‍‍‍`list`) JSON ؚا قاؚلیت م؎خص سازی تایٟ ایتم های درون لیست. + * فیلد های ر؎ته (`str`)، ØšÙ‡ همراه م؎خص سازی حداقل و حداکثر طول ر؎ته. + * اعداد (‍‍`int`,`float`) ؚا حداقل و حداکثر مقدار و غیره. + +* اعتؚارسنجی ؚرای تایٟ های عجیؚ تر، مثل: + * URL. + * Email. + * UUID. + * و غیره. + +تمام اعتؚارسنجی ها توسط کتاؚخانه اثؚات ؎ده و قدرتمند **Pydantic** انجام می؎ود. + +### امنیت و احراز هویت + +امنیت و احرازهویت ؚدون هیچگونه ارتؚاط و مصالحه ای ؚا ٟایگاه های داده یا مدل های داده ایجاد ؎ده اند. + +تمام طرح های امنیتی در OpenAPI تعریف ؎ده اند، از جمله: + +* . +* **OAuth2** (همچنین ؚا **JWT tokens**). آموز؎ را در [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=\_blank} م؎اهده کنید. +* کلید های API: + * Headers + * Query parameters + * Cookies، و غیره. + +ØšÙ‡ علاوه تمام ویژگی های امنیتی از **Statlette** (؎امل **session cookies**) + +همه اینها ØšÙ‡ عنوان اؚزارها و اجزای قاؚل استفاده ای ساخته ؎ده اند که ØšÙ‡ راحتی ؚا سیستم های ؎ما، مخازن داده، ٟایگاه های داده راؚطه ای و NoSQL و غیره ادغام می؎وند. + +### Dependency Injection + +FastAPI ؎امل یک سیستم Dependency Injection ؚسیار آسان اما ؚسیار قدرتمند است. + +* حتی واؚستگی ها نیز میتوانند واؚستگی هایی دا؎ته ؚا؎ند و یک سلسله مراتؚ یا **"گرافی" از واؚستگی ها** ایجاد کنند. + +* همه چیز توسط فریم ورک **ØšÙ‡ طور خودکار اداره می؎ود** + +* همه واؚستگی ها میتوانند ØšÙ‡ داده های request ها نیاز دا؎ته ؚا؎ند و مستندات خودکار و محدودیت های path operation را **افزای؎** دهند. + +* ؚا قاؚلیت **اعتؚارسنجی خودکار** حتی ؚرای path operation parameter های تعریف ؎ده در واؚستگی ها. + +* ٟ؎تیؚانی از سیستم های ٟیچیده احرازهویت کارؚر، **اتصالات ٟایگاه داده** و غیره. + +* ؚدون هیچ ارتؚاطی ؚا دیتاؚیس ها، فرانت اند و غیره. اما ادغام آسان و راحت ؚا همه آنها. + +### ٟلاگین های نامحدود + +یا ØšÙ‡ عؚارت دیگر، هیچ نیازی ØšÙ‡ آنها نیست، کد موردنیاز خود را وارد و استفاده کنید. + +هر یکٟارچه سازی ØšÙ‡ گونه ای طراحی ؎ده است که استفاده از آن ؚسیار ساده ؚا؎د (ؚا واؚستگی ها) که میتوانید ؚا استفاده از همان ساختار و رو؎ی که ؚرای _path operation_ های خود استفاده کرده اید تنها در Û² خط کد "ٟلاگین" ؚرنامه خودتان را ایجاد کنید. + +### تست ؎ده + +* 100% ٟو؎؎ تست. + +* 100% کد ؚر اساس type annotate ها. + +* استفاده ؎ده در اٟلیکی؎ن های تولید + +## ویژگی های Starlette + +**FastAPI** کاملا (و ؚراساس) ؚا Starlette سازگار است. ؚناؚراین، هرکد اضافی Starlette که دارید، نیز کار خواهد کرد. + +‍‍`FastAPI` در واقع یک زیرکلاس از `Starlette` است. ؚناؚراین اگر از Ù‚ØšÙ„ Starlette را می؎ناسید یا ؚا آن کار کرده اید، ؚی؎تر قاؚلیت ها ØšÙ‡ همین رو؎ کار خواهد کرد. + +ؚا **FastAPI** ؎ما تمام ویژگی های **Starlette** را خواهید دا؎ت (زیرا FastAPI یک نسخه و نمونه ØšÙ‡ تمام معنا از Starlette است): + +* عملکرد ØšÙ‡ طورجدی چ؎مگیر. این یکی از سریعترین فریم ورک های موجود در ٟایتون است که همتراز ؚا **نود جی اس** و **گو** است. +* ٟ؎تیؚانی از **WebSocket**. +* تسک های درجریان در ٟس زمینه. +* رویداد های راه اندازی و متوفق ؎دن. +* تست کلاینت ساخته ؎ده ØšÙ‡ روی HTTPX. +* **CORS**, GZip, فایل های استاتیک, ٟاسخ های جریانی. +* ٟ؎تیؚانی از **ن؎ست ها و کوکی ها**. +* 100% ٟو؎؎ ؚا تست. +* 100% کد ؚراساس type annotate ها. + +## ویژگی های Pydantic + +**FastAPI** کاملا (و ؚراساس) ؚا Pydantic سازگار است. ؚناؚراین هرکد Pydantic اضافی که دا؎ته ؚا؎ید، نیز کار خواهد کرد. + +از جمله کتاؚخانه های خارجی نیز مؚتنی ؚر Pydantic میتوان ØšÙ‡ ORM و ODM ها ؚرای دیتاؚیس ها ا؎اره کرد. + +این همچنین ØšÙ‡ این معناست که در خیلی از موارد میتوانید همان اؚجکتی که از request میگیرید را **مستقیما ØšÙ‡ دیتاؚیس** ؚفرستید زیرا همه چیز ØšÙ‡ طور خودکار تأیید می؎ود. + +همین امر ؚرعکس نیز صدق می‌کند، در ؚسیاری از موارد ؎ما می‌توانید اؚجکتی را که از ٟایگاه داده دریافت می‌کنید را **مستقیماً ØšÙ‡ کارؚر** ارسال کنید. + +ؚا FastAPI ؎ما تمام ویژگی های Pydantic را دراختیار دارید (زیرا FastAPI ؚرای تمام ؚخ؎ مدیریت دیتا ؚر اساس Pydantic عمل میکند): + +* **خؚری از گیج ؎دن نیست**: + * هیچ زؚان خردی ؚرای یادگیری تعریف طرحواره های جدید وجود ندارد. + * اگر تایٟ های ٟایتون را می؎ناسید، نحوه استفاده از Pydantic را نیز میدانید. +* ØšÙ‡ خوؚی ؚا **IDE/linter/مغز** ؎ما عمل میکند: + * ØšÙ‡ این دلیل که ساختار داده Pydantic فقط نمونه هایی از کلاس هایی هستند که ؎ما تعریف میکنید، تکمیل خودکار، mypy، linting و م؎اهده ؎ما ؚاید ØšÙ‡ درستی ؚا داده های معتؚر ؎ما کار کنند. +* اعتؚار سنجی **ساختارهای ٟیچیده**: + * استفاده از مدل های سلسله مراتؚی Pydantic, `List` و `Dict` کتاؚخانه `typing` ٟایتون و غیره. + * و اعتؚارسنج ها اجازه میدهند که طرحواره های داده ٟیچیده ØšÙ‡ طور واضح و آسان تعریف، ؚررسی و ؚر ٟایه JSON مستند ؎وند. + * ؎ما میتوانید اؚجکت های عمیقا تودرتو JSON را که همگی تایید ؎ده و annotated ؎ده اند را دا؎ته ؚا؎ید. +* **قاؚل توسعه**: + * Pydantic اجازه میدهد تا data type های سفار؎ی تعریف ؎وند یا میتوانید اعتؚارسنجی را ؚا رو؎ هایی ØšÙ‡ روی مدل ها ؚا validator decorator گستر؎ دهید. +* 100% ٟو؎؎ ؚا تست. From aa53a48fe364a7c9de92479437ae275448b6e456 Mon Sep 17 00:00:00 2001 From: Kay Jan Date: Wed, 10 Jan 2024 00:21:54 +0800 Subject: [PATCH 081/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`openapi-callbacks.md`=20(#10673)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/openapi-callbacks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 37339eae575cf..03429b187fe55 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -38,7 +38,7 @@ This part is pretty normal, most of the code is probably already familiar to you !!! tip The `callback_url` query parameter uses a Pydantic URL type. -The only new thing is the `callbacks=messages_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. +The only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. ## Documenting the callback From 6efd537204f4b59e7ef7ba013c9506a97e09f01b Mon Sep 17 00:00:00 2001 From: Sumin Kim <42088290+Eeap@users.noreply.github.com> Date: Wed, 10 Jan 2024 01:23:09 +0900 Subject: [PATCH 082/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20=20Update=20Python?= =?UTF-8?q?=20version=20in=20`docs/ko/docs/index.md`=20(#10680)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 7ce938106d8bb..c09b538cf4726 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -323,7 +323,7 @@ def update_item(item_id: int, item: Item): 새로욎 묞법, 특정 띌읎람러늬의 메소드나 큎래슀 등을 ë°°ìšž 필요가 없습니닀. -ê·žì € 표쀀 **Python 3.6+**입니닀. +ê·žì € 표쀀 **Python 3.8+** 입니닀. 예륌 듀얎, `int`에 대핎선: From ed3e79be77021edecb56041a558e80e8754db849 Mon Sep 17 00:00:00 2001 From: Clarence Date: Tue, 9 Jan 2024 17:30:58 +0100 Subject: [PATCH 083/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typos=20in?= =?UTF-8?q?=20`/docs/reference/exceptions.md`=20and=20`/en/docs/reference/?= =?UTF-8?q?status.md`=20(#10809)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/reference/exceptions.md | 2 +- docs/en/docs/reference/status.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/reference/exceptions.md b/docs/en/docs/reference/exceptions.md index adc9b91ce5659..7c480834928f9 100644 --- a/docs/en/docs/reference/exceptions.md +++ b/docs/en/docs/reference/exceptions.md @@ -3,7 +3,7 @@ These are the exceptions that you can raise to show errors to the client. When you raise an exception, as would happen with normal Python, the rest of the -excecution is aborted. This way you can raise these exceptions from anywhere in the +execution is aborted. This way you can raise these exceptions from anywhere in the code to abort a request and show the error to the client. You can use: diff --git a/docs/en/docs/reference/status.md b/docs/en/docs/reference/status.md index 54fba9387e664..a238007923be8 100644 --- a/docs/en/docs/reference/status.md +++ b/docs/en/docs/reference/status.md @@ -8,7 +8,7 @@ from fastapi import status `status` is provided directly by Starlette. -It containes a group of named constants (variables) with integer status codes. +It contains a group of named constants (variables) with integer status codes. For example: From 04dbcf416c881f4320b8263e840f188e7d494ca9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 16:31:04 +0000 Subject: [PATCH 084/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 83cae1ddaeca9..345f85ed6fbd9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Fix typo in `fastapi/routing.py` . PR [#10520](https://github.com/tiangolo/fastapi/pull/10520) by [@sepsh](https://github.com/sepsh). * 📝 Replace HTTP code returned in case of existing user error in docs for testing. PR [#4482](https://github.com/tiangolo/fastapi/pull/4482) by [@TristanMarion](https://github.com/TristanMarion). * 📝 Add blog for FastAPI & Supabase. PR [#6018](https://github.com/tiangolo/fastapi/pull/6018) by [@theinfosecguy](https://github.com/theinfosecguy). * 📝 Update example source files for SQL databases with SQLAlchemy. PR [#9508](https://github.com/tiangolo/fastapi/pull/9508) by [@s-mustafa](https://github.com/s-mustafa). From c2dc0252b01e767fcafd80d9d6c1d03e4fd48f59 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 16:38:21 +0000 Subject: [PATCH 085/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 345f85ed6fbd9..7115fa3f6049c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Translations +* 🌐 Add Persian translation for `docs/fa/docs/features.md`. PR [#5887](https://github.com/tiangolo/fastapi/pull/5887) by [@amirilf](https://github.com/amirilf). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/additional-responses.md`. PR [#10325](https://github.com/tiangolo/fastapi/pull/10325) by [@ShuibeiC](https://github.com/ShuibeiC). * 🌐 Fix typos in Russian translations for `docs/ru/docs/tutorial/background-tasks.md`, `docs/ru/docs/tutorial/body-nested-models.md`, `docs/ru/docs/tutorial/debugging.md`, `docs/ru/docs/tutorial/testing.md`. PR [#10311](https://github.com/tiangolo/fastapi/pull/10311) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-files.md`. PR [#10332](https://github.com/tiangolo/fastapi/pull/10332) by [@AlertRED](https://github.com/AlertRED). From 6c15776406ac238a7089b7644dca21affe4cf8d0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 16:50:06 +0000 Subject: [PATCH 086/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7115fa3f6049c..deb2b285dacd7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Fix typo in `openapi-callbacks.md`. PR [#10673](https://github.com/tiangolo/fastapi/pull/10673) by [@kayjan](https://github.com/kayjan). * ✏ Fix typo in `fastapi/routing.py` . PR [#10520](https://github.com/tiangolo/fastapi/pull/10520) by [@sepsh](https://github.com/sepsh). * 📝 Replace HTTP code returned in case of existing user error in docs for testing. PR [#4482](https://github.com/tiangolo/fastapi/pull/4482) by [@TristanMarion](https://github.com/TristanMarion). * 📝 Add blog for FastAPI & Supabase. PR [#6018](https://github.com/tiangolo/fastapi/pull/6018) by [@theinfosecguy](https://github.com/theinfosecguy). From 5e5cabefe18e33c6087043af640d98e089884b9e Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 16:51:05 +0000 Subject: [PATCH 087/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index deb2b285dacd7..d6bacfe957061 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Translations +* ✏ Update Python version in `docs/ko/docs/index.md`. PR [#10680](https://github.com/tiangolo/fastapi/pull/10680) by [@Eeap](https://github.com/Eeap). * 🌐 Add Persian translation for `docs/fa/docs/features.md`. PR [#5887](https://github.com/tiangolo/fastapi/pull/5887) by [@amirilf](https://github.com/amirilf). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/additional-responses.md`. PR [#10325](https://github.com/tiangolo/fastapi/pull/10325) by [@ShuibeiC](https://github.com/ShuibeiC). * 🌐 Fix typos in Russian translations for `docs/ru/docs/tutorial/background-tasks.md`, `docs/ru/docs/tutorial/body-nested-models.md`, `docs/ru/docs/tutorial/debugging.md`, `docs/ru/docs/tutorial/testing.md`. PR [#10311](https://github.com/tiangolo/fastapi/pull/10311) by [@AlertRED](https://github.com/AlertRED). From 43489beb98555374949b451054e1cd02bca267eb Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 17:00:36 +0000 Subject: [PATCH 088/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d6bacfe957061..7b1b861b277fc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Fix typos in `/docs/reference/exceptions.md` and `/en/docs/reference/status.md`. PR [#10809](https://github.com/tiangolo/fastapi/pull/10809) by [@clarencepenz](https://github.com/clarencepenz). * ✏ Fix typo in `openapi-callbacks.md`. PR [#10673](https://github.com/tiangolo/fastapi/pull/10673) by [@kayjan](https://github.com/kayjan). * ✏ Fix typo in `fastapi/routing.py` . PR [#10520](https://github.com/tiangolo/fastapi/pull/10520) by [@sepsh](https://github.com/sepsh). * 📝 Replace HTTP code returned in case of existing user error in docs for testing. PR [#4482](https://github.com/tiangolo/fastapi/pull/4482) by [@TristanMarion](https://github.com/TristanMarion). From e98689434449c4ec667df42b798bcf4b2359b399 Mon Sep 17 00:00:00 2001 From: Rostyslav Date: Tue, 9 Jan 2024 19:04:42 +0200 Subject: [PATCH 089/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/index.md`=20(#10362)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/uk/docs/index.md | 465 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 465 insertions(+) create mode 100644 docs/uk/docs/index.md diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md new file mode 100644 index 0000000000000..fad693f79deb2 --- /dev/null +++ b/docs/uk/docs/index.md @@ -0,0 +1,465 @@ +

+ FastAPI +

+

+ ГПтПвОй ЎП прПЎакшОМу, вОсПкПпрПЎуктОвМОй, прПстОй у вОвчеММі та швОЎкОй Ўля МапОсаММя кПЎу фрейЌвПрк +

+

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

+ +--- + +**ДПкуЌеМтація**: https://fastapi.tiangolo.com + +**ПрПграЌМОй кПЎ**: https://github.com/tiangolo/fastapi + +--- + +FastAPI - це сучасМОй, швОЎкОй (вОсПкПпрПЎуктОвМОй), вебфрейЌвПрк Ўля ствПреММя API за ЎПпПЌПгПю Python 3.8+,в ПсМПві якПгП лежОть стаМЎартМа аМПтація тОпів Python. + +КлючПві ПсПблОвПсті: + +* **КвОЎкОй**: Дуже вОсПка прПЎуктОвМість, Ма рівМі з **NodeJS** та **Go** (завЎякО Starlette та Pydantic). [ОЎОМ із МайшвОЎшОх фрейЌвПрків](#performance). + +* **КвОЎке МапОсаММя кПЎу**: ПрОшвОЎшує рПзрПбку фуМкціПМалу прОблОзМП Ма 200%-300%. * +* **МеМше пПЌОлПк**: ЗЌеМшОть кількість пПЌОлПк спрОчОМеМОх люЎОМПю (рПзрПбМОкПЌ) Ма 40%. * +* **ІМтуїтОвМОй**: ЧуЎПва піЎтрОЌка реЎактПраЌО кПЎу. ДПпПвМеММя всюЎО. ЗЌеМште час Ма МалагПЎжеММя. +* **ПрПстОй**: СпрПектПваМОй, Ўля легкПгП вОкПрОстаММя та МавчаММя. ЗМаЎПбОться ЌеМше часу Ма чОтаММя ЎПкуЌеМтації. +* **КПрПткОй**: ЗвеЎе ЎП ЌіМіЌуЌу ЎублюваММя кПЎу. КПжеМ ПгПлПшеМОй параЌетр ЌПже вОкПМуватО кілька фуМкцій. +* **НаЎійМОй**: ВО ЌатОЌете стабільМОй кПЎ гПтПвОй ЎП прПЎакшОМу з автПЌатОчМПю іМтерактОвМПю ЎПкуЌеМтацією. +* **СтаМЎартОзПваМОй**: ОсМПваМОй та пПвМістю суЌісМОй з віЎкрОтОЌО стаМЎартаЌО Ўля API: OpenAPI (пПпереЎМьП віЎПЌОй як Swagger) та JSON Schema. + +* ПціМка Ма ПсМПві тестів вМутрішМьПї кПЌаМЎО рПзрПбМОків, ствПреММя прПЎуктПвОх застПсуМків. + +## СпПМсПрО + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Other sponsors + +## ВражеММя + +"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_I’m over the moon excited about **FastAPI**. It’s so fun!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" + +"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +## **Typer**, FastAPI CLI + + + +СтвПрюючО CLI застПсуМПк Ўля вОкПрОстаММя в терЌіМалі, заЌість веб-API зверМіть увагу Ма **Typer**. + +**Typer** є ЌПлПЎшОЌ братПЌ FastAPI. І це **FastAPI Ўля CLI**. ⌚ 🚀 + +## ВОЌПгО + +Python 3.8+ + +FastAPI стПїть Ма плечах гігаМтів: + +* Starlette Ўля web частОМО. +* Pydantic Ўля частОМО ЎаМОх. + +## ВставМПвлеММя + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +ВаЌ такПж зМаЎПбОться сервер ASGI Ўля прПЎакшОМу, МапрОклаЎ Uvicorn абП Hypercorn. + +
+ +```console +$ pip install uvicorn[standard] + +---> 100% +``` + +
+ +## ПрОклаЎ + +### СтвПріть + +* СтвПріть файл `main.py` з: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+АбП вОкПрОстайте async def... + +ЯкщП ваш кПЎ вОкПрОстПвує `async` / `await`, скПрОстайтеся `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**ПрОЌітка**: + +СтОкМувшОсь з прПблеЌаЌО, Ме зайвОЌ буЎе ПзМайПЌОтОся з рПзЎілПЌ _"In a hurry?"_ прП `async` та `await` у ЎПкуЌеМтації. + +
+ +### Запустіть + +Запустіть server з: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+ПрП кПЌаМЎО uvicorn main:app --reload... + +КПЌаМЎа `uvicorn main:app` пПсОлається Ма: + +* `main`: файл `main.py` ("МПЎуль" Python). +* `app`: Пб’єкт ствПреМОй усереЎОМі `main.py` ряЎкПЌ `app = FastAPI()`. +* `--reload`: перезапускає сервер після зЌіМО кПЎу. ВОкПрОстПвуйте вОключМП Ўля рПзрПбкО. + +
+ +### Перевірте + +ВіЎкрОйте браузер та ввеЎіть аЎресу http://127.0.0.1:8000/items/5?q=somequery. + +ВО пПбачОте у віЎпПвіЎь пПЎібМОй JSON: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +ВО вже ствПрОлО API, якОй: + +* ОтрОЌує HTTP запОтО за _шляхаЌО_ `/` та `/items/{item_id}`. +* ОбОЎва _шляхО_ прОйЌають `GET` Пперації (такПж віЎПЌі як HTTP _ЌетПЎО_). +* _Клях_ `/items/{item_id}` ЌістОть _параЌетр шляху_ `item_id` якОй Ќає бутО тОпу `int`. +* _Клях_ `/items/{item_id}` ЌістОть МеПбПвʌязкПвОй `str` _параЌетр запОту_ `q`. + +### ІМтерактОвМі ЎПкуЌеМтації API + +ПерейЎеЌП сюЎО http://127.0.0.1:8000/docs. + +ВО пПбачОте автПЌатОчМу іМтерактОвМу API ЎПкуЌеМтацію (ствПреМу завЎякО Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### АльтерМатОвМі ЎПкуЌеМтації API + +Тепер перейЎеЌП сюЎО http://127.0.0.1:8000/redoc. + +ВО пПбачОте альтерМатОвМу автПЌатОчМу ЎПкуЌеМтацію (ствПреМу завЎякО ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## ПрОклаЎ ПМПвлеММя + +Тепер ЌПЎОфікуйте файл `main.py`, щПб ПтрОЌатО вЌіст запОту `PUT`. + +ОгПлПшуйте вЌіст запОту за ЎПпПЌПгПю стаМЎартМОх тОпів Python завЎякО Pydantic. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +Сервер пПвОМеМ автПЌатОчМП перезаваМтажуватОся (тПЌу щП ВО ЎПЎалО `--reload` ЎП `uvicorn` кПЌаМЎО вОще). + +### ОМПвлеММя іМтерактОвМПї API ЎПкуЌеМтації + +Тепер перейЎеЌП сюЎО http://127.0.0.1:8000/docs. + +* ІМтерактОвМа ЎПкуЌеМтація API буЎе автПЌатОчМП ПМПвлеМа, включаючО МПвОй вЌіст: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* НатОсМіть кМПпку "Try it out", це ЎПзвПлОть ваЌ запПвМОтО параЌетрО та безпПсереЎМьП взаєЌПЎіятО з API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* ППтіЌ МатОсМіть кМПпку "Execute", іМтерфейс кПрОстувача зв'яжеться з вашОЌ API, МаЎішле параЌетрО, у віЎпПвіЎь ПтрОЌає результатО та пПкаже їх Ма екраМі: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### ОМПвлеММя альтерМатОвМПї API ЎПкуЌеМтації + +Зараз перейЎеЌП http://127.0.0.1:8000/redoc. + +* АльтерМатОвМа ЎПкуЌеМтація такПж пПказуватОЌе МПвОй параЌетр і вЌіст запОту: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### ПіЎсуЌкО + +ТакОЌ чОМПЌ, ВО **ПЎОМ раз** ПгПлПшуєте тОпО параЌетрів, тіла тПщП, як параЌетрО фуМкції. + +ВО рПбОте це за ЎПпПЌПгПю стаМЎартМОх сучасМОх тОпів Python. + +ВаЌ Ме пПтрібМП вОвчатО МПвОй сОМтаксОс, ЌетПЎО чО класО кПМкретМПї бібліПтекО тПщП. + +ВОкПрОстПвуючО стаМЎартМОй **Python 3.8+**. + +НапрОклаЎ, Ўля `int`: + +```Python +item_id: int +``` + +абП Ўля більш склаЎМПї ЌПЎелі `Item`: + +```Python +item: Item +``` + +...і з цОЌ єЎОМОЌ ПгПлПшеММяЌ ВО ПтрОЌуєте: + +* ПіЎтрОЌку реЎактПра, включаючО: + * ВаріаМтО запПвМеММя. + * Перевірку тОпів. +* Перевірку ЎаМОх: + * АвтПЌатОчМі та зрПзуЌілі пПЌОлкО, у разі МекПректМОх ЎаМОх. + * Перевірка Мавіть Ўля JSON з вОсПкОЌ рівМеЌ вклаЎеМПсті. +* ПеретвПреММя вхіЎМОх ЎаМОх: з Ќережі ЎП ЎаМОх і тОпів Python. ЧОтаММя з: + * JSON. + * ПараЌетрів шляху. + * ПараЌетрів запОту. + * Cookies. + * Headers. + * Forms. + * Ѐайлів. +* ПеретвПреММя вОхіЎМОх ЎаМОх: з тОпів і ЎаМОх Python ЎП ЌережевОх ЎаМОх (як JSON): + * КПМвертація Python тОпів (`str`, `int`, `float`, `bool`, `list`, тПщП). + * `datetime` Пб'єктО. + * `UUID` Пб'єктО. + * МПЎелі базО ЎаМОх. + * ...та багатП іМшПгП. +* АвтПЌатОчМу іМтерактОвМу ЎПкуЌеМтацію API, включаючО 2 альтерМатОвМі іМтерфейсО кПрОстувача: + * Swagger UI. + * ReDoc. + +--- + +ППвертаючОсь ЎП пПпереЎМьПгП прОклаЎу кПЎу, **FastAPI**: + +* ПіЎтверЎОть МаявМість `item_id` у шляху Ўля запОтів `GET` та `PUT`. +* ПіЎтверЎОть, щП `item_id` Ќає тОп `int` Ўля запОтів `GET` and `PUT`. + * ЯкщП це Ме так, клієМт пПбачОть кПрОсМу, зрПзуЌілу пПЌОлку. +* ПеревірОть, чО є МеПбПв'язкПвОй параЌетр запОту з МазвПю `q` (а саЌе `http://127.0.0.1:8000/items/foo?q=somequery`) Ўля запОтів `GET`. + * ОскількО параЌетр `q` ПгПлПшеМП як `= None`, віМ МеПбПв'язкПвОй. + * За віЎсутМПсті `None` віМ був бО ПбПв'язкПвОЌ (як і вЌіст у вОпаЎку з `PUT`). +* Для запОтів `PUT` із `/items/{item_id}`, чОтає вЌіст як JSON: + * ПеревірОть, чО Ќає ПбПв'язкПвОй атрОбут `name` тОп `str`. + * ПеревірОть, чО Ќає ПбПв'язкПвОй атрОбут `price` тОп `float`. + * ПеревірОть, чО ісМує МеПбПв'язкПвОй атрОбут `is_offer` та чО Ќає віМ тОп `bool`. + * Усе це такПж працюватОЌе Ўля глОбПкП вклаЎеМОх Пб'єктів JSON. +* АвтПЌатОчМП кПМвертує із та в JSON. +* ДПкуЌеМтує все за ЎПпПЌПгПю OpenAPI, якОй ЌПже бутО вОкПрОстаМП в: + * ІМтерактОвМОх сОстеЌах ЎПкуЌеМтації. + * СОстеЌах автПЌатОчМПї геМерації клієМтськПгП кПЎу Ўля багатьПх ЌПв. +* НаЎає безпПсереЎМьП 2 вебіМтерфейсО іМтерактОвМПї ЎПкуЌеМтації. + +--- + +МО лОше трішкО ЎПтПркМулОся ЎП кПЎу, але ВО вже Ќаєте уявлеММя прП те, як все працює. + +СпрПбуйте зЌіМОтО ряЎПк: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...із: + +```Python + ... "item_name": item.name ... +``` + +...Ма: + +```Python + ... "item_price": item.price ... +``` + +...і пПбачОте, як ваш реЎактПр автПЌатОчМП запПвМюватОЌе атрОбутО та зМатОЌе їхМі тОпО: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Для більш пПвМПгП ПзМайПЌлеММя з ЎПЎаткПвОЌО фуМкціяЌО, перегляМьте ТутПріал - ППсібМОк КПрОстувача. + +**Spoiler alert**: тутПріал - пПсібМОк кПрОстувача ЌістОть: + +* ОгПлПшеММя **параЌетрів** з іМшОх Ќісць як: **headers**, **cookies**, **form fields** та **files**. +* Як встаМПвОтО **перевірку ПбЌежеМь** як `maximum_length` абП `regex`. +* Дуже пПтужМа і прПста у вОкПрОстаММі сОстеЌа **ІМ'єкція ЗалежМПстей**. +* Безпека та автеМтОфікація, включаючО піЎтрОЌку **OAuth2** з **JWT tokens** та **HTTP Basic** автеМтОфікацію. +* ДПскПМаліші (але ПЎМакПвП прПсті) техМікО Ўля ПгПлПшеММя **глОбПкП вклаЎеМОх ЌПЎелей JSON** (завЎякО Pydantic). +* БагатП ЎПЎаткПвОх фуМкцій (завЎякО Starlette) як-Пт: + * **WebSockets** + * МаЎзвОчайМП прПсті тестО Ма ПсМПві HTTPX та `pytest` + * **CORS** + * **Cookie Sessions** + * ...та більше. + +## ПрПЎуктОвМість + +НезалежМі тестО TechEmpower пПказують щП застПсуМкО **FastAPI**, які працюють піЎ керуваММяЌ Uvicorn є ПЎМОЌО з МайшвОЎшОх сереЎ ЎПступМОх фрейЌвПрків в Python, пПступаючОсь лОше Starlette та Uvicorn (які вМутрішМьП вОкПрОстПвуються в FastAPI). (*) + +ЩПб ЎізМатОся більше прП це, перегляМьте рПзЎіл Benchmarks. + +## НеПбПв'язкПві залежМПсті + +Pydantic вОкПрОстПвує: + +* email_validator - Ўля валіЎації електрПММПї пПштО. +* pydantic-settings - Ўля управліММя МалаштуваММяЌО. +* pydantic-extra-types - Ўля ЎПЎаткПвОх тОпів, щП ЌПжуть бутО вОкПрОстаМі з Pydantic. + + +Starlette вОкПрОстПвує: + +* httpx - НеПбхіЎМП, якщП ВО хПчете вОкПрОстПвуватО `TestClient`. +* jinja2 - НеПбхіЎМП, якщП ВО хПчете вОкПрОстПвуватО шаблПМО як кПМфігурацію за заЌПвчуваММяЌ. +* python-multipart - НеПбхіЎМП, якщП ВО хПчете піЎтрОЌуватО "рПзбір" фПрЌО за ЎПпПЌПгПю `request.form()`. +* itsdangerous - НеПбхіЎМП Ўля піЎтрОЌкО `SessionMiddleware`. +* pyyaml - НеПбхіЎМП Ўля піЎтрОЌкО Starlette `SchemaGenerator` (йЌПвірМП, ваЌ це Ме пПтрібМП з FastAPI). +* ujson - НеПбхіЎМП, якщП ВО хПчете вОкПрОстПвуватО `UJSONResponse`. + +FastAPI / Starlette вОкПрОстПвують: + +* uvicorn - Ўля сервера, якОй заваМтажує та ПбслугПвує вашу прПграЌу. +* orjson - НеПбхіЎМП, якщП ВО хПчете вОкПрОстПвуватО `ORJSONResponse`. + +ВО ЌПжете встаМПвОтО все це за ЎПпПЌПгПю `pip install fastapi[all]`. + +## ЛіцеМзія + +Њей прПєкт ліцеМзПваМП згіЎМП з уЌПваЌО ліцеМзії MIT. From 33e57e6f022a24f4aec966a6735754c1c18d9245 Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov Date: Tue, 9 Jan 2024 20:06:10 +0300 Subject: [PATCH 090/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/request-forms-and-files.md`?= =?UTF-8?q?=20(#10347)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- .../docs/tutorial/request-forms-and-files.md | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 docs/ru/docs/tutorial/request-forms-and-files.md diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md new file mode 100644 index 0000000000000..3f587c38a3ae7 --- /dev/null +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,69 @@ +# Ѐайлы О фПрЌы в запрПсе + +Вы ЌПжете ПпреЎелять файлы О пПля фПрЌы ПЎМПвреЌеММП, ОспПльзуя `File` О `Form`. + +!!! info "ДПпПлМОтельМая ОМфПрЌацОя" + ЧтПбы пПлучать загружеММые файлы О/ОлО ЎаММые фПрЌ, сМачала устаМПвОте `python-multipart`. + + НапрОЌер: `pip install python-multipart`. + +## ИЌпПртОруйте `File` О `Form` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} + ``` + +## ОпреЎелОте параЌетры `File` О `Form` + +СПзЎайте параЌетры файла О фПрЌы такОЌ же ПбразПЌ, как Ўля `Body` ОлО `Query`: + +=== "Python 3.9+" + + ```Python hl_lines="10-12" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="9-11" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + ПреЎпПчтОтельМее ОспПльзПвать версОю с аММПтацОей, еслО этП вПзЌПжМП. + + ```Python hl_lines="8" + {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} + ``` + +Ѐайлы О пПля фПрЌы буЎут загружеМы в вОЎе ЎаММых фПрЌы, О вы пПлучОте файлы О пПля фПрЌы. + +Вы ЌПжете ПбъявОть МекПтПрые файлы как `bytes`, а МекПтПрые - как `UploadFile`. + +!!! warning "ВМОЌаМОе" + Вы ЌПжете ПбъявОть МескПлькП параЌетрПв `File` О `Form` в ПперацОО *path*, МП вы Ме ЌПжете также ПбъявОть пПля `Body`, кПтПрые вы ПжОЎаете пПлучОть в вОЎе JSON, так как запрПс буЎет ОЌеть телП, закПЎОрПваММПе с пПЌПщью `multipart/form-data` вЌестП `application/json`. + + ЭтП Ме ПграМОчеМОе **Fast API**, этП часть прПтПкПла HTTP. + +## РезюЌе + +ИспПльзуйте `File` О `Form` вЌесте, кПгЎа МеПбхПЎОЌП пПлучОть ЎаММые О файлы в ПЎМПЌ запрПсе. From d2c7ffb447f4007e35c3bc102ef2ce13695ea5d8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 17:31:25 +0000 Subject: [PATCH 091/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7b1b861b277fc..eb6435235ea79 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/index.md`. PR [#10362](https://github.com/tiangolo/fastapi/pull/10362) by [@rostik1410](https://github.com/rostik1410). * ✏ Update Python version in `docs/ko/docs/index.md`. PR [#10680](https://github.com/tiangolo/fastapi/pull/10680) by [@Eeap](https://github.com/Eeap). * 🌐 Add Persian translation for `docs/fa/docs/features.md`. PR [#5887](https://github.com/tiangolo/fastapi/pull/5887) by [@amirilf](https://github.com/amirilf). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/additional-responses.md`. PR [#10325](https://github.com/tiangolo/fastapi/pull/10325) by [@ShuibeiC](https://github.com/ShuibeiC). From d62b3ea69c70c77b570dafe175b6a4062ea545b2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 17:32:21 +0000 Subject: [PATCH 092/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index eb6435235ea79..bea478c2b2a8d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-forms-and-files.md`. PR [#10347](https://github.com/tiangolo/fastapi/pull/10347) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Ukrainian translation for `docs/uk/docs/index.md`. PR [#10362](https://github.com/tiangolo/fastapi/pull/10362) by [@rostik1410](https://github.com/rostik1410). * ✏ Update Python version in `docs/ko/docs/index.md`. PR [#10680](https://github.com/tiangolo/fastapi/pull/10680) by [@Eeap](https://github.com/Eeap). * 🌐 Add Persian translation for `docs/fa/docs/features.md`. PR [#5887](https://github.com/tiangolo/fastapi/pull/5887) by [@amirilf](https://github.com/amirilf). From 6f43539d87406ea0afc52de3c54f352487024f6c Mon Sep 17 00:00:00 2001 From: Andrew Chang-DeWitt <11323923+andrew-chang-dewitt@users.noreply.github.com> Date: Tue, 9 Jan 2024 11:45:52 -0600 Subject: [PATCH 093/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20warning=20about=20?= =?UTF-8?q?lifecycle=20events=20with=20`AsyncClient`=20(#4167)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Marcelo Trylesinski --- docs/en/docs/advanced/async-tests.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index 9b39d70fca6a8..c79822d63e19b 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -84,6 +84,9 @@ response = client.get('/') !!! tip Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. +!!! warning + If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from https://github.com/florimondmanca/asgi-lifespan#usage. + ## Other Asynchronous Function Calls As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code. From 7dd944deda6433924712274b81743edc63f92bbb Mon Sep 17 00:00:00 2001 From: John Philip Date: Tue, 9 Jan 2024 20:49:58 +0300 Subject: [PATCH 094/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20article:=20"Buildi?= =?UTF-8?q?ng=20a=20RESTful=20API=20with=20FastAPI:=20Secure=20Signup=20an?= =?UTF-8?q?d=20Login=20Functionality=20Included"=20(#9733)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 35c9b6718ed76..d53afd7f9fac6 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ Articles: English: + - author: John Philip + author_link: https://medium.com/@amjohnphilip + link: https://python.plainenglish.io/building-a-restful-api-with-fastapi-secure-signup-and-login-functionality-included-45cdbcb36106 + title: "Building a RESTful API with FastAPI: Secure Signup and Login Functionality Included" - author: Keshav Malik author_link: https://theinfosecguy.xyz/ link: https://blog.theinfosecguy.xyz/building-a-crud-api-with-fastapi-and-supabase-a-step-by-step-guide From 809b21c849a4d84898fb59ea832bb77386ae3aec Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 18:12:12 +0000 Subject: [PATCH 095/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bea478c2b2a8d..839d84e81084d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add warning about lifecycle events with `AsyncClient`. PR [#4167](https://github.com/tiangolo/fastapi/pull/4167) by [@andrew-chang-dewitt](https://github.com/andrew-chang-dewitt). * ✏ Fix typos in `/docs/reference/exceptions.md` and `/en/docs/reference/status.md`. PR [#10809](https://github.com/tiangolo/fastapi/pull/10809) by [@clarencepenz](https://github.com/clarencepenz). * ✏ Fix typo in `openapi-callbacks.md`. PR [#10673](https://github.com/tiangolo/fastapi/pull/10673) by [@kayjan](https://github.com/kayjan). * ✏ Fix typo in `fastapi/routing.py` . PR [#10520](https://github.com/tiangolo/fastapi/pull/10520) by [@sepsh](https://github.com/sepsh). From e628e1928e18643196e8ae9a02f2f5ce0817c914 Mon Sep 17 00:00:00 2001 From: Takuma Yamamoto Date: Wed, 10 Jan 2024 03:13:02 +0900 Subject: [PATCH 096/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Update=20Python=20?= =?UTF-8?q?version=20in=20`index.md`=20in=20several=20languages=20(#10711)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/ja/docs/index.md | 4 ++-- docs/ko/docs/index.md | 2 +- docs/pl/docs/index.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index f340fdb87ebc5..22c31e7ca926e 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI は、Pythonの暙準である型ヒントに基づいおPython 3.6 以降でAPI を構築するための、モダンで、高速(高パフォヌマンス)な、Web フレヌムワヌクです。 +FastAPI は、Pythonの暙準である型ヒントに基づいおPython 3.8 以降でAPI を構築するための、モダンで、高速(高パフォヌマンス)な、Web フレヌムワヌクです。 䞻な特城: @@ -317,7 +317,7 @@ def update_item(item_id: int, item: Item): 新しい構文や特定のラむブラリのメ゜ッドやクラスなどを芚える必芁はありたせん。 -単なる暙準的な**3.6 以降の Python**です。 +単なる暙準的な**3.8 以降の Python**です。 䟋えば、`int`の堎合: diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index c09b538cf4726..594b092f7316f 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI는 현대적읎고, 빠륎며(고성능), 파읎썬 표쀀 타입 힌튞에 Ʞ쎈한 Python3.6+의 API륌 빌드하Ʞ 위한 웹 프레임워크입니닀. +FastAPI는 현대적읎고, 빠륎며(고성능), 파읎썬 표쀀 타입 힌튞에 Ʞ쎈한 Python3.8+의 API륌 빌드하Ʞ 위한 웹 프레임워크입니닀. 죌요 특징윌로: diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 43a20383ca1fd..49f5c2b011734 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI to nowoczesny, wydajny framework webowy do budowania API z uÅŒyciem Pythona 3.6+ bazujący na standardowym typowaniu Pythona. +FastAPI to nowoczesny, wydajny framework webowy do budowania API z uÅŒyciem Pythona 3.8+ bazujący na standardowym typowaniu Pythona. Kluczowe cechy: From cbd53f3bc8900b10b10d89dba895d8d7f15db7a5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 18:15:02 +0000 Subject: [PATCH 097/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 839d84e81084d..cf686b02a5be5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add article: "Building a RESTful API with FastAPI: Secure Signup and Login Functionality Included". PR [#9733](https://github.com/tiangolo/fastapi/pull/9733) by [@dxphilo](https://github.com/dxphilo). * 📝 Add warning about lifecycle events with `AsyncClient`. PR [#4167](https://github.com/tiangolo/fastapi/pull/4167) by [@andrew-chang-dewitt](https://github.com/andrew-chang-dewitt). * ✏ Fix typos in `/docs/reference/exceptions.md` and `/en/docs/reference/status.md`. PR [#10809](https://github.com/tiangolo/fastapi/pull/10809) by [@clarencepenz](https://github.com/clarencepenz). * ✏ Fix typo in `openapi-callbacks.md`. PR [#10673](https://github.com/tiangolo/fastapi/pull/10673) by [@kayjan](https://github.com/kayjan). From f226040d28621175477ee6b1273044f775ceac93 Mon Sep 17 00:00:00 2001 From: Dmitry Volodin Date: Tue, 9 Jan 2024 22:19:59 +0400 Subject: [PATCH 098/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typos=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/dependencies/dependencies-with-yield.?= =?UTF-8?q?md`=20(#10834)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 4ead4682cba9a..de87ba3156e54 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -160,7 +160,7 @@ The same way, you could raise an `HTTPException` or similar in the exit code, af {!> ../../../docs_src/dependencies/tutorial008b.py!} ``` -An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is ot create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. +An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is to create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. ## Execution of dependencies with `yield` @@ -249,7 +249,7 @@ with open("./somefile.txt") as f: print(contents) ``` -Underneath, the `open("./somefile.txt")` creates an object that is a called a "Context Manager". +Underneath, the `open("./somefile.txt")` creates an object that is called a "Context Manager". When the `with` block finishes, it makes sure to close the file, even if there were exceptions. From 0108b002f38f5179b29cc579e4bf8e5c3c282a00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 9 Jan 2024 22:20:37 +0400 Subject: [PATCH 099/217] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20(#10871)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/github_sponsors.yml | 159 +++++++++++++++---------- docs/en/data/people.yml | 192 +++++++++++++++---------------- 2 files changed, 190 insertions(+), 161 deletions(-) diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index 43b4b8c6b3280..713f229cf4de2 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -1,19 +1,25 @@ sponsors: -- - login: codacy +- - login: scalar + avatarUrl: https://avatars.githubusercontent.com/u/301879?v=4 + url: https://github.com/scalar + - login: codacy avatarUrl: https://avatars.githubusercontent.com/u/1834093?v=4 url: https://github.com/codacy - login: bump-sh avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 url: https://github.com/bump-sh + - login: Alek99 + avatarUrl: https://avatars.githubusercontent.com/u/38776361?u=bd6c163fe787c2de1a26c881598e54b67e2482dd&v=4 + url: https://github.com/Alek99 - login: cryptapi avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4 url: https://github.com/cryptapi - login: porter-dev avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 url: https://github.com/porter-dev - - login: fern-api - avatarUrl: https://avatars.githubusercontent.com/u/102944815?v=4 - url: https://github.com/fern-api + - login: andrew-propelauth + avatarUrl: https://avatars.githubusercontent.com/u/89474256?u=1188c27cb744bbec36447a2cfd4453126b2ddb5c&v=4 + url: https://github.com/andrew-propelauth - - login: nihpo avatarUrl: https://avatars.githubusercontent.com/u/1841030?u=0264956d7580f7e46687a762a7baa629f84cf97c&v=4 url: https://github.com/nihpo @@ -21,7 +27,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/65656077?v=4 url: https://github.com/ObliviousAI - - login: mikeckennedy - avatarUrl: https://avatars.githubusercontent.com/u/2035561?u=1bb18268bcd4d9249e1f783a063c27df9a84c05b&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/2035561?u=ce6165b799ea3164cb6f5ff54ea08042057442af&v=4 url: https://github.com/mikeckennedy - login: ndimares avatarUrl: https://avatars.githubusercontent.com/u/6267663?u=cfb27efde7a7212be8142abb6c058a1aeadb41b1&v=4 @@ -59,10 +65,7 @@ sponsors: - login: jina-ai avatarUrl: https://avatars.githubusercontent.com/u/60539444?v=4 url: https://github.com/jina-ai -- - login: HiredScore - avatarUrl: https://avatars.githubusercontent.com/u/3908850?v=4 - url: https://github.com/HiredScore - - login: Trivie +- - login: Trivie avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4 url: https://github.com/Trivie - - login: birkjernstrom @@ -80,27 +83,39 @@ sponsors: - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries - - login: deployplex + - login: doseiai avatarUrl: https://avatars.githubusercontent.com/u/57115726?v=4 - url: https://github.com/deployplex + url: https://github.com/doseiai + - login: CanoaPBC + avatarUrl: https://avatars.githubusercontent.com/u/64223768?v=4 + url: https://github.com/CanoaPBC - - login: povilasb avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 url: https://github.com/povilasb - login: primer-io avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4 url: https://github.com/primer-io +- - login: upciti + avatarUrl: https://avatars.githubusercontent.com/u/43346262?v=4 + url: https://github.com/upciti - - login: Kludex avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: samuelcolvin avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 url: https://github.com/samuelcolvin + - login: koconder + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 + url: https://github.com/koconder - login: jefftriplett avatarUrl: https://avatars.githubusercontent.com/u/50527?u=af1ddfd50f6afd6d99f333ba2ac8d0a5b245ea74&v=4 url: https://github.com/jefftriplett - login: jstanden avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 url: https://github.com/jstanden + - login: andreaso + avatarUrl: https://avatars.githubusercontent.com/u/285964?u=837265cc7562c0685f25b2d81cd9de0434fe107c&v=4 + url: https://github.com/andreaso - login: pamelafox avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4 url: https://github.com/pamelafox @@ -116,9 +131,9 @@ sponsors: - login: falkben avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben - - login: jqueguiner - avatarUrl: https://avatars.githubusercontent.com/u/690878?u=bd65cc1f228ce6455e56dfaca3ef47c33bc7c3b0&v=4 - url: https://github.com/jqueguiner + - login: mintuhouse + avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 + url: https://github.com/mintuhouse - login: tcsmith avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 url: https://github.com/tcsmith @@ -128,6 +143,9 @@ sponsors: - login: knallgelb avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4 url: https://github.com/knallgelb + - login: johannquerne + avatarUrl: https://avatars.githubusercontent.com/u/2736484?u=9b3381546a25679913a2b08110e4373c98840821&v=4 + url: https://github.com/johannquerne - login: Shark009 avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4 url: https://github.com/Shark009 @@ -147,7 +165,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 url: https://github.com/anomaly - login: jgreys - avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=c66ae617d614f6c886f1f1c1799d22100b3c848d&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=096820d1ef89877d57d0f68e669ead8b0fde84df&v=4 url: https://github.com/jgreys - login: jaredtrog avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4 @@ -212,42 +230,48 @@ sponsors: - login: Filimoa avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4 url: https://github.com/Filimoa + - login: ehaca + avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 + url: https://github.com/ehaca + - login: timlrx + avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 + url: https://github.com/timlrx - login: BrettskiPy avatarUrl: https://avatars.githubusercontent.com/u/30988215?u=d8a94a67e140d5ee5427724b292cc52d8827087a&v=4 url: https://github.com/BrettskiPy - - login: mauroalejandrojm - avatarUrl: https://avatars.githubusercontent.com/u/31569442?u=cdada990a1527926a36e95f62c30a8b48bbc49a1&v=4 - url: https://github.com/mauroalejandrojm - login: Leay15 avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 url: https://github.com/Leay15 - - login: dvlpjrs - avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 - url: https://github.com/dvlpjrs - login: ygorpontelo avatarUrl: https://avatars.githubusercontent.com/u/32963605?u=35f7103f9c4c4c2589ae5737ee882e9375ef072e&v=4 url: https://github.com/ygorpontelo - login: ProteinQure avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 url: https://github.com/ProteinQure + - login: RafaelWO + avatarUrl: https://avatars.githubusercontent.com/u/38643099?u=56c676f024667ee416dc8b1cdf0c2611b9dc994f&v=4 + url: https://github.com/RafaelWO - login: arleybri18 avatarUrl: https://avatars.githubusercontent.com/u/39681546?u=5c028f81324b0e8c73b3c15bc4e7b0218d2ba0c3&v=4 url: https://github.com/arleybri18 - login: thenickben avatarUrl: https://avatars.githubusercontent.com/u/40610922?u=1e907d904041b7c91213951a3cb344cd37c14aaf&v=4 url: https://github.com/thenickben - - login: adtalos - avatarUrl: https://avatars.githubusercontent.com/u/40748353?v=4 - url: https://github.com/adtalos - - login: ybressler - avatarUrl: https://avatars.githubusercontent.com/u/40807730?u=41e2c00f1eebe3c402635f0325e41b4e6511462c&v=4 - url: https://github.com/ybressler - login: ddilidili avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 url: https://github.com/ddilidili + - login: ramonalmeidam + avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4 + url: https://github.com/ramonalmeidam - login: dudikbender avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4 url: https://github.com/dudikbender + - login: Amirshox + avatarUrl: https://avatars.githubusercontent.com/u/56707784?u=2a2f8cc243d6f5b29cd63fd2772f7a97aadc6c6b&v=4 + url: https://github.com/Amirshox + - login: prodhype + avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 + url: https://github.com/prodhype - login: yakkonaut avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4 url: https://github.com/yakkonaut @@ -257,15 +281,18 @@ sponsors: - login: anthonycepeda avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=4252c6b6dc5024af502a823a3ac5e7a03a69963f&v=4 url: https://github.com/anthonycepeda + - login: patricioperezv + avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4 + url: https://github.com/patricioperezv + - login: kaoru0310 + avatarUrl: https://avatars.githubusercontent.com/u/80977929?u=1b61d10142b490e56af932ddf08a390fae8ee94f&v=4 + url: https://github.com/kaoru0310 - login: DelfinaCare avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 url: https://github.com/DelfinaCare - login: osawa-koki avatarUrl: https://avatars.githubusercontent.com/u/94336223?u=59c6fe6945bcbbaff87b2a794238671b060620d2&v=4 url: https://github.com/osawa-koki - - login: pyt3h - avatarUrl: https://avatars.githubusercontent.com/u/99658549?v=4 - url: https://github.com/pyt3h - login: apitally avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4 url: https://github.com/apitally @@ -281,9 +308,6 @@ 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 @@ -305,12 +329,12 @@ sponsors: - login: browniebroke avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 url: https://github.com/browniebroke - - login: janfilips - avatarUrl: https://avatars.githubusercontent.com/u/870699?u=80702ec63f14e675cd4cdcc6ce3821d2ed207fd7&v=4 - url: https://github.com/janfilips - login: dodo5522 avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 url: https://github.com/dodo5522 + - login: miguelgr + avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4 + url: https://github.com/miguelgr - login: WillHogan avatarUrl: https://avatars.githubusercontent.com/u/1661551?u=7036c064cf29781470573865264ec8e60b6b809f&v=4 url: https://github.com/WillHogan @@ -326,15 +350,12 @@ sponsors: - login: anthonycorletti avatarUrl: https://avatars.githubusercontent.com/u/3477132?v=4 url: https://github.com/anthonycorletti - - login: erhan - avatarUrl: https://avatars.githubusercontent.com/u/3872888?u=cd9a20fcd33c5598d9d7797a78dedfc9148592f6&v=4 - url: https://github.com/erhan - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa - - login: piotrgredowski - avatarUrl: https://avatars.githubusercontent.com/u/4294480?v=4 - url: https://github.com/piotrgredowski + - login: gowikel + avatarUrl: https://avatars.githubusercontent.com/u/4339072?u=0e325ffcc539c38f89d9aa876bd87f9ec06ce0ee&v=4 + url: https://github.com/gowikel - login: danielunderwood avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 url: https://github.com/danielunderwood @@ -350,6 +371,9 @@ sponsors: - login: Baghdady92 avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4 url: https://github.com/Baghdady92 + - login: jakeecolution + avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4 + url: https://github.com/jakeecolution - login: KentShikama avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4 url: https://github.com/KentShikama @@ -369,7 +393,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/8574425?u=aad2a9674273c9275fe414d99269b7418d144089&v=4 url: https://github.com/albertkun - login: xncbf - avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=05cb2d7c797a02f666805ad4639d9582f31d432c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=ee91e210ae93b9cdd8f248b21cb028316cc0b747&v=4 url: https://github.com/xncbf - login: DMantis avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 @@ -389,27 +413,42 @@ sponsors: - login: pheanex avatarUrl: https://avatars.githubusercontent.com/u/10408624?u=5b6bab6ee174aa6e991333e06eb29f628741013d&v=4 url: https://github.com/pheanex + - login: dzoladz + avatarUrl: https://avatars.githubusercontent.com/u/10561752?u=5ee314d54aa79592c18566827ad8914debd5630d&v=4 + url: https://github.com/dzoladz - login: JimFawkes avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 url: https://github.com/JimFawkes + - login: artempronevskiy + avatarUrl: https://avatars.githubusercontent.com/u/12235104?u=03df6e1e55c9c6fe5d230adabb8dd7d43d8bbe8f&v=4 + url: https://github.com/artempronevskiy - login: giuliano-oliveira avatarUrl: https://avatars.githubusercontent.com/u/13181797?u=0ef2dfbf7fc9a9726d45c21d32b5d1038a174870&v=4 url: https://github.com/giuliano-oliveira - login: TheR1D avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 url: https://github.com/TheR1D + - login: joshuatz + avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4 + url: https://github.com/joshuatz - login: jangia avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4 url: https://github.com/jangia - login: shuheng-liu avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4 url: https://github.com/shuheng-liu + - login: salahelfarissi + avatarUrl: https://avatars.githubusercontent.com/u/23387408?u=73222a4be627c1a3dee9736e0da22224eccdc8f6&v=4 + url: https://github.com/salahelfarissi - login: pers0n4 avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4 url: https://github.com/pers0n4 - login: kxzk avatarUrl: https://avatars.githubusercontent.com/u/25046261?u=e185e58080090f9e678192cd214a14b14a2b232b&v=4 url: https://github.com/kxzk + - login: SebTota + avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 + url: https://github.com/SebTota - login: nisutec avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 url: https://github.com/nisutec @@ -422,9 +461,6 @@ sponsors: - login: rlnchow avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 url: https://github.com/rlnchow - - login: mertguvencli - avatarUrl: https://avatars.githubusercontent.com/u/29762151?u=16a906d90df96c8cff9ea131a575c4bc171b1523&v=4 - url: https://github.com/mertguvencli - login: White-Mask avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 url: https://github.com/White-Mask @@ -435,14 +471,11 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 url: https://github.com/engineerjoe440 - login: bnkc - avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=ea88e4bd668c984cff1bca3e71ab2deb37fafdc4&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4 url: https://github.com/bnkc - login: declon avatarUrl: https://avatars.githubusercontent.com/u/36180226?v=4 url: https://github.com/declon - - 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 @@ -458,12 +491,12 @@ sponsors: - login: hgalytoby avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4 url: https://github.com/hgalytoby - - login: eladgunders - avatarUrl: https://avatars.githubusercontent.com/u/52347338?u=83d454817cf991a035c8827d46ade050c813e2d6&v=4 - url: https://github.com/eladgunders - login: conservative-dude avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 url: https://github.com/conservative-dude + - login: Calesi19 + avatarUrl: https://avatars.githubusercontent.com/u/58052598?u=273d4fc364c004602c93dd6adeaf5cc915b93cd2&v=4 + url: https://github.com/Calesi19 - login: 0417taehyun avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 url: https://github.com/0417taehyun @@ -476,30 +509,30 @@ sponsors: - login: mbukeRepo avatarUrl: https://avatars.githubusercontent.com/u/70356088?u=d2eb23e2b222a3b316c4183b05a3236b32819dc2&v=4 url: https://github.com/mbukeRepo + - login: adriiamontoto + avatarUrl: https://avatars.githubusercontent.com/u/75563346?u=eeb1350b82ecb4d96592f9b6cd1a16870c355e38&v=4 + url: https://github.com/adriiamontoto - login: PelicanQ avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 url: https://github.com/PelicanQ + - login: tahmarrrr23 + avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4 + url: https://github.com/tahmarrrr23 - - login: ssbarnea avatarUrl: https://avatars.githubusercontent.com/u/102495?u=b4bf6818deefe59952ac22fec6ed8c76de1b8f7c&v=4 url: https://github.com/ssbarnea - login: Patechoc avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 url: https://github.com/Patechoc - - login: LanceMoe - avatarUrl: https://avatars.githubusercontent.com/u/18505474?u=7fd3ead4364bdf215b6d75cb122b3811c391ef6b&v=4 - url: https://github.com/LanceMoe + - login: DazzyMlv + avatarUrl: https://avatars.githubusercontent.com/u/23006212?u=df429da52882b0432e5ac81d4f1b489abc86433c&v=4 + url: https://github.com/DazzyMlv - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu - - login: msniezynski - avatarUrl: https://avatars.githubusercontent.com/u/27588547?u=0e3be5ac57dcfdf124f470bcdf74b5bf79af1b6c&v=4 - url: https://github.com/msniezynski - login: danburonline - avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=2cad4388c1544e539ecb732d656e42fb07b4ff2d&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 url: https://github.com/danburonline - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd - - login: IvanReyesO7 - avatarUrl: https://avatars.githubusercontent.com/u/74359151?u=4b2c368f71e1411b462a8c2290c920ad35dc1af8&v=4 - url: https://github.com/IvanReyesO7 diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 2e84f11285cbc..2877e7938c2ca 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,16 +1,16 @@ maintainers: - login: tiangolo answers: 1870 - prs: 508 + prs: 523 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 512 + count: 522 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu - count: 240 + count: 241 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu - login: Mause @@ -21,20 +21,20 @@ experts: count: 217 avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 url: https://github.com/ycd +- login: jgould22 + count: 205 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: JarroVGIT count: 193 avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 url: https://github.com/JarroVGIT -- login: jgould22 - count: 186 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 - login: euri10 count: 153 avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 url: https://github.com/euri10 - login: iudeen - count: 126 + count: 127 avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 url: https://github.com/iudeen - login: phy25 @@ -62,9 +62,17 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen - login: yinziyan1206 - count: 45 + count: 48 avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 url: https://github.com/yinziyan1206 +- login: insomnes + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 + url: https://github.com/insomnes +- login: adriangb + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb - login: acidjunk count: 45 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 @@ -73,26 +81,22 @@ experts: count: 45 avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 url: https://github.com/Dustyposa -- login: adriangb - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 - url: https://github.com/adriangb -- login: insomnes - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 - url: https://github.com/insomnes -- login: frankie567 - count: 43 - avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 - url: https://github.com/frankie567 - login: odiseo0 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 url: https://github.com/odiseo0 +- login: frankie567 + count: 43 + avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 + url: https://github.com/frankie567 - login: includeamin count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 url: https://github.com/includeamin +- login: n8sty + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - login: chbndrhnns count: 38 avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 @@ -101,10 +105,6 @@ experts: count: 37 avatarUrl: https://avatars.githubusercontent.com/u/5167622?u=de8f597c81d6336fcebc37b32dfd61a3f877160c&v=4 url: https://github.com/STeveShary -- login: n8sty - count: 36 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty - login: krishnardt count: 35 avatarUrl: https://avatars.githubusercontent.com/u/31960541?u=47f4829c77f4962ab437ffb7995951e41eeebe9b&v=4 @@ -113,6 +113,10 @@ experts: count: 32 avatarUrl: https://avatars.githubusercontent.com/u/41326348?u=ba2fda6b30110411ecbf406d187907e2b420ac19&v=4 url: https://github.com/panla +- login: JavierSanchezCastro + count: 30 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: prostomarkeloff count: 28 avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4 @@ -125,50 +129,46 @@ experts: count: 25 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes -- login: SirTelemak - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 - url: https://github.com/SirTelemak - login: acnebs count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 url: https://github.com/acnebs +- login: SirTelemak + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 + url: https://github.com/SirTelemak - login: rafsaf count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf -- login: chris-allnutt - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 - url: https://github.com/chris-allnutt -- login: ebottos94 +- login: nymous count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous - login: nsidnev count: 20 avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 url: https://github.com/nsidnev -- login: JavierSanchezCastro +- login: chris-allnutt count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro + avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 + url: https://github.com/chris-allnutt - login: chrisK824 - count: 19 + count: 20 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 - url: https://github.com/zoliknemet +- login: ebottos94 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 - login: retnikt count: 18 avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 url: https://github.com/retnikt -- login: nymous - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous +- login: zoliknemet + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 + url: https://github.com/zoliknemet - login: Hultner count: 17 avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4 @@ -193,39 +193,31 @@ experts: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 url: https://github.com/jonatasoli -- login: abhint +- login: ghost count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 - url: https://github.com/abhint + avatarUrl: https://avatars.githubusercontent.com/u/10137?u=b1951d34a583cf12ec0d3b0781ba19be97726318&v=4 + url: https://github.com/ghost last_month_active: +- login: Ventura94 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 + url: https://github.com/Ventura94 +- login: JavierSanchezCastro + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: jgould22 - count: 18 + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: Kludex - count: 10 + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: White-Mask - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 - url: https://github.com/White-Mask - login: n8sty - count: 4 + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty -- login: hasansezertasan - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=e389634d494d503cca867f76c2d00cacc273a46e&v=4 - url: https://github.com/hasansezertasan -- login: pythonweb2 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: ebottos94 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 top_contributors: - login: waynerv count: 25 @@ -343,6 +335,10 @@ top_contributors: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 url: https://github.com/lsglucas +- login: adriangb + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb - login: iudeen count: 4 avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 @@ -365,21 +361,25 @@ top_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: BilalAlpaslan - count: 82 + count: 86 avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 url: https://github.com/BilalAlpaslan - login: yezz123 - count: 80 + count: 82 avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 url: https://github.com/yezz123 - login: iudeen - count: 54 + count: 55 avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 url: https://github.com/iudeen - login: tokusumi count: 51 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi +- login: Xewus + count: 50 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus - login: waynerv count: 47 avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 @@ -388,10 +388,6 @@ top_reviewers: count: 47 avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4 url: https://github.com/Laineyzhang55 -- login: Xewus - count: 47 - avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 - url: https://github.com/Xewus - login: ycd count: 45 avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 @@ -416,17 +412,17 @@ top_reviewers: count: 28 avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=b0a652331da17efeb85cd6e3a4969182e5004804&v=4 url: https://github.com/cassiobotaro +- login: lsglucas + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 + url: https://github.com/lsglucas - login: komtaki count: 27 avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki -- login: lsglucas - count: 26 - avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 - url: https://github.com/lsglucas - login: Ryandaydev count: 25 - avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=ba0eea19429e7cf77cf2ab8ad2f3d3af202bc1cf&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 url: https://github.com/Ryandaydev - login: LorhanSohaky count: 24 @@ -460,6 +456,10 @@ top_reviewers: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 url: https://github.com/zy7y +- login: peidrao + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 + url: https://github.com/peidrao - login: yanever count: 16 avatarUrl: https://avatars.githubusercontent.com/u/21978760?v=4 @@ -468,6 +468,10 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 url: https://github.com/SwftAlpc +- login: nilslindemann + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann - login: axel584 count: 16 avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 @@ -480,6 +484,10 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 url: https://github.com/DevDae +- login: hasansezertasan + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: pedabraham count: 15 avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 @@ -488,10 +496,6 @@ top_reviewers: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 url: https://github.com/delhi09 -- login: peidrao - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 - url: https://github.com/peidrao - login: sh0nk count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 @@ -536,6 +540,10 @@ top_reviewers: count: 10 avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 url: https://github.com/ComicShrimp +- login: romashevchenko + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 + url: https://github.com/romashevchenko - login: izaguerreiro count: 9 avatarUrl: https://avatars.githubusercontent.com/u/2241504?v=4 @@ -544,15 +552,3 @@ top_reviewers: count: 9 avatarUrl: https://avatars.githubusercontent.com/u/413772?u=64b77b6aa405c68a9c6bcf45f84257c66eea5f32&v=4 url: https://github.com/graingert -- login: PandaHun - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/13096845?u=646eba44db720e37d0dbe8e98e77ab534ea78a20&v=4 - url: https://github.com/PandaHun -- login: kty4119 - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/49435654?v=4 - url: https://github.com/kty4119 -- login: bezaca - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 - url: https://github.com/bezaca From f43fc82267f35586b2868ebdd2caf7859b964914 Mon Sep 17 00:00:00 2001 From: s111d Date: Tue, 9 Jan 2024 21:22:46 +0300 Subject: [PATCH 100/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typos=20in?= =?UTF-8?q?=20`docs/en/docs/alternatives.md`=20and=20`docs/en/docs/tutoria?= =?UTF-8?q?l/dependencies/index.md`=20(#10906)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/alternatives.md | 6 +++--- docs/en/docs/tutorial/dependencies/index.md | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index 0f074ccf32dcc..e02b3b55a113b 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -185,7 +185,7 @@ It's a Flask plug-in, that ties together Webargs, Marshmallow and APISpec. It uses the information from Webargs and Marshmallow to automatically generate OpenAPI schemas, using APISpec. -It's a great tool, very under-rated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract. +It's a great tool, very underrated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract. This solved having to write YAML (another syntax) inside of Python docstrings. @@ -263,7 +263,7 @@ I discovered Molten in the first stages of building **FastAPI**. And it has quit It doesn't use a data validation, serialization and documentation third-party library like Pydantic, it has its own. So, these data type definitions would not be reusable as easily. -It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high-performance provided by tools like Uvicorn, Starlette and Sanic. +It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high performance provided by tools like Uvicorn, Starlette and Sanic. The dependency injection system requires pre-registration of the dependencies and the dependencies are solved based on the declared types. So, it's not possible to declare more than one "component" that provides a certain type. @@ -357,7 +357,7 @@ It is comparable to Marshmallow. Although it's faster than Marshmallow in benchm ### Starlette -Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services. +Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services. It is very simple and intuitive. It's designed to be easily extensible, and have modular components. diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index bc98cb26edc54..608ced407ea49 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -287,9 +287,9 @@ Other common terms for this same idea of "dependency injection" are: ## **FastAPI** plug-ins -Integrations and "plug-in"s can be built using the **Dependency Injection** system. But in fact, there is actually **no need to create "plug-ins"**, as by using dependencies it's possible to declare an infinite number of integrations and interactions that become available to your *path operation functions*. +Integrations and "plug-ins" can be built using the **Dependency Injection** system. But in fact, there is actually **no need to create "plug-ins"**, as by using dependencies it's possible to declare an infinite number of integrations and interactions that become available to your *path operation functions*. -And dependencies can be created in a very simple and intuitive way that allow you to just import the Python packages you need, and integrate them with your API functions in a couple of lines of code, *literally*. +And dependencies can be created in a very simple and intuitive way that allows you to just import the Python packages you need, and integrate them with your API functions in a couple of lines of code, *literally*. You will see examples of this in the next chapters, about relational and NoSQL databases, security, etc. From aa6586d51a7868a08b2971ee14957d6db7f47d2e Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 18:24:21 +0000 Subject: [PATCH 101/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cf686b02a5be5..59de429abc640 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Translations +* ✏ Update Python version in `index.md` in several languages. PR [#10711](https://github.com/tiangolo/fastapi/pull/10711) by [@tamago3keran](https://github.com/tamago3keran). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-forms-and-files.md`. PR [#10347](https://github.com/tiangolo/fastapi/pull/10347) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Ukrainian translation for `docs/uk/docs/index.md`. PR [#10362](https://github.com/tiangolo/fastapi/pull/10362) by [@rostik1410](https://github.com/rostik1410). * ✏ Update Python version in `docs/ko/docs/index.md`. PR [#10680](https://github.com/tiangolo/fastapi/pull/10680) by [@Eeap](https://github.com/Eeap). From dd6cf5d71091f15b4cef40fe23f7f7d7344d6f93 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 18:32:18 +0000 Subject: [PATCH 102/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 59de429abc640..bb7c722ea389c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Fix typos in `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10834](https://github.com/tiangolo/fastapi/pull/10834) by [@Molkree](https://github.com/Molkree). * 📝 Add article: "Building a RESTful API with FastAPI: Secure Signup and Login Functionality Included". PR [#9733](https://github.com/tiangolo/fastapi/pull/9733) by [@dxphilo](https://github.com/dxphilo). * 📝 Add warning about lifecycle events with `AsyncClient`. PR [#4167](https://github.com/tiangolo/fastapi/pull/4167) by [@andrew-chang-dewitt](https://github.com/andrew-chang-dewitt). * ✏ Fix typos in `/docs/reference/exceptions.md` and `/en/docs/reference/status.md`. PR [#10809](https://github.com/tiangolo/fastapi/pull/10809) by [@clarencepenz](https://github.com/clarencepenz). From f73be1d59984f5af8330655de44f8305ed0ec784 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 18:33:22 +0000 Subject: [PATCH 103/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bb7c722ea389c..d350124fcea7f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -52,6 +52,7 @@ hide: ### Internal +* 👥 Update FastAPI People. PR [#10871](https://github.com/tiangolo/fastapi/pull/10871) by [@tiangolo](https://github.com/tiangolo). * 👷 Upgrade custom GitHub Action comment-docs-preview-in-pr. PR [#10916](https://github.com/tiangolo/fastapi/pull/10916) by [@tiangolo](https://github.com/tiangolo). * ⬆ Upgrade GitHub Action latest-changes. PR [#10915](https://github.com/tiangolo/fastapi/pull/10915) by [@tiangolo](https://github.com/tiangolo). * 👷 Upgrade GitHub Action label-approved. PR [#10913](https://github.com/tiangolo/fastapi/pull/10913) by [@tiangolo](https://github.com/tiangolo). From 3b9a2bcb1b0b3ec234cf70adeb551d5655f774e9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 18:35:49 +0000 Subject: [PATCH 104/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d350124fcea7f..c7787053e9580 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Fix typos in `docs/en/docs/alternatives.md` and `docs/en/docs/tutorial/dependencies/index.md`. PR [#10906](https://github.com/tiangolo/fastapi/pull/10906) by [@s111d](https://github.com/s111d). * ✏ Fix typos in `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10834](https://github.com/tiangolo/fastapi/pull/10834) by [@Molkree](https://github.com/Molkree). * 📝 Add article: "Building a RESTful API with FastAPI: Secure Signup and Login Functionality Included". PR [#9733](https://github.com/tiangolo/fastapi/pull/9733) by [@dxphilo](https://github.com/dxphilo). * 📝 Add warning about lifecycle events with `AsyncClient`. PR [#4167](https://github.com/tiangolo/fastapi/pull/4167) by [@andrew-chang-dewitt](https://github.com/andrew-chang-dewitt). From 7eeacc9958565dc7f2279c206d0be0e5364dd99d Mon Sep 17 00:00:00 2001 From: Craig Blaszczyk Date: Tue, 9 Jan 2024 20:37:09 +0000 Subject: [PATCH 105/217] =?UTF-8?q?=E2=9C=A8=20Generate=20automatic=20lang?= =?UTF-8?q?uage=20names=20for=20docs=20translations=20(#5354)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Craig Blaszczyk Co-authored-by: Sebastián Ramírez --- docs/en/mkdocs.yml | 29 ++++--- docs/language_names.yml | 182 ++++++++++++++++++++++++++++++++++++++++ scripts/docs.py | 26 +++--- 3 files changed, 213 insertions(+), 24 deletions(-) create mode 100644 docs/language_names.yml diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index a64eff26969aa..92d081aa12333 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -58,15 +58,18 @@ plugins: python: options: extensions: - - griffe_typingdoc + - griffe_typingdoc show_root_heading: true show_if_no_docstring: true - preload_modules: [httpx, starlette] + preload_modules: + - httpx + - starlette inherited_members: true members_order: source separate_signature: true unwrap_annotated: true - filters: ["!^_"] + filters: + - '!^_' merge_init_into_class: true docstring_section_style: spacy signature_crossrefs: true @@ -264,25 +267,25 @@ extra: - link: / name: en - English - link: /de/ - name: de - - link: /em/ - name: 😉 + name: de - Deutsch - link: /es/ name: es - español - link: /fa/ - name: fa + name: fa - فارسی - link: /fr/ name: fr - français - link: /he/ - name: he + name: he - עבךית + - link: /hu/ + name: hu - magyar - link: /id/ - name: id + name: id - Bahasa Indonesia - link: /ja/ name: ja - 日本語 - link: /ko/ name: ko - 한국얎 - link: /pl/ - name: pl + name: pl - Polski - link: /pt/ name: pt - português - link: /ru/ @@ -290,15 +293,17 @@ extra: - link: /tr/ name: tr - TÃŒrkçe - link: /uk/ - name: uk + name: uk - україМська ЌПва - link: /ur/ - name: ur + name: ur - اردو - link: /vi/ name: vi - Tiếng Việt - link: /yo/ name: yo - Yorùbá - link: /zh/ name: zh - 汉语 + - link: /em/ + name: 😉 extra_css: - css/termynal.css - css/custom.css diff --git a/docs/language_names.yml b/docs/language_names.yml new file mode 100644 index 0000000000000..fbbbde303e31a --- /dev/null +++ b/docs/language_names.yml @@ -0,0 +1,182 @@ +aa: Afaraf +ab: аҧсуа бызшәа +ae: avesta +af: Afrikaans +ak: Akan +am: አማርኛ +an: aragonés +ar: اللغة العرؚية +as: àŠ…àŠžàŠ®à§€àŠ¯àŠŒàŠŸ +av: авар ЌацӀ +ay: aymar aru +az: azərbaycan dili +ba: башҡПрт теле +be: беларуская ЌПва +bg: българскО езОк +bh: à€­à¥‹à€œà€ªà¥à€°à¥€ +bi: Bislama +bm: bamanankan +bn: àŠ¬àŠŸàŠ‚àŠ²àŠŸ +bo: àœ–àœŒàœ‘àŒ‹àœ¡àœ²àœ‚ +br: brezhoneg +bs: bosanski jezik +ca: Català +ce: МПхчОйМ ЌПтт +ch: Chamoru +co: corsu +cr: ᓀᐊᐃᔭᐍᐏᐣ +cs: čeÅ¡tina +cu: ѩзыкъ слПвѣМьскъ +cv: чӑваш чӗлхО +cy: Cymraeg +da: dansk +de: Deutsch +dv: Dhivehi +dz: àœ¢àŸ«àœŒàœ„àŒ‹àœ +ee: Eʋegbe +el: ΕλληΜικά +en: English +eo: Esperanto +es: español +et: eesti +eu: euskara +fa: فارسی +ff: Fulfulde +fi: suomi +fj: Vakaviti +fo: fÞroyskt +fr: français +fy: Frysk +ga: Gaeilge +gd: Gàidhlig +gl: galego +gu: ગુજરટ઀ી +gv: Gaelg +ha: هَوُسَ +he: עבךית +hi: à€¹à€¿à€šà¥à€Šà¥€ +ho: Hiri Motu +hr: Hrvatski +ht: Kreyòl ayisyen +hu: magyar +hy: Հայերեն +hz: Otjiherero +ia: Interlingua +id: Bahasa Indonesia +ie: Interlingue +ig: Asụsụ Igbo +ii: ꆈꌠ꒿ Nuosuhxop +ik: Iñupiaq +io: Ido +is: Íslenska +it: italiano +iu: ᐃᓄᒃᑎᑐᑩ +ja: 日本語 +jv: basa Jawa +ka: ქართული +kg: Kikongo +ki: GÄ©kÅ©yÅ© +kj: Kuanyama +kk: қазақ тілі +kl: kalaallisut +km: ខេមរភាសា +kn: ಕಚ್ಚಡ +ko: 한국얎 +kr: Kanuri +ks: à€•à€¶à¥à€®à¥€à€°à¥€ +ku: Kurdî +kv: кПЌО кыв +kw: Kernewek +ky: Кыргызча +la: latine +lb: Lëtzebuergesch +lg: Luganda +li: Limburgs +ln: Lingála +lo: ພາສາ +lt: lietuvių kalba +lu: Tshiluba +lv: latvieÅ¡u valoda +mg: fiteny malagasy +mh: Kajin M̧ajeÄŒ +mi: te reo Māori +mk: ЌакеЎПМскО јазОк +ml: àŽ®àŽ²àŽ¯àŽŸàŽ³àŽ‚ +mn: МПМгПл хэл +mr: à€®à€°à€Ÿà€ à¥€ +ms: Bahasa Malaysia +mt: Malti +my: ဗမာစာ +na: EkakairÅ© Naoero +nb: Norsk bokmÃ¥l +nd: isiNdebele +ne: à€šà¥‡à€ªà€Ÿà€²à¥€ +ng: Owambo +nl: Nederlands +nn: Norsk nynorsk +'no': Norsk +nr: isiNdebele +nv: Diné bizaad +ny: chiCheŵa +oc: occitan +oj: ᐊᓂᔑᓈᐯᒧᐎᓐ +om: Afaan Oromoo +or: ଓଡଌିଆ +os: ОрПМ Êвзаг +pa: àšªà©°àšœàšŸàš¬à©€ +pi: à€ªà€Ÿà€Žà€¿ +pl: Polski +ps: ٟښتو +pt: português +qu: Runa Simi +rm: rumantsch grischun +rn: Ikirundi +ro: Română +ru: русскОй язык +rw: Ikinyarwanda +sa: à€žà€‚à€žà¥à€•à¥ƒà€€à€®à¥ +sc: sardu +sd: à€žà€¿à€šà¥à€§à¥€ +se: Davvisámegiella +sg: yângâ tî sÀngö +si: සිංහග +sk: slovenčina +sl: slovenščina +sn: chiShona +so: Soomaaliga +sq: shqip +sr: српскО језОк +ss: SiSwati +st: Sesotho +su: Basa Sunda +sv: svenska +sw: Kiswahili +ta: ஀மிஎ் +te: ఀెలుగు +tg: тПҷОкӣ +th: à¹„àž—àž¢ +ti: ትግርኛ +tk: TÃŒrkmen +tl: Wikang Tagalog +tn: Setswana +to: faka Tonga +tr: TÃŒrkçe +ts: Xitsonga +tt: татар теле +tw: Twi +ty: Reo Tahiti +ug: ؊ۇيغۇرچە‎ +uk: україМська ЌПва +ur: اردو +uz: Ўзбек +ve: Tshivenᾓa +vi: Tiếng Việt +vo: VolapÃŒk +wa: walon +wo: Wollof +xh: isiXhosa +yi: יי֎דיש +yo: Yorùbá +za: Saɯ cueŋƅ +zh: 汉语 +zu: isiZulu diff --git a/scripts/docs.py b/scripts/docs.py index 73e1900ada0c4..a6710d7a50fac 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -274,22 +274,24 @@ def live( def update_config() -> None: config = get_en_config() languages = [{"en": "/"}] - alternate: List[Dict[str, str]] = config["extra"].get("alternate", []) - alternate_dict = {alt["link"]: alt["name"] for alt in alternate} new_alternate: List[Dict[str, str]] = [] + # Language names sourced from https://quickref.me/iso-639-1 + # Contributors may wish to update or change these, e.g. to fix capitalization. + language_names_path = Path(__file__).parent / "../docs/language_names.yml" + local_language_names: Dict[str, str] = mkdocs.utils.yaml_load( + language_names_path.read_text(encoding="utf-8") + ) for lang_path in get_lang_paths(): - if lang_path.name == "en" or not lang_path.is_dir(): + if lang_path.name in {"en", "em"} or not lang_path.is_dir(): continue - name = lang_path.name - languages.append({name: f"/{name}/"}) + code = lang_path.name + languages.append({code: f"/{code}/"}) for lang_dict in languages: - name = list(lang_dict.keys())[0] - url = lang_dict[name] - if url not in alternate_dict: - new_alternate.append({"link": url, "name": name}) - else: - use_name = alternate_dict[url] - new_alternate.append({"link": url, "name": use_name}) + code = list(lang_dict.keys())[0] + url = lang_dict[code] + use_name = f"{code} - {local_language_names[code]}" + new_alternate.append({"link": url, "name": use_name}) + new_alternate.append({"link": "/em/", "name": "😉"}) config["extra"]["alternate"] = new_alternate en_config_path.write_text( yaml.dump(config, sort_keys=False, width=200, allow_unicode=True), From 958425a899642d1853a1181a3b89dcb07aabea4f Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 9 Jan 2024 20:37:29 +0000 Subject: [PATCH 106/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c7787053e9580..8699fbddcdcff 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✹ Generate automatic language names for docs translations. PR [#5354](https://github.com/tiangolo/fastapi/pull/5354) by [@jakul](https://github.com/jakul). * ✏ Fix typos in `docs/en/docs/alternatives.md` and `docs/en/docs/tutorial/dependencies/index.md`. PR [#10906](https://github.com/tiangolo/fastapi/pull/10906) by [@s111d](https://github.com/s111d). * ✏ Fix typos in `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10834](https://github.com/tiangolo/fastapi/pull/10834) by [@Molkree](https://github.com/Molkree). * 📝 Add article: "Building a RESTful API with FastAPI: Secure Signup and Login Functionality Included". PR [#9733](https://github.com/tiangolo/fastapi/pull/9733) by [@dxphilo](https://github.com/dxphilo). From 84cd488df17543089e0dbb1e1ab3c7bd4e976be3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 10 Jan 2024 21:19:21 +0400 Subject: [PATCH 107/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20FastAPI=20application=20monitoring=20made=20easy=20(#10917)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Simon Gurcke --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index d53afd7f9fac6..d9cfe3431d093 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ Articles: English: + - author: Apitally + author_link: https://apitally.io + link: https://blog.apitally.io/fastapi-application-monitoring-made-easy + title: FastAPI application monitoring made easy - author: John Philip author_link: https://medium.com/@amjohnphilip link: https://python.plainenglish.io/building-a-restful-api-with-fastapi-secure-signup-and-login-functionality-included-45cdbcb36106 From 7e0cdf25100207880e9519f109b9ad5377a83e01 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 10 Jan 2024 17:19:42 +0000 Subject: [PATCH 108/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8699fbddcdcff..6885ef68d7e4a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add External Link: FastAPI application monitoring made easy. PR [#10917](https://github.com/tiangolo/fastapi/pull/10917) by [@tiangolo](https://github.com/tiangolo). * ✹ Generate automatic language names for docs translations. PR [#5354](https://github.com/tiangolo/fastapi/pull/5354) by [@jakul](https://github.com/jakul). * ✏ Fix typos in `docs/en/docs/alternatives.md` and `docs/en/docs/tutorial/dependencies/index.md`. PR [#10906](https://github.com/tiangolo/fastapi/pull/10906) by [@s111d](https://github.com/s111d). * ✏ Fix typos in `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10834](https://github.com/tiangolo/fastapi/pull/10834) by [@Molkree](https://github.com/Molkree). From 06bf7781df11213ce4bc39370566b733de4dfd07 Mon Sep 17 00:00:00 2001 From: Fahad Md Kamal Date: Wed, 10 Jan 2024 23:43:35 +0600 Subject: [PATCH 109/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Bengali=20translat?= =?UTF-8?q?ion=20for=20`docs/bn/docs/index.md`=20(#9177)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/bn/docs/index.md | 464 ++++++++++++++++++++++++++++++++++++++++++ docs/bn/mkdocs.yml | 1 + 2 files changed, 465 insertions(+) create mode 100644 docs/bn/docs/index.md create mode 100644 docs/bn/mkdocs.yml diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md new file mode 100644 index 0000000000000..4f778e87352f9 --- /dev/null +++ b/docs/bn/docs/index.md @@ -0,0 +1,464 @@ +

+ FastAPI +

+

+ FastAPI àŠ‰àŠšà§àŠšàŠ•à§àŠ·àŠ®àŠ€àŠŸ àŠžàŠ®à§àŠªàŠšà§àŠš, àŠžàŠ¹àŠœà§‡ àŠ¶à§‡àŠ–àŠŸàŠ° àŠàŠ¬àŠ‚ àŠŠà§àŠ°à§àŠ€ àŠ•à§‹àŠ¡ àŠ•àŠ°à§‡ àŠªà§àŠ°à§‹àŠ¡àŠŸàŠ•àŠ¶àŠšà§‡àŠ° àŠœàŠšà§àŠ¯ àŠ«à§àŠ°àŠŸàŠ®àŠ“à§ŸàŠŸàŠ°à§àŠ•à¥€ +

+

+ + Test + + + Coverage + + + Package version + +

+ +--- + +**àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿**: https://fastapi.tiangolo.com + +**àŠžà§‹àŠ°à§àŠž àŠ•à§‹àŠ¡**: https://github.com/tiangolo/fastapi + +--- + +FastAPI àŠàŠ•àŠŸàŠ¿ àŠ†àŠ§à§àŠšàŠ¿àŠ•, àŠŠà§àŠ°à§àŠ€ ( àŠ¬à§‡àŠ¶àŠ¿ àŠ•à§àŠ·àŠ®àŠ€àŠŸ ) àŠžàŠ®à§àŠªàŠšà§àŠš, Python 3.6+ àŠŠàŠ¿à§Ÿà§‡ API àŠ€à§ˆàŠ°àŠ¿àŠ° àŠœàŠšà§àŠ¯ àŠžà§àŠŸà§àŠ¯àŠŸàŠšà§àŠ¡àŠŸàŠ°à§àŠ¡ àŠªàŠŸàŠ‡àŠ¥àŠš àŠŸàŠŸàŠ‡àŠª àŠ‡àŠ™à§àŠ—àŠ¿àŠ€ àŠ­àŠ¿àŠ€à§àŠ€àŠ¿àŠ• àŠ“àŠ¯àŠŒà§‡àŠ¬ àŠ«à§àŠ°à§‡àŠ®àŠ“àŠ¯àŠŒàŠŸàŠ°à§àŠ•à¥€ + +àŠàŠ° àŠ®à§‚àŠ² àŠ¬à§ˆàŠ¶àŠ¿àŠ·à§àŠŸà§àŠ¯ àŠ—à§àŠ²à§‹ àŠ¹àŠ²àŠƒ + +- **àŠ—àŠ€àŠ¿**: àŠàŠŸàŠ¿ **NodeJS** àŠàŠ¬àŠ‚ **Go** àŠàŠ° àŠ®àŠ€ àŠ•àŠŸàŠ°à§àŠ¯àŠ•à§àŠ·àŠ®àŠ€àŠŸ àŠžàŠ®à§àŠªàŠšà§àŠš (Starlette àŠàŠ¬àŠ‚ Pydantic àŠàŠ° àŠžàŠŸàŠ¹àŠŸàŠ¯à§àŠ¯à§‡)ी [àŠªàŠŸàŠ‡àŠ¥àŠš àŠàŠ° àŠŠà§àŠ°à§àŠ€àŠ€àŠ® àŠ«à§àŠ°à§‡àŠ®àŠ“àŠ¯àŠŒàŠŸàŠ°à§àŠ• àŠ—à§àŠ²à§‹àŠ° àŠ®àŠ§à§àŠ¯à§‡ àŠàŠŸàŠ¿ àŠàŠ•àŠŸàŠ¿](#_11)ी +- **àŠŠà§àŠ°à§àŠ€ àŠ•à§‹àŠ¡ àŠ•àŠ°àŠŸ**:àŠ¬à§ˆàŠ¶àŠ¿àŠ·à§àŠŸà§àŠ¯ àŠ€à§ˆàŠ°àŠ¿àŠ° àŠ—àŠ€àŠ¿ ৚৊৊% àŠ¥à§‡àŠ•à§‡ ৩৊৊% àŠ¬à§ƒàŠŠà§àŠ§àŠ¿ àŠ•àŠ°à§‡à§· \* +- **àŠžà§àŠ¬àŠ²à§àŠª bugs**: àŠ®àŠŸàŠšà§àŠ¬ (àŠ¡à§‡àŠ­à§‡àŠ²àŠªàŠŸàŠ°) àŠžà§ƒàŠ·à§àŠŸ àŠ€à§àŠ°à§àŠŸàŠ¿àŠ° àŠªà§àŠ°àŠŸàŠ¯àŠŒ ৪৊% àŠ¹à§àŠ°àŠŸàŠž àŠ•àŠ°à§‡à¥€ \* +- **àŠžà§àŠ¬àŠœà§àŠžàŠŸàŠ€**: àŠŠà§àŠ°à§àŠŠàŠŸàŠšà§àŠ€ àŠàŠ¡àŠ¿àŠŸàŠ° àŠžàŠŸàŠ¹àŠŸàŠ¯à§àŠ¯ Completion àŠšàŠŸàŠ®à§‡àŠ“ àŠªàŠ°àŠ¿àŠšàŠ¿àŠ€à¥€ àŠŠà§àŠ°à§àŠ€ àŠ¡àŠ¿àŠ¬àŠŸàŠ— àŠ•àŠ°àŠŸ àŠ¯àŠŸà§Ÿà¥€ + +- **àŠžàŠ¹àŠœ**: àŠàŠŸàŠ¿ àŠàŠ®àŠš àŠ­àŠŸàŠ¬à§‡ àŠžàŠœàŠŸàŠšà§‹ àŠ¹à§Ÿà§‡àŠ›à§‡ àŠ¯à§‡àŠš àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿ àŠªà§œà§‡ àŠžàŠ¹àŠœà§‡ àŠ¶à§‡àŠ–àŠŸ àŠàŠ¬àŠ‚ àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°àŠŸ àŠ¯àŠŸà§Ÿà¥€ +- **àŠžàŠ‚àŠ•à§àŠ·àŠ¿àŠªà§àŠ€**: àŠ•à§‹àŠ¡ àŠªà§àŠšàŠ°àŠŸàŠ¬à§ƒàŠ€à§àŠ€àŠ¿ àŠ•àŠ®àŠŸàŠšà§‹àŠ° àŠªàŠŸàŠ¶àŠŸàŠªàŠŸàŠ¶àŠ¿, bug àŠ•àŠ®àŠŸà§Ÿ àŠàŠ¬àŠ‚ àŠªà§àŠ°àŠ€àŠ¿àŠŸàŠ¿ àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ° àŠ˜à§‹àŠ·àŠ£àŠŸ àŠ¥à§‡àŠ•à§‡ àŠàŠ•àŠŸàŠ§àŠ¿àŠ• àŠ«àŠ¿àŠšàŠŸàŠ° àŠªàŠŸàŠ“à§ŸàŠŸ àŠ¯àŠŸà§Ÿ ी +- **àŠœà§‹àŠ°àŠŸàŠ²à§‹**: àŠžà§àŠ¬àŠ¯àŠŒàŠ‚àŠ•à§àŠ°àŠ¿àŠ¯àŠŒ àŠ­àŠŸàŠ¬à§‡ àŠ€à§ˆàŠ°àŠ¿ àŠ•à§àŠ°àŠ¿à§ŸàŠŸàŠ¶à§€àŠ² àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠšàŠŸ àŠšàŠ¥àŠ¿ (documentation) àŠžàŠ¹ àŠ‰à§ŽàŠªàŠŸàŠŠàŠš àŠ‰àŠªàŠ¯à§‹àŠ—àŠ¿ (Production-ready) àŠ•à§‹àŠ¡ àŠªàŠŸàŠ“à§ŸàŠŸ àŠ¯àŠŸà§Ÿà¥€ +- **àŠ®àŠŸàŠš-àŠ­àŠ¿àŠ€à§àŠ€àŠ¿àŠ•**: àŠàŠ° àŠ­àŠ¿àŠ€à§àŠ€àŠ¿ OpenAPI (àŠ¯àŠŸ àŠªà§àŠ°à§àŠ¬à§‡ Swagger àŠšàŠŸàŠ®à§‡ àŠªàŠ°àŠ¿àŠšàŠ¿àŠ€ àŠ›àŠ¿àŠ²) àŠàŠ¬àŠ‚ JSON Schema àŠàŠ° àŠ†àŠŠàŠ°à§àŠ¶à§‡àŠ° àŠ®àŠŸàŠšà§‡àŠ° àŠ“àŠªàŠ° + +\* àŠ‰à§ŽàŠªàŠŸàŠŠàŠšàŠ®à§àŠ–àŠ¿ àŠàŠªà§àŠ²àŠ¿àŠ•à§‡àŠ¶àŠš àŠ¬àŠŸàŠšàŠŸàŠšà§‹àŠ° àŠàŠ• àŠŠàŠ² àŠ¡à§‡àŠ­à§‡àŠ²àŠªàŠŸàŠ° àŠàŠ° àŠ®àŠ€àŠŸàŠ®àŠ€ àŠ­àŠ¿àŠ€à§àŠ€àŠ¿àŠ• àŠ«àŠ²àŠŸàŠ«àŠ²à¥€ + +## àŠžà§àŠªàŠšàŠžàŠ° àŠ—àŠ£ + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +àŠ…àŠšà§àŠ¯àŠŸàŠšà§àŠ¯ àŠžà§àŠªàŠšàŠžàŠ° àŠ—àŠ£ + +## àŠ®àŠ€àŠŸàŠ®àŠ€ àŠžàŠ®à§‚àŠ¹ + +"_àŠ†àŠ®àŠ¿ àŠ†àŠœàŠ•àŠŸàŠ² **FastAPI** àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°àŠ›àŠ¿à¥€ [...] àŠ†àŠ®àŠ°àŠŸ àŠ­àŠŸàŠ¬àŠ›àŠ¿ àŠ®àŠŸàŠ‡àŠ•à§àŠ°à§‹àŠžàŠ«à§àŠŸà§‡ **ML àŠžàŠŸàŠ°à§àŠ­àŠ¿àŠž** àŠ àŠžàŠ•àŠ² àŠŠàŠ²à§‡àŠ° àŠœàŠšà§àŠ¯ àŠàŠŸàŠ¿ àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°àŠ¬à¥€ àŠ¯àŠŸàŠ° àŠ®àŠ§à§àŠ¯à§‡ àŠ•àŠ¿àŠ›à§ àŠªàŠ£à§àŠ¯ **Windows** àŠ àŠžàŠ‚àŠ¯à§‹àŠ¯àŠš àŠ¹à§Ÿ àŠàŠ¬àŠ‚ àŠ•àŠ¿àŠ›à§ **Office** àŠàŠ° àŠžàŠŸàŠ¥à§‡ àŠžàŠ‚àŠ¯à§‹àŠ¯àŠš àŠ¹àŠšà§àŠ›à§‡à¥€_" + +
àŠ•àŠ¬àŠ¿àŠ° àŠ–àŠŸàŠš - àŠ®àŠŸàŠ‡àŠ•à§àŠ°à§‹àŠžàŠ«à§àŠŸà§‡ (ref)
+ +--- + +"_àŠ†àŠ®àŠ°àŠŸ **FastAPI** àŠ²àŠŸàŠ‡àŠ¬à§àŠ°à§‡àŠ°àŠ¿ àŠ—à§àŠ°àŠ¹àŠ£ àŠ•àŠ°à§‡àŠ›àŠ¿ àŠàŠ•àŠŸàŠ¿ **REST** àŠžàŠŸàŠ°à§àŠ­àŠŸàŠ° àŠ€à§ˆàŠ°àŠ¿ àŠ•àŠ°àŠ€à§‡, àŠ¯àŠŸ **àŠ­àŠ¬àŠ¿àŠ·à§àŠ¯àŠŠà§àŠ¬àŠŸàŠ£à§€** àŠªàŠŸàŠ“àŠ¯àŠŒàŠŸàŠ° àŠœàŠšà§àŠ¯ àŠ•à§à§Ÿà§‡àŠ°àŠ¿ àŠ•àŠ°àŠŸ àŠ¯à§‡àŠ€à§‡ àŠªàŠŸàŠ°à§‡à¥€ [àŠ²à§àŠ¡àŠ‰àŠ‡àŠ—à§‡àŠ° àŠœàŠšà§àŠ¯]_" + +
àŠªàŠ¿àŠ¯àŠŒà§‡àŠ°à§‹ àŠ®à§‹àŠ²àŠ¿àŠšà§‹, àŠ‡àŠ¯àŠŒàŠŸàŠ°à§‹àŠžà§àŠ²àŠŸàŠ­ àŠŠà§àŠŠàŠ¿àŠš, àŠàŠ¬àŠ‚ àŠžàŠŸàŠ‡ àŠžà§àŠ®àŠšà§àŠ¥ àŠ®àŠ¿àŠ°àŠ¿àŠ¯àŠŒàŠŸàŠ²àŠŸ - àŠ‰àŠ¬àŠŸàŠ° (ref)
+ +--- + +"_**Netflix** àŠ†àŠ®àŠŸàŠŠà§‡àŠ° **àŠ•à§àŠ°àŠŸàŠ‡àŠžàŠ¿àŠž àŠ®à§àŠ¯àŠŸàŠšà§‡àŠœàŠ®à§‡àŠšà§àŠŸ** àŠ…àŠ°à§àŠ•à§‡àŠžà§àŠŸà§àŠ°à§‡àŠ¶àŠš àŠ«à§àŠ°à§‡àŠ®àŠ“àŠ¯àŠŒàŠŸàŠ°à§àŠ•: **àŠ¡àŠ¿àŠžàŠªà§àŠ¯àŠŸàŠš** àŠàŠ° àŠ“àŠªà§‡àŠš àŠžà§‹àŠ°à§àŠž àŠ°àŠ¿àŠ²àŠ¿àŠœ àŠ˜à§‹àŠ·àŠ£àŠŸ àŠ•àŠ°àŠ€à§‡ àŠªà§‡àŠ°à§‡ àŠ†àŠšàŠšà§àŠŠàŠ¿àŠ€! [àŠ¯àŠŸàŠ•àŠ¿àŠšàŠŸ **FastAPI** àŠŠàŠ¿àŠ¯àŠŒà§‡ àŠšàŠ¿àŠ°à§àŠ®àŠ¿àŠ€]_" + +
àŠ•à§‡àŠ­àŠ¿àŠš àŠ—à§àŠ²àŠ¿àŠžàŠš, àŠ®àŠŸàŠ°à§àŠ• àŠ­àŠ¿àŠ²àŠŸàŠšà§‹àŠ­àŠŸ, àŠ«àŠ°à§‡àŠžà§àŠŸ àŠ®àŠšàŠžà§‡àŠš - àŠšà§‡àŠŸàŠ«à§àŠ²àŠ¿àŠ•à§àŠž (ref)
+ +--- + +"_àŠ†àŠ®àŠ¿ **FastAPI** àŠšàŠ¿àŠ¯àŠŒà§‡ àŠšàŠŸàŠàŠŠà§‡àŠ° àŠžàŠ®àŠŸàŠš àŠ‰à§ŽàŠžàŠŸàŠ¹àŠ¿àŠ€à¥€ àŠàŠŸàŠ¿ àŠ–à§àŠ¬àŠ‡ àŠ®àŠœàŠŸàŠ°!_" + +
àŠ¬à§àŠ°àŠŸàŠ¯àŠŒàŠŸàŠš àŠ“àŠ•à§‡àŠš - àŠªàŠŸàŠ‡àŠ¥àŠš àŠ¬àŠŸàŠ‡àŠŸàŠž àŠªàŠ¡àŠ•àŠŸàŠžà§àŠŸ àŠ¹à§‹àŠžà§àŠŸ (ref)
+ +--- + +"\_àŠžàŠ€à§àŠ¯àŠ¿àŠ‡, àŠ†àŠªàŠšàŠ¿ àŠ¯àŠŸ àŠ€à§ˆàŠ°àŠ¿ àŠ•àŠ°à§‡àŠ›à§‡àŠš àŠ€àŠŸ àŠ–à§àŠ¬ àŠ®àŠœàŠ¬à§àŠ€ àŠàŠ¬àŠ‚ àŠªàŠ°àŠ¿àŠªà§‚àŠ°à§àŠšà§· àŠ…àŠšà§‡àŠ• àŠ‰àŠªàŠŸàŠ¯àŠŒà§‡, àŠ†àŠ®àŠ¿ àŠ¯àŠŸ **Hug** àŠ àŠ•àŠ°àŠ€à§‡ àŠšà§‡à§Ÿà§‡àŠ›àŠ¿àŠ²àŠŸàŠ® - àŠ€àŠŸ àŠ•àŠŸàŠ‰àŠ•à§‡ àŠ€à§ˆàŠ°àŠ¿ àŠ•àŠ°àŠ€à§‡ àŠŠà§‡àŠ–à§‡ àŠ†àŠ®àŠ¿ àŠžàŠ€à§àŠ¯àŠ¿àŠ‡ àŠ…àŠšà§àŠªà§àŠ°àŠŸàŠšàŠ¿àŠ€à§·\_" + +
àŠŸàŠ¿àŠ®à§‹àŠ¥àŠ¿ àŠ•à§àŠ°àŠžàŠ²à§‡ - Hug àŠžà§àŠ°àŠ·à§àŠŸàŠŸ (ref)
+ +--- + +"àŠ†àŠªàŠšàŠ¿ àŠ¯àŠŠàŠ¿ REST API àŠ€à§ˆàŠ°àŠ¿àŠ° àŠœàŠšà§àŠ¯ àŠàŠ•àŠŸàŠ¿ **àŠ†àŠ§à§àŠšàŠ¿àŠ• àŠ«à§àŠ°à§‡àŠ®àŠ“à§ŸàŠŸàŠ°à§àŠ•** àŠ¶àŠ¿àŠ–àŠ€à§‡ àŠšàŠŸàŠš, àŠ€àŠŸàŠ¹àŠ²à§‡ **FastAPI** àŠŠà§‡àŠ–à§àŠš [...] àŠàŠŸàŠ¿ àŠŠà§àŠ°à§àŠ€, àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°àŠŸ àŠžàŠ¹àŠœ àŠàŠ¬àŠ‚ àŠ¶àŠ¿àŠ–àŠ€à§‡àŠ“ àŠžàŠ¹àŠœ [...]\_" + +"_àŠ†àŠ®àŠ°àŠŸ àŠ†àŠ®àŠŸàŠŠà§‡àŠ° **APIs** [...] àŠàŠ° àŠœàŠšà§àŠ¯ **FastAPI**- àŠ€à§‡ àŠàŠžà§‡àŠ›àŠ¿ [...] àŠ†àŠ®àŠ¿ àŠ®àŠšà§‡ àŠ•àŠ°àŠ¿ àŠ†àŠªàŠšàŠ¿àŠ“ àŠàŠŸàŠ¿ àŠªàŠ›àŠšà§àŠŠ àŠ•àŠ°àŠ¬à§‡àŠš [...]_" + +
àŠ‡àŠšà§‡àŠž àŠ®àŠšà§àŠŸàŠŸàŠšàŠ¿ - àŠ®à§àŠ¯àŠŸàŠ¥àŠ¿àŠ‰ àŠ¹à§‹àŠšàŠ¿àŠ¬àŠŸàŠ² - Explosion AI àŠªà§àŠ°àŠ€àŠ¿àŠ·à§àŠ àŠŸàŠ€àŠŸ - spaCy àŠžà§àŠ°àŠ·à§àŠŸàŠŸ (ref) - (ref)
+ +--- + +## **Typer**, CLI àŠàŠ° àŠœàŠšà§àŠ¯ FastAPI + + + +àŠ†àŠªàŠšàŠ¿ àŠ¯àŠŠàŠ¿ CLI àŠ…à§àŠ¯àŠŸàŠª àŠ¬àŠŸàŠšàŠŸàŠ€à§‡ àŠšàŠŸàŠš, àŠ¯àŠŸ àŠ•àŠ¿àŠšàŠŸ àŠ“à§Ÿà§‡àŠ¬ API àŠàŠ° àŠªàŠ°àŠ¿àŠ¬àŠ°à§àŠ€à§‡ àŠŸàŠŸàŠ°à§àŠ®àŠ¿àŠšàŠŸàŠ²à§‡ àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ¹àŠ¬à§‡, àŠ€àŠŸàŠ¹àŠ²à§‡ àŠŠà§‡àŠ–à§àŠš**Typer**. + +**àŠŸàŠŸàŠ‡àŠªàŠŸàŠ°** àŠ¹àŠ² FastAPI àŠàŠ° àŠ›à§‹àŠŸ àŠ­àŠŸàŠ‡à§Ÿà§‡àŠ° àŠ®àŠ€à¥€ àŠàŠ¬àŠ‚ àŠàŠŸàŠ¿àŠ° àŠ‰àŠŠà§àŠŠà§‡àŠ¶à§àŠ¯ àŠ›àŠ¿àŠ² **CLIs àŠàŠ° FastAPI** àŠ¹àŠ“à§ŸàŠŸà¥€ ⌚ 🚀 + +## àŠªà§àŠ°àŠ¯àŠŒà§‹àŠœàŠšà§€àŠ¯àŠŒàŠ€àŠŸ àŠ—à§àŠ²à§‹ + +Python 3.7+ + +FastAPI àŠ•àŠ¿àŠ›à§ àŠŠàŠŸàŠšàŠ¬à§‡àŠŠà§‡àŠ° àŠ•àŠŸàŠàŠ§à§‡ àŠŠàŠŸàŠàŠ¡àŠŒàŠ¿àŠ¯àŠŒà§‡ àŠ†àŠ›à§‡: + +- Starlette àŠ“àŠ¯àŠŒà§‡àŠ¬ àŠ…àŠ‚àŠ¶à§‡àŠ° àŠœàŠšà§àŠ¯. +- Pydantic àŠ¡à§‡àŠŸàŠŸ àŠ…àŠ‚àŠ¶àŠ—à§àŠ²àŠ¿àŠ° àŠœàŠšà§àŠ¯. + +## àŠ‡àŠšàŠžà§àŠŸàŠ²à§‡àŠ¶àŠš àŠªà§àŠ°àŠ•à§àŠ°àŠ¿à§ŸàŠŸ + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +àŠ†àŠªàŠšàŠŸàŠ° àŠàŠ•àŠŸàŠ¿ ASGI àŠžàŠŸàŠ°à§àŠ­àŠŸàŠ°à§‡àŠ°àŠ“ àŠªà§àŠ°àŠ¯àŠŒà§‹àŠœàŠš àŠ¹àŠ¬à§‡, àŠªà§àŠ°à§‹àŠ¡àŠŸàŠ•àŠ¶àŠšà§‡àŠ° àŠœàŠšà§àŠ¯ Uvicorn àŠ…àŠ¥àŠ¬àŠŸ Hypercorn. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## àŠ‰àŠŠàŠŸàŠ¹àŠ°àŠ£ + +### àŠ€à§ˆàŠ°àŠ¿ + +- `main.py` àŠšàŠŸàŠ®à§‡ àŠàŠ•àŠŸàŠ¿ àŠ«àŠŸàŠ‡àŠ² àŠ€à§ˆàŠ°àŠ¿ àŠ•àŠ°à§àŠš: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+àŠ…àŠ¥àŠ¬àŠŸ àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°à§àŠš async def... + +àŠ¯àŠŠàŠ¿ àŠ†àŠªàŠšàŠŸàŠ° àŠ•à§‹àŠ¡ `async` / `await`, àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°à§‡ àŠ€àŠŸàŠ¹àŠ²à§‡ `async def` àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°à§àŠš: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**àŠŸà§€àŠ•àŠŸ**: + +àŠ†àŠªàŠšàŠ¿ àŠ¯àŠŠàŠ¿ àŠšàŠŸ àŠœàŠŸàŠšà§‡àŠš, _"àŠ€àŠŸàŠ¡àŠŒàŠŸàŠ¹à§àŠ¡àŠŒà§‹?"_ àŠ¬àŠ¿àŠ­àŠŸàŠ—àŠŸàŠ¿ àŠŠà§‡àŠ–à§àŠš `async` àŠàŠ¬àŠ‚ `await` àŠšàŠ¥àŠ¿àŠ° àŠ®àŠ§à§àŠ¯à§‡ àŠŠà§‡àŠ–à§àŠš . + +
+ +### àŠàŠŸàŠ¿ àŠšàŠŸàŠ²àŠŸàŠš + +àŠžàŠŸàŠ°à§àŠ­àŠŸàŠ° àŠšàŠŸàŠ²à§ àŠ•àŠ°à§àŠš: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠšàŠŸ àŠžàŠ®à§àŠªàŠ°à§àŠ•à§‡ uvicorn main:app --reload... + +`uvicorn main:app` àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠšàŠŸàŠŸàŠ¿ àŠŠà§àŠ¬àŠŸàŠ°àŠŸ àŠ¬à§‹àŠàŠŸàŠ¯àŠŒ: + +- `main`: àŠ«àŠŸàŠ‡àŠ² `main.py` (àŠªàŠŸàŠ‡àŠ¥àŠš "àŠ®àŠ¡àŠ¿àŠ‰àŠ²")ी +- `app`: `app = FastAPI()` àŠ²àŠŸàŠ‡àŠš àŠŠàŠ¿àŠ¯àŠŒà§‡ `main.py` àŠàŠ° àŠ­àŠ¿àŠ€àŠ°à§‡ àŠ€à§ˆàŠ°àŠ¿ àŠ•àŠ°àŠŸ àŠ…àŠ¬àŠœà§‡àŠ•à§àŠŸà¥€ +- `--reload`: àŠ•à§‹àŠ¡ àŠªàŠ°àŠ¿àŠ¬àŠ°à§àŠ€àŠšà§‡àŠ° àŠªàŠ°à§‡ àŠžàŠŸàŠ°à§àŠ­àŠŸàŠ° àŠªà§àŠšàŠ°àŠŸàŠ¯àŠŒ àŠšàŠŸàŠ²à§ àŠ•àŠ°à§àŠšà¥€ àŠàŠŸàŠ¿ àŠ¶à§àŠ§à§àŠ®àŠŸàŠ€à§àŠ° àŠ¡à§‡àŠ­à§‡àŠ²àŠªàŠ®à§‡àŠšà§àŠŸ àŠàŠ° àŠžàŠ®à§Ÿ àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°à§àŠšà¥€ + +
+ +### àŠàŠŸàŠŸ àŠšà§‡àŠ• àŠ•àŠ°à§àŠš + +àŠ†àŠªàŠšàŠŸàŠ° àŠ¬à§àŠ°àŠŸàŠ‰àŠœàŠŸàŠ° àŠ–à§àŠ²à§àŠš http://127.0.0.1:8000/items/5?q=somequery àŠà¥€ + +àŠ†àŠªàŠšàŠ¿ JSON àŠ°à§‡àŠžàŠªàŠšà§àŠž àŠŠà§‡àŠ–àŠ€à§‡ àŠªàŠŸàŠ¬à§‡àŠš: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +àŠ†àŠªàŠšàŠ¿ àŠ‡àŠ€àŠ¿àŠ®àŠ§à§àŠ¯à§‡ àŠàŠ•àŠŸàŠ¿ API àŠ€à§ˆàŠ°àŠ¿ àŠ•àŠ°à§‡àŠ›à§‡àŠš àŠ¯àŠŸ: + +- `/` àŠàŠ¬àŠ‚ `/items/{item_id}` _paths_ àŠ HTTP àŠ…àŠšà§àŠ°à§‹àŠ§ àŠ—à§àŠ°àŠ¹àŠ£ àŠ•àŠ°à§‡à¥€ +- àŠ‰àŠ­àŠ¯àŠŒ *path*àŠ‡ `GET` àŠ…àŠªàŠŸàŠ°à§‡àŠ¶àŠš àŠšà§‡àŠ¯àŠŒ ( àŠ¯àŠŸ HTTP _methods_ àŠšàŠŸàŠ®à§‡àŠ“ àŠªàŠ°àŠ¿àŠšàŠ¿àŠ€)ी +- _path_ `/items/{item_id}`-àŠ àŠàŠ•àŠŸàŠ¿ _path àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ°_ `item_id` àŠ†àŠ›à§‡ àŠ¯àŠŸ àŠ•àŠ¿àŠšàŠŸ `int` àŠ¹àŠ€à§‡ àŠ¹àŠ¬à§‡à¥€ +- _path_ `/items/{item_id}`-àŠàŠ° àŠàŠ•àŠŸàŠ¿ àŠàŠšà§àŠ›àŠ¿àŠ• `str` _query àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ°_ `q` àŠ†àŠ›à§‡à¥€ + +### àŠ•à§àŠ°àŠ¿à§ŸàŠŸàŠ¶à§€àŠ² API àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿ + +àŠàŠ–àŠš àŠ¯àŠŸàŠš http://127.0.0.1:8000/docs. + +àŠ†àŠªàŠšàŠ¿ àŠžà§àŠ¬àŠ¯àŠŒàŠ‚àŠ•à§àŠ°àŠ¿àŠ¯àŠŒ àŠ­àŠŸàŠ¬à§‡ àŠªà§àŠ°àŠžà§àŠ€à§àŠ€ àŠ•à§àŠ°àŠ¿à§ŸàŠŸàŠ¶à§€àŠ² API àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿ àŠŠà§‡àŠ–àŠ€à§‡ àŠªàŠŸàŠ¬à§‡àŠš (Swagger UI àŠªà§àŠ°àŠŠàŠ€à§àŠ€): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### àŠ¬àŠ¿àŠ•àŠ²à§àŠª API àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿ + +àŠàŠ¬àŠ‚ àŠàŠ–àŠš http://127.0.0.1:8000/redoc àŠ àŠ¯àŠŸàŠš. + +àŠ†àŠªàŠšàŠ¿ àŠžà§àŠ¬àŠ¯àŠŒàŠ‚àŠ•à§àŠ°àŠ¿àŠ¯àŠŒ àŠ­àŠŸàŠ¬à§‡ àŠªà§àŠ°àŠžà§àŠ€à§àŠ€ àŠ¬àŠ¿àŠ•àŠ²à§àŠª àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿ àŠŠà§‡àŠ–àŠ€à§‡ àŠªàŠŸàŠ¬à§‡àŠš (ReDoc àŠªà§àŠ°àŠŠàŠ€à§àŠ€): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## àŠ‰àŠŠàŠŸàŠ¹àŠ°àŠ£àŠžà§àŠ¬àŠ°à§‚àŠª àŠ†àŠªàŠ—à§àŠ°à§‡àŠ¡ + +àŠàŠ–àŠš `main.py` àŠ«àŠŸàŠ‡àŠ²àŠŸàŠ¿ àŠªàŠ°àŠ¿àŠ¬àŠ°à§àŠ€àŠš àŠ•àŠ°à§àŠš àŠ¯à§‡àŠš àŠàŠŸàŠ¿ `PUT` àŠ°àŠ¿àŠ•à§à§Ÿà§‡àŠžà§àŠŸ àŠ¥à§‡àŠ•à§‡ àŠ¬àŠ¡àŠ¿ àŠªà§‡àŠ€à§‡ àŠªàŠŸàŠ°à§‡à¥€ + +Python àŠžà§àŠŸà§àŠ¯àŠŸàŠšà§àŠ¡àŠŸàŠ°à§àŠ¡ àŠ²àŠŸàŠ‡àŠ¬à§àŠ°à§‡àŠ°àŠ¿, Pydantic àŠàŠ° àŠžàŠŸàŠ¹àŠŸàŠ¯à§àŠ¯à§‡ àŠ¬àŠ¡àŠ¿ àŠ˜à§‹àŠ·àŠ£àŠŸ àŠ•àŠ°à§àŠšà¥€ + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +àŠžàŠŸàŠ°à§àŠ­àŠŸàŠ°àŠŸàŠ¿ àŠžà§àŠ¬àŠ¯àŠŒàŠ‚àŠ•à§àŠ°àŠ¿àŠ¯àŠŒàŠ­àŠŸàŠ¬à§‡ àŠªà§àŠšàŠ°àŠŸàŠ¯àŠŒ àŠ²à§‹àŠ¡ àŠ¹àŠ“àŠ¯àŠŒàŠŸ àŠ‰àŠšàŠ¿àŠ€ (àŠ•àŠŸàŠ°àŠ£ àŠ†àŠªàŠšàŠ¿ àŠ‰àŠªàŠ°à§‡àŠ° `uvicorn` àŠ•àŠ®àŠŸàŠšà§àŠ¡à§‡ `--reload` àŠ¯à§‹àŠ— àŠ•àŠ°à§‡àŠ›à§‡àŠš)ी + +### àŠ•à§àŠ°àŠ¿à§ŸàŠŸàŠ¶à§€àŠ² API àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿ àŠ‰àŠšà§àŠšà§€àŠ€àŠ•àŠ°àŠ£ + +àŠàŠ–àŠš http://127.0.0.1:8000/docs àŠàŠ¡àŠ¡à§àŠ°à§‡àŠžà§‡ àŠ¯àŠŸàŠš. + +- àŠ•à§àŠ°àŠ¿à§ŸàŠŸàŠ¶à§€àŠ² API àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿àŠŸàŠ¿ àŠžà§àŠ¬àŠ¯àŠŒàŠ‚àŠ•à§àŠ°àŠ¿àŠ¯àŠŒàŠ­àŠŸàŠ¬à§‡ àŠ‰àŠšà§àŠšà§€àŠ€ àŠ¹àŠ¯à§‡ àŠ¯àŠŸàŠ¬à§‡, àŠšàŠ€à§àŠš àŠ¬àŠ¡àŠ¿ àŠžàŠ¹: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +- "Try it out" àŠ¬àŠŸàŠŸàŠšà§‡ àŠšàŠŸàŠªà§àŠš, àŠàŠŸàŠ¿ àŠ†àŠªàŠšàŠŸàŠ•à§‡ àŠªà§‡àŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ°àŠ—à§àŠ²à§‹ àŠªà§‚àŠ°àŠ£ àŠ•àŠ°àŠ€à§‡ àŠàŠ¬àŠ‚ API àŠàŠ° àŠžàŠŸàŠ¥à§‡ àŠžàŠ°àŠŸàŠžàŠ°àŠ¿ àŠ•à§àŠ°àŠ¿à§ŸàŠŸ-àŠ•àŠ²àŠŸàŠª àŠ•àŠ°àŠ€à§‡ àŠŠàŠ¿àŠ¬à§‡: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +- àŠ€àŠŸàŠ°àŠªàŠ°à§‡ "Execute" àŠ¬àŠŸàŠŸàŠšà§‡ àŠšàŠŸàŠªà§àŠš, àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ°àŠ•àŠŸàŠ°à§€àŠ° àŠ‡àŠšà§àŠŸàŠŸàŠ°àŠ«à§‡àŠž àŠ†àŠªàŠšàŠŸàŠ° API àŠàŠ° àŠžàŠŸàŠ¥à§‡ àŠ¯à§‹àŠ—àŠŸàŠ¯à§‹àŠ— àŠ•àŠ°àŠ¬à§‡, àŠªà§‡àŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ° àŠªàŠŸàŠ àŠŸàŠ¬à§‡, àŠ«àŠ²àŠŸàŠ«àŠ²àŠ—à§àŠ²àŠ¿ àŠªàŠŸàŠ¬à§‡ àŠàŠ¬àŠ‚ àŠžà§‡àŠ—à§àŠ²àŠ¿ àŠªàŠ°à§àŠ°àŠŠàŠŸà§Ÿ àŠŠà§‡àŠ–àŠŸàŠ¬à§‡: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### àŠ¬àŠ¿àŠ•àŠ²à§àŠª API àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿ àŠ†àŠªàŠ—à§àŠ°à§‡àŠ¡ + +àŠàŠ¬àŠ‚ àŠàŠ–àŠš http://127.0.0.1:8000/redoc àŠ àŠ¯àŠŸàŠšà¥€ + +- àŠ¬àŠ¿àŠ•àŠ²à§àŠª àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿àŠ€à§‡àŠ“ àŠšàŠ€à§àŠš àŠ•à§à§Ÿà§‡àŠ°àŠ¿ àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ° àŠàŠ¬àŠ‚ àŠ¬àŠ¡àŠ¿ àŠªà§àŠ°àŠ€àŠ¿àŠ«àŠ²àŠ¿àŠ€ àŠ¹àŠ¬à§‡: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### àŠžàŠ‚àŠ•à§àŠ·àŠ¿àŠªà§àŠ€àŠ•àŠ°àŠ£ + +àŠžàŠ‚àŠ•à§àŠ·à§‡àŠªà§‡, àŠ†àŠªàŠšàŠ¿ **àŠ¶à§àŠ§à§ àŠàŠ•àŠ¬àŠŸàŠ°** àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ°à§‡àŠ° àŠ§àŠ°àŠš, àŠ¬àŠ¡àŠ¿ àŠ‡àŠ€à§àŠ¯àŠŸàŠŠàŠ¿ àŠ«àŠŸàŠ‚àŠ¶àŠš àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ° àŠ¹àŠ¿àŠžà§‡àŠ¬à§‡ àŠ˜à§‹àŠ·àŠ£àŠŸ àŠ•àŠ°à§‡àŠšà¥€ + +àŠ†àŠªàŠšàŠ¿ àŠžà§‡àŠŸàŠ¿ àŠ†àŠ§à§àŠšàŠ¿àŠ• àŠªàŠŸàŠ‡àŠ¥àŠšà§‡àŠ° àŠžàŠŸàŠ¥à§‡ àŠ•àŠ°à§‡àŠšà¥€ + +àŠ†àŠªàŠšàŠŸàŠ•à§‡ àŠšàŠ€à§àŠš àŠ•àŠ°à§‡ àŠšàŠ¿àŠ°à§àŠŠàŠ¿àŠ·à§àŠŸ àŠ•à§‹àŠš àŠ²àŠŸàŠ‡àŠ¬à§àŠ°à§‡àŠ°àŠ¿àŠ° àŠ¬àŠŸàŠ•à§àŠ¯ àŠ—àŠ àŠš, àŠ«àŠŸàŠ‚àŠ¶àŠš àŠ¬àŠŸ àŠ•à§àŠ²àŠŸàŠž àŠ•àŠ¿àŠ›à§àŠ‡ àŠ¶àŠ¿àŠ–àŠ€à§‡ àŠ¹àŠšà§àŠ›à§‡ àŠšàŠŸà¥€ + +àŠ¶à§àŠ§à§àŠ‡ àŠ†àŠ§à§àŠšàŠ¿àŠ• **Python 3.6+** + +àŠ‰àŠŠàŠŸàŠ¹àŠ°àŠ£àŠžà§àŠ¬àŠ°à§‚àŠª, `int` àŠàŠ° àŠœàŠšà§àŠ¯: + +```Python +item_id: int +``` + +àŠ…àŠ¥àŠ¬àŠŸ àŠ†àŠ°àŠ“ àŠœàŠŸàŠ¿àŠ² `Item` àŠ®àŠ¡à§‡àŠ²à§‡àŠ° àŠœàŠšà§àŠ¯: + +```Python +item: Item +``` + +...àŠàŠ¬àŠ‚ àŠžà§‡àŠ‡ àŠàŠ•àŠ‡ àŠ˜à§‹àŠ·àŠ£àŠŸàŠ° àŠžàŠŸàŠ¥à§‡ àŠ†àŠªàŠšàŠ¿ àŠªàŠŸàŠ¬à§‡àŠš: + +- àŠàŠ¡àŠ¿àŠŸàŠ° àŠžàŠŸàŠ¹àŠŸàŠ¯à§àŠ¯, àŠ¯à§‡àŠ®àŠš + - àŠžàŠ®àŠŸàŠªà§àŠ€àŠ¿à¥€ + - àŠ§àŠ°àŠ£ àŠ¯àŠŸàŠšàŠŸàŠ‡ +- àŠ€àŠ¥à§àŠ¯ àŠ¯àŠŸàŠšàŠŸàŠ‡àŠ•àŠ°àŠ£: + - àŠ¡à§‡àŠŸàŠŸ àŠ…àŠ¬à§ˆàŠ§ àŠ¹àŠ²à§‡ àŠžà§àŠ¬àŠ¯àŠŒàŠ‚àŠ•à§àŠ°àŠ¿àŠ¯àŠŒ àŠàŠ¬àŠ‚ àŠªàŠ°àŠ¿àŠ·à§àŠ•àŠŸàŠ° àŠ€à§àŠ°à§àŠŸàŠ¿àŠ° àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠšàŠŸà¥€ + - àŠàŠ®àŠšàŠ•àŠ¿ àŠ—àŠ­à§€àŠ°àŠ­àŠŸàŠ¬à§‡ àŠšà§‡àŠžà§àŠŸ àŠ•àŠ°àŠŸ JSON àŠ…àŠ¬àŠœà§‡àŠ•à§àŠŸà§‡àŠ° àŠœàŠšà§àŠ¯ àŠ¬à§ˆàŠ§àŠ€àŠŸà¥€ +- àŠªà§àŠ°à§‡àŠ°àŠ¿àŠ€ àŠ€àŠ¥à§àŠ¯ àŠ°à§‚àŠªàŠŸàŠšà§àŠ€àŠ°: àŠ¯àŠŸ àŠšà§‡àŠŸàŠ“à§ŸàŠŸàŠ°à§àŠ• àŠ¥à§‡àŠ•à§‡ àŠªàŠŸàŠ‡àŠ¥àŠšà§‡àŠ° àŠ€àŠ¥à§àŠ¯ àŠàŠ¬àŠ‚ àŠ§àŠ°àŠšà§‡ àŠ†àŠžà§‡, àŠàŠ¬àŠ‚ àŠžà§‡àŠ–àŠŸàŠš àŠ¥à§‡àŠ•à§‡ àŠªà§œàŠŸ: + + - JSONी + - àŠªàŠŸàŠ¥ àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ°à¥€ + - àŠ•à§à§Ÿà§‡àŠ°àŠ¿ àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ°à¥€ + - àŠ•à§àŠ•àŠ¿àŠœ + - àŠ¹à§‡àŠ¡àŠŸàŠ° + - àŠ«àŠ°à§àŠ® + - àŠ«àŠŸàŠ‡àŠ² + +- àŠ†àŠ‰àŠŸàŠªà§àŠŸ àŠ¡à§‡àŠŸàŠŸàŠ° àŠ°à§‚àŠªàŠŸàŠšà§àŠ€àŠ°: àŠªàŠŸàŠ‡àŠ¥àŠš àŠ¡à§‡àŠŸàŠŸ àŠàŠ¬àŠ‚ àŠŸàŠŸàŠ‡àŠª àŠ¥à§‡àŠ•à§‡ àŠšà§‡àŠŸàŠ“àŠ¯àŠŒàŠŸàŠ°à§àŠ• àŠ¡à§‡àŠŸàŠŸàŠ€à§‡ àŠ°à§‚àŠªàŠŸàŠšà§àŠ€àŠ° àŠ•àŠ°àŠŸ (JSON àŠ¹àŠ¿àŠžàŠŸàŠ¬à§‡): + -àŠªàŠŸàŠ‡àŠ¥àŠš àŠŸàŠŸàŠ‡àŠªà§‡ àŠ°à§‚àŠªàŠŸàŠšà§àŠ€àŠ° àŠ•àŠ°à§àŠš (`str`, `int`, `float`, `bool`, `list`, àŠ‡àŠ€à§àŠ¯àŠŸàŠŠàŠ¿)ी + - `datetime` àŠ…àŠ¬àŠœà§‡àŠ•à§àŠŸà¥€ + - `UUID` objeàŠ…àŠ¬àŠœà§‡àŠ•à§àŠŸctsी + - àŠ¡àŠŸàŠŸàŠŸàŠ¬à§‡àŠž àŠ®àŠ¡à§‡àŠ²à¥€ + - ...àŠàŠ¬àŠ‚ àŠ†àŠ°à§‹ àŠ…àŠšà§‡àŠ•à¥€ +- àŠžà§àŠ¬àŠ¯àŠŒàŠ‚àŠ•à§àŠ°àŠ¿àŠ¯àŠŒ àŠ•à§àŠ°àŠ¿à§ŸàŠŸàŠ¶à§€àŠ² API àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿, 2àŠŸàŠ¿ àŠ¬àŠ¿àŠ•àŠ²à§àŠª àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ°àŠ•àŠŸàŠ°à§€àŠ° àŠ‡àŠšà§àŠŸàŠŸàŠ°àŠ«à§‡àŠž àŠžàŠ¹: + - àŠžà§‹àŠ¯àŠŒàŠŸàŠ—àŠŸàŠ° àŠ‡àŠ‰ àŠ†àŠ‡ (Swagger UI)ी + - àŠ°àŠ¿àŠ¡àŠ• (ReDoc)ी + +--- + +àŠªà§‚àŠ°à§àŠ¬àŠ¬àŠ°à§àŠ€à§€ àŠ•à§‹àŠ¡ àŠ‰àŠŠàŠŸàŠ¹àŠ°àŠ£à§‡ àŠ«àŠ¿àŠ°à§‡ àŠ†àŠžàŠŸ àŠ¯àŠŸàŠ•, **FastAPI** àŠ¯àŠŸ àŠ•àŠ°àŠ¬à§‡: + +- `GET` àŠàŠ¬àŠ‚ `PUT` àŠ…àŠšà§àŠ°à§‹àŠ§à§‡àŠ° àŠœàŠšà§àŠ¯ àŠªàŠ¥à§‡ `item_id` àŠ†àŠ›à§‡ àŠ•àŠ¿àŠšàŠŸ àŠ€àŠŸ àŠ¯àŠŸàŠšàŠŸàŠ‡ àŠ•àŠ°àŠ¬à§‡à¥€ +- `GET` àŠàŠ¬àŠ‚ `PUT` àŠ…àŠšà§àŠ°à§‹àŠ§à§‡àŠ° àŠœàŠšà§àŠ¯ `item_id` àŠŸàŠŸàŠ‡àŠª `int` àŠàŠ° àŠ¹àŠ€à§‡ àŠ¹àŠ¬à§‡ àŠ€àŠŸ àŠ¯àŠŸàŠšàŠŸàŠ‡ àŠ•àŠ°àŠ¬à§‡à¥€ + - àŠ¯àŠŠàŠ¿ àŠšàŠŸ àŠ¹àŠ¯àŠŒ àŠ€àŠ¬à§‡ àŠ•à§àŠ²àŠŸàŠ¯àŠŒà§‡àŠšà§àŠŸ àŠàŠ•àŠŸàŠ¿ àŠ‰àŠªàŠ¯à§àŠ•à§àŠ€, àŠªàŠ°àŠ¿àŠ·à§àŠ•àŠŸàŠ° àŠ€à§àŠ°à§àŠŸàŠ¿ àŠŠà§‡àŠ–àŠ€à§‡ àŠªàŠŸàŠ¬à§‡àŠšà¥€ +- `GET` àŠ…àŠšà§àŠ°à§‹àŠ§à§‡àŠ° àŠœàŠšà§àŠ¯ àŠàŠ•àŠŸàŠ¿ àŠàŠšà§àŠ›àŠ¿àŠ• àŠ•à§àŠ¯à§àŠ¯àŠŒà§‡àŠ°àŠ¿ àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ° àŠšàŠŸàŠ®àŠ• `q` (àŠ¯à§‡àŠ®àŠš `http://127.0.0.1:8000/items/foo?q=somequery`) àŠ†àŠ›à§‡ àŠ•àŠ¿ àŠ€àŠŸ àŠšà§‡àŠ• àŠ•àŠ°àŠ¬à§‡à¥€ + - àŠ¯à§‡àŠ¹à§‡àŠ€à§ `q` àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ°àŠŸàŠ¿ `= None` àŠŠàŠ¿àŠ¯àŠŒà§‡ àŠ˜à§‹àŠ·àŠ£àŠŸ àŠ•àŠ°àŠŸ àŠ¹àŠ¯àŠŒà§‡àŠ›à§‡, àŠ€àŠŸàŠ‡ àŠàŠŸàŠ¿ àŠàŠšà§àŠ›àŠ¿àŠ•à¥€ + - `None` àŠ›àŠŸàŠ¡àŠŒàŠŸ àŠàŠŸàŠ¿ àŠªà§àŠ°àŠ¯àŠŒà§‹àŠœàŠšà§€àŠ¯àŠŒ àŠ¹àŠ€à§‹ (àŠ¯à§‡àŠ®àŠš `PUT` àŠàŠ° àŠ•à§àŠ·à§‡àŠ€à§àŠ°à§‡ àŠ¹à§Ÿà§‡àŠ›à§‡)ी +- `/items/{item_id}` àŠàŠ° àŠœàŠšà§àŠ¯ `PUT` àŠ…àŠšà§àŠ°à§‹àŠ§à§‡àŠ° àŠ¬àŠ¡àŠ¿ JSON àŠ¹àŠ¿àŠžàŠŸàŠ¬à§‡ àŠªàŠ¡àŠŒà§àŠš: + - àŠ²àŠ•à§àŠ· àŠ•àŠ°à§àŠš, `name` àŠàŠ•àŠŸàŠ¿ àŠªà§àŠ°àŠ¯àŠŒà§‹àŠœàŠšà§€àŠ¯àŠŒ àŠ…à§àŠ¯àŠŸàŠŸà§àŠ°àŠ¿àŠ¬àŠ¿àŠ‰àŠŸ àŠ¹àŠ¿àŠžàŠŸàŠ¬à§‡ àŠ¬àŠ¿àŠ¬à§‡àŠšàŠšàŠŸ àŠ•àŠ°à§‡àŠ›à§‡ àŠàŠ¬àŠ‚ àŠàŠŸàŠ¿ `str` àŠ¹àŠ€à§‡ àŠ¹àŠ¬à§‡à¥€ + - àŠ²àŠ•à§àŠ· àŠ•àŠ°à§àŠš àŠàŠ–àŠŸàŠšà§‡, `price` àŠ…à§àŠ¯àŠŸàŠŸà§àŠ°àŠ¿àŠ¬àŠ¿àŠ‰àŠŸàŠŸàŠ¿ àŠ†àŠ¬àŠ¶à§àŠ¯àŠ• àŠàŠ¬àŠ‚ àŠàŠŸàŠ¿ `float` àŠ¹àŠ€à§‡ àŠ¹àŠ¬à§‡à¥€ + - àŠ²àŠ•à§àŠ· àŠ•àŠ°à§àŠš `is_offer` àŠàŠ•àŠŸàŠ¿ àŠàŠšà§àŠ›àŠ¿àŠ• àŠ…à§àŠ¯àŠŸàŠŸà§àŠ°àŠ¿àŠ¬àŠ¿àŠ‰àŠŸ àŠàŠ¬àŠ‚ àŠàŠŸàŠ¿ `bool` àŠ¹àŠ€à§‡ àŠ¹àŠ¬à§‡ àŠ¯àŠŠàŠ¿ àŠ‰àŠªàŠžà§àŠ¥àŠ¿àŠ€ àŠ¥àŠŸàŠ•à§‡à¥€ + - àŠàŠ‡ àŠžàŠ¬àŠŸàŠ¿ àŠ—àŠ­à§€àŠ°àŠ­àŠŸàŠ¬à§‡ àŠ…àŠ¬àŠžà§àŠ¥àŠŸàŠšàŠ°àŠ€ JSON àŠ…àŠ¬àŠœà§‡àŠ•à§àŠŸàŠ—à§àŠ²àŠ¿àŠ€à§‡àŠ“ àŠ•àŠŸàŠœ àŠ•àŠ°àŠ¬à§‡à¥€ +- àŠžà§àŠ¬àŠ¯àŠŒàŠ‚àŠ•à§àŠ°àŠ¿àŠ¯àŠŒàŠ­àŠŸàŠ¬à§‡ JSON àŠ¹àŠ€à§‡ àŠàŠ¬àŠ‚ JSON àŠ¥à§‡àŠ•à§‡ àŠ•àŠšàŠ­àŠŸàŠ°à§àŠŸ àŠ•àŠ°à§àŠšà¥€ +- OpenAPI àŠŠàŠ¿àŠ¯àŠŒà§‡ àŠžàŠ¬àŠ•àŠ¿àŠ›à§ àŠ¡àŠ•à§àŠ®à§‡àŠšà§àŠŸ àŠ•àŠ°à§àŠš, àŠ¯àŠŸ àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°àŠŸ àŠ¯à§‡àŠ€à§‡ àŠªàŠŸàŠ°à§‡: + - àŠ•à§àŠ°àŠ¿à§ŸàŠŸàŠ¶à§€àŠ² àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿à¥€ + - àŠ…àŠšà§‡àŠ• àŠ­àŠŸàŠ·àŠŸàŠ° àŠœàŠšà§àŠ¯ àŠžà§àŠ¬àŠ¯àŠŒàŠ‚àŠ•à§àŠ°àŠ¿àŠ¯àŠŒ àŠ•à§àŠ²àŠŸàŠ¯àŠŒà§‡àŠšà§àŠŸ àŠ•à§‹àŠ¡ àŠ€à§ˆàŠ°àŠ¿àŠ° àŠ¬à§àŠ¯àŠ¬àŠžà§àŠ¥àŠŸà¥€ +- àŠžàŠ°àŠŸàŠžàŠ°àŠ¿ 2àŠŸàŠ¿ àŠ•à§àŠ°àŠ¿à§ŸàŠŸàŠ¶à§€àŠ² àŠšàŠ¿àŠ°à§àŠŠà§‡àŠ¶àŠ¿àŠ•àŠŸ àŠšàŠ¥àŠ¿ àŠ“àŠ¯àŠŒà§‡àŠ¬ àŠªà§ƒàŠ·à§àŠ  àŠªà§àŠ°àŠŠàŠŸàŠš àŠ•àŠ°àŠŸ àŠ¹à§Ÿà§‡àŠ›à§‡à¥€ + +--- + +àŠ†àŠ®àŠ°àŠŸ àŠàŠ€àŠ•à§àŠ·àŠš àŠ¶à§àŠ§à§ àŠàŠ° àŠªà§ƒàŠ·à§àŠ  àŠ€à§ˆàŠ°àŠ¿ àŠ•àŠ°à§‡àŠ›àŠ¿, àŠ•àŠ¿àŠšà§àŠ€à§ àŠ†àŠªàŠšàŠ¿ àŠ‡àŠ€àŠ®àŠ§à§àŠ¯à§‡àŠ‡ àŠàŠŸàŠ¿ àŠ•àŠ¿àŠ­àŠŸàŠ¬à§‡ àŠ•àŠŸàŠœ àŠ•àŠ°à§‡ àŠ€àŠŸàŠ° àŠ§àŠŸàŠ°àŠ£àŠŸàŠ“ àŠªà§‡à§Ÿà§‡ àŠ—àŠ¿à§Ÿà§‡àŠ›à§‡àŠšà¥€ + +àŠšàŠ¿àŠ®à§àŠšà§‹àŠ•à§àŠ€ àŠ²àŠŸàŠ‡àŠš àŠ—à§àŠ²à§‹ àŠªàŠ°àŠ¿àŠ¬àŠ°à§àŠ€àŠš àŠ•àŠ°àŠŸàŠ° àŠšà§‡àŠ·à§àŠŸàŠŸ àŠ•àŠ°à§àŠš: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...àŠªà§àŠ°à§àŠ¬à§‡: + +```Python + ... "item_name": item.name ... +``` + +...àŠªàŠ°àŠ¬àŠ°à§àŠ€à§€àŠ€à§‡: + +```Python + ... "item_price": item.price ... +``` + +...àŠàŠ¬àŠ‚ àŠŠà§‡àŠ–à§àŠš àŠ•àŠ¿àŠ­àŠŸàŠ¬à§‡ àŠ†àŠªàŠšàŠŸàŠ° àŠàŠ¡àŠ¿àŠŸàŠ° àŠ‰àŠªàŠŸàŠŠàŠŸàŠšàŠ—à§àŠ²à§‹àŠ•à§‡ àŠžà§ŸàŠ‚àŠ•à§àŠ°àŠ¿à§ŸàŠ­àŠŸàŠ¬à§‡-àŠžàŠ®à§àŠªàŠšà§àŠš àŠ•àŠ°àŠ¬à§‡ àŠàŠ¬àŠ‚ àŠ€àŠŸàŠŠà§‡àŠ° àŠ§àŠ°àŠš àŠœàŠŸàŠšàŠ€à§‡ àŠªàŠŸàŠ°àŠ¬à§‡: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +àŠ†àŠ°àŠ“ àŠ¬à§ˆàŠ¶àŠ¿àŠ·à§àŠŸà§àŠ¯ àŠžàŠ®à§àŠªàŠšà§àŠš àŠ‰àŠŠàŠŸàŠ¹àŠ°àŠ£à§‡àŠ° àŠœàŠšà§àŠ¯, àŠŠà§‡àŠ–à§àŠš àŠŸàŠ¿àŠ‰àŠŸà§‹àŠ°àŠ¿à§ŸàŠŸàŠ² - àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ°àŠ•àŠŸàŠ°à§€àŠ° àŠ—àŠŸàŠ‡àŠ¡. + +**àŠžà§àŠªà§ŸàŠ²àŠŸàŠ° àŠžàŠ€àŠ°à§àŠ•àŠ€àŠŸ**: àŠŸàŠ¿àŠ‰àŠŸà§‹àŠ°àŠ¿à§ŸàŠŸàŠ² - àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ°àŠ•àŠŸàŠ°à§€àŠ° àŠ—àŠŸàŠ‡àŠ¡ àŠšàŠ¿àŠ®à§àŠšà§‹àŠ•à§àŠ€ àŠ¬àŠ¿àŠ·à§ŸàŠ—à§àŠ²àŠ¿ àŠ…àŠšà§àŠ€àŠ°à§àŠ­à§àŠ•à§àŠ€ àŠ•àŠ°à§‡: + +- **àŠ¹à§‡àŠ¡àŠŸàŠ°**, **àŠ•à§àŠ•àŠ¿àŠœ**, **àŠ«àŠ°à§àŠ® àŠ«àŠ¿àŠ²à§àŠ¡** àŠàŠ¬àŠ‚ **àŠ«àŠŸàŠ‡àŠ²àŠ—à§àŠ²àŠ¿** àŠàŠ®àŠš àŠ…àŠšà§àŠ¯àŠŸàŠšà§àŠ¯ àŠœàŠŸà§ŸàŠ—àŠŸ àŠ¥à§‡àŠ•à§‡ àŠªà§àŠ¯àŠŸàŠ°àŠŸàŠ®àŠ¿àŠŸàŠŸàŠ° àŠ˜à§‹àŠ·àŠ£àŠŸ àŠ•àŠ°àŠŸà¥€ +- `maximum_length` àŠ¬àŠŸ `regex` àŠàŠ° àŠ®àŠ€à§‹ **àŠ¯àŠŸàŠšàŠŸàŠ‡àŠ•àŠ°àŠ£ àŠ¬àŠŸàŠ§àŠŸàŠ®à§àŠ•à§àŠ€àŠ¿** àŠžà§‡àŠŸ àŠ•àŠ°àŠŸ àŠ¹àŠ¯àŠŒ àŠ•àŠ¿àŠ­àŠŸàŠ¬à§‡, àŠ€àŠŸ àŠšàŠ¿à§Ÿà§‡ àŠ†àŠ²à§‹àŠšàŠšàŠŸ àŠ•àŠ°àŠŸ àŠ¹àŠ¬à§‡à¥€ +- àŠàŠ•àŠŸàŠ¿ àŠ–à§àŠ¬ àŠ¶àŠ•à§àŠ€àŠ¿àŠ¶àŠŸàŠ²à§€ àŠàŠ¬àŠ‚ àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°àŠŸ àŠžàŠ¹àŠœ àŠ¡àŠ¿àŠªà§‡àŠšà§àŠ¡à§‡àŠšà§àŠžàŠ¿ àŠ‡àŠšàŠœà§‡àŠ•àŠ¶àŠš àŠªàŠŠà§àŠ§àŠ€àŠ¿ +- **OAuth2** àŠàŠ¬àŠ‚ **JWT àŠŸà§‹àŠ•à§‡àŠš** àŠàŠ¬àŠ‚ **HTTP Basic** auth àŠžàŠ¹ àŠšàŠ¿àŠ°àŠŸàŠªàŠ€à§àŠ€àŠŸ àŠàŠ¬àŠ‚ àŠ…àŠšà§àŠ®à§‹àŠŠàŠšàŠªà§àŠ°àŠŸàŠªà§àŠ€àŠ¿ àŠžàŠ®à§àŠªàŠ°à§àŠ•àŠ¿àŠ€ àŠ¬àŠ¿àŠ·à§ŸàŠžàŠ®à§‚àŠ¹à§‡àŠ° àŠ‰àŠªàŠ°à¥€ +- **àŠ—àŠ­à§€àŠ°àŠ­àŠŸàŠ¬à§‡ àŠ…àŠ¬àŠžà§àŠ¥àŠŸàŠšàŠ°àŠ€ JSON àŠ®àŠ¡à§‡àŠ²** àŠ˜à§‹àŠ·àŠ£àŠŸ àŠ•àŠ°àŠŸàŠ° àŠœàŠšà§àŠ¯ àŠ†àŠ°àŠ“ àŠ‰àŠšà§àŠšàŠ€ (àŠ•àŠ¿àŠšà§àŠ€à§ àŠžàŠ®àŠŸàŠš àŠžàŠ¹àŠœ) àŠ•à§ŒàŠ¶àŠ² (Pydantic àŠ•à§‡ àŠ§àŠšà§àŠ¯àŠ¬àŠŸàŠŠ)ी +- àŠ†àŠ°à§‹ àŠ…àŠ€àŠ¿àŠ°àŠ¿àŠ•à§àŠ€ àŠ¬à§ˆàŠ¶àŠ¿àŠ·à§àŠŸà§àŠ¯ (àŠžà§àŠŸàŠŸàŠ°àŠ²à§‡àŠŸàŠ•à§‡ àŠ§àŠšà§àŠ¯àŠ¬àŠŸàŠŠ) àŠ¹àŠ¿àŠžàŠŸàŠ¬à§‡: + - **WebSockets** + - **GraphQL** + - HTTPX àŠàŠ¬àŠ‚ `pytest` àŠ­àŠ¿àŠ€à§àŠ€àŠ¿àŠ• àŠ…àŠ€à§àŠ¯àŠšà§àŠ€ àŠžàŠ¹àŠœ àŠªàŠ°à§€àŠ•à§àŠ·àŠŸ + - **CORS** + - **Cookie Sessions** + - ...àŠàŠ¬àŠ‚ àŠ†àŠ°à§‹à¥€ + +## àŠ•àŠ°à§àŠ®àŠ•à§àŠ·àŠ®àŠ€àŠŸ + +àŠžà§àŠ¬àŠŸàŠ§à§€àŠš TechEmpower Benchmarks àŠŠà§‡àŠ–àŠŸàŠ¯àŠŒ àŠ¯à§‡ **FastAPI** àŠ…à§àŠ¯àŠŸàŠªà§àŠ²àŠ¿àŠ•à§‡àŠ¶àŠšàŠ—à§àŠ²àŠ¿ Uvicorn-àŠàŠ° àŠ…àŠ§à§€àŠšà§‡ àŠšàŠ²àŠ®àŠŸàŠš àŠŠà§àŠ°à§àŠ€àŠ€àŠ®àŠªàŠŸàŠ‡àŠ¥àŠš àŠ«à§àŠ°à§‡àŠ®àŠ“àŠ¯àŠŒàŠŸàŠ°à§àŠ•àŠ—à§àŠ²àŠ¿àŠ° àŠ®àŠ§à§àŠ¯à§‡ àŠàŠ•àŠŸàŠ¿, àŠ¶à§àŠ§à§àŠ®àŠŸàŠ€à§àŠ° Starlette àŠàŠ¬àŠ‚ Uvicorn-àŠàŠ° àŠªàŠ° (FastAPI àŠŠà§àŠ¬àŠŸàŠ°àŠŸ àŠ…àŠ­à§àŠ¯àŠšà§àŠ€àŠ°à§€àŠ£àŠ­àŠŸàŠ¬à§‡ àŠ¬à§àŠ¯àŠ¬àŠ¹à§ƒàŠ€)ी (\*) + +àŠàŠŸàŠ¿ àŠžàŠ®à§àŠªàŠ°à§àŠ•à§‡ àŠ†àŠ°àŠ“ àŠ¬à§àŠàŠ€à§‡, àŠŠà§‡àŠ–à§àŠš Benchmarks. + +## àŠàŠšà§àŠ›àŠ¿àŠ• àŠšàŠ¿àŠ°à§àŠ­àŠ°àŠ¶à§€àŠ²àŠ€àŠŸ + +Pydantic àŠŠà§àŠ¬àŠŸàŠ°àŠŸ àŠ¬à§àŠ¯àŠ¬àŠ¹à§ƒàŠ€: + +- ujson - àŠŠà§àŠ°à§àŠ€ JSON àŠàŠ° àŠœàŠšà§àŠ¯ "parsing". +- email_validator - àŠ‡àŠ®à§‡àŠ² àŠ¯àŠŸàŠšàŠŸàŠ‡àŠ•àŠ°àŠ£à§‡àŠ° àŠœàŠšà§àŠ¯à¥€ + +àŠžà§àŠŸàŠŸàŠ°àŠ²à§‡àŠŸ àŠŠà§àŠ¬àŠŸàŠ°àŠŸ àŠ¬à§àŠ¯àŠ¬àŠ¹à§ƒàŠ€: + +- httpx - àŠ†àŠªàŠšàŠ¿ àŠ¯àŠŠàŠ¿ `TestClient` àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°àŠ€à§‡ àŠšàŠŸàŠš àŠ€àŠŸàŠ¹àŠ²à§‡ àŠ†àŠ¬àŠ¶à§àŠ¯àŠ•à¥€ +- jinja2 - àŠ†àŠªàŠšàŠ¿ àŠ¯àŠŠàŠ¿ àŠªà§àŠ°àŠŠàŠ€à§àŠ€ àŠŸà§‡àŠ®àŠªà§àŠ²à§‡àŠŸ àŠ°à§‚àŠªàŠ°à§‡àŠ–àŠŸ àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°àŠ€à§‡ àŠšàŠŸàŠš àŠ€àŠŸàŠ¹àŠ²à§‡ àŠªà§àŠ°àŠ¯àŠŒà§‹àŠœàŠšà¥€ +- python-multipart - àŠ†àŠªàŠšàŠ¿ àŠ¯àŠŠàŠ¿ àŠ«àŠ°à§àŠ® àŠžàŠ¹àŠŸàŠ¯àŠŒàŠ€àŠŸ àŠ•àŠ°àŠ€à§‡ àŠšàŠŸàŠš àŠ€àŠŸàŠ¹àŠ²à§‡ àŠªà§àŠ°àŠ¯àŠŒà§‹àŠœàŠš "parsing", `request.form()` àŠžàŠ¹à¥€ +- itsdangerous - `SessionMiddleware` àŠžàŠ¹àŠŸàŠ¯àŠŒàŠ€àŠŸàŠ° àŠœàŠšà§àŠ¯ àŠªà§àŠ°àŠ¯àŠŒà§‹àŠœàŠšà¥€ +- pyyaml - àŠžà§àŠŸàŠŸàŠ°àŠ²à§‡àŠŸà§‡àŠ° SchemaGenerator àŠžàŠŸàŠªà§‹àŠ°à§àŠŸ àŠàŠ° àŠœàŠšà§àŠ¯ àŠªà§àŠ°à§Ÿà§‹àŠœàŠš (àŠ†àŠªàŠšàŠŸàŠ° àŠžàŠ®à§àŠ­àŠŸàŠ¬àŠ€ FastAPI àŠªà§àŠ°àŠ¯àŠŒà§‹àŠœàŠš àŠšà§‡àŠ‡)ी +- graphene - `GraphQLApp` àŠžàŠ¹àŠŸàŠ¯àŠŒàŠ€àŠŸàŠ° àŠœàŠšà§àŠ¯ àŠªà§àŠ°à§Ÿà§‹àŠœàŠšà¥€ +- ujson - àŠ†àŠªàŠšàŠ¿ `UJSONResponse` àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°àŠ€à§‡ àŠšàŠŸàŠ‡àŠ²à§‡ àŠªà§àŠ°àŠ¯àŠŒà§‹àŠœàŠšà¥€ + +FastAPI / Starlette àŠŠà§àŠ¬àŠŸàŠ°àŠŸ àŠ¬à§àŠ¯àŠ¬àŠ¹à§ƒàŠ€: + +- uvicorn - àŠžàŠŸàŠ°à§àŠ­àŠŸàŠ°à§‡àŠ° àŠœàŠšà§àŠ¯ àŠ¯àŠŸ àŠ†àŠªàŠšàŠŸàŠ° àŠ…à§àŠ¯àŠŸàŠªà§àŠ²àŠ¿àŠ•à§‡àŠ¶àŠš àŠ²à§‹àŠ¡ àŠ•àŠ°à§‡ àŠàŠ¬àŠ‚ àŠªàŠ°àŠ¿àŠ¬à§‡àŠ¶àŠš àŠ•àŠ°à§‡à¥€ +- orjson - àŠ†àŠªàŠšàŠ¿ `ORJSONResponse` àŠ¬à§àŠ¯àŠ¬àŠ¹àŠŸàŠ° àŠ•àŠ°àŠ€à§‡ àŠšàŠŸàŠ‡àŠ²à§‡ àŠªà§àŠ°àŠ¯àŠŒà§‹àŠœàŠšà¥€ + +àŠ†àŠªàŠšàŠ¿ àŠàŠ‡ àŠžàŠ¬ àŠ‡àŠšàŠžà§àŠŸàŠ² àŠ•àŠ°àŠ€à§‡ àŠªàŠŸàŠ°à§‡àŠš `pip install fastapi[all]` àŠŠàŠ¿à§Ÿà§‡. + +## àŠ²àŠŸàŠ‡àŠžà§‡àŠšà§àŠž + +àŠàŠ‡ àŠªà§àŠ°àŠœà§‡àŠ•à§àŠŸ MIT àŠ²àŠŸàŠ‡àŠžà§‡àŠšà§àŠž àŠšà§€àŠ€àŠ¿àŠ®àŠŸàŠ²àŠŸàŠ° àŠ…àŠ§à§€àŠšà§‡ àŠ¶àŠ°à§àŠ€àŠŸà§ŸàŠ¿àŠ€à¥€ diff --git a/docs/bn/mkdocs.yml b/docs/bn/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/bn/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml From 1cd23a1dbce8f2fd7f15ece57c3cd45a2cb04cac Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 10 Jan 2024 17:43:56 +0000 Subject: [PATCH 110/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6885ef68d7e4a..f3c70489b6782 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Translations +* 🌐 Add Bengali translation for `docs/bn/docs/index.md`. PR [#9177](https://github.com/tiangolo/fastapi/pull/9177) by [@Fahad-Md-Kamal](https://github.com/Fahad-Md-Kamal). * ✏ Update Python version in `index.md` in several languages. PR [#10711](https://github.com/tiangolo/fastapi/pull/10711) by [@tamago3keran](https://github.com/tamago3keran). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-forms-and-files.md`. PR [#10347](https://github.com/tiangolo/fastapi/pull/10347) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Ukrainian translation for `docs/uk/docs/index.md`. PR [#10362](https://github.com/tiangolo/fastapi/pull/10362) by [@rostik1410](https://github.com/rostik1410). From 843bc85155be86d7688ab126bb7ea266d410bf71 Mon Sep 17 00:00:00 2001 From: Sungyun Hur Date: Thu, 11 Jan 2024 03:15:04 +0900 Subject: [PATCH 111/217] =?UTF-8?q?=F0=9F=93=9D=20Fix=20broken=20link=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/sql-databases.md`=20(#10765)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/docs/tutorial/sql-databases.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 010244bbf6f14..ce6507912252e 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -624,7 +624,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ``` !!! info - If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../advanced/async-sql-databases.md){.internal-link target=_blank}. + If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}. !!! note "Very Technical Details" If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs. From 1334485435ce0e934a965b23912654baab5d861d Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 10 Jan 2024 18:15:28 +0000 Subject: [PATCH 112/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f3c70489b6782..b0a6c8dc6f38a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix broken link in `docs/en/docs/tutorial/sql-databases.md`. PR [#10765](https://github.com/tiangolo/fastapi/pull/10765) by [@HurSungYun](https://github.com/HurSungYun). * 📝 Add External Link: FastAPI application monitoring made easy. PR [#10917](https://github.com/tiangolo/fastapi/pull/10917) by [@tiangolo](https://github.com/tiangolo). * ✹ Generate automatic language names for docs translations. PR [#5354](https://github.com/tiangolo/fastapi/pull/5354) by [@jakul](https://github.com/jakul). * ✏ Fix typos in `docs/en/docs/alternatives.md` and `docs/en/docs/tutorial/dependencies/index.md`. PR [#10906](https://github.com/tiangolo/fastapi/pull/10906) by [@s111d](https://github.com/s111d). From b584faffee11bfc08bea3bd2d66c304701b921d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 10 Jan 2024 23:13:55 +0400 Subject: [PATCH 113/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20notes=20about=20Py?= =?UTF-8?q?dantic=20v2's=20new=20`.model=5Fdump()`=20(#10929)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/how-to/async-sql-encode-databases.md | 5 +++++ docs/en/docs/tutorial/body-updates.md | 20 ++++++++++++++----- docs/en/docs/tutorial/extra-models.md | 5 +++++ docs/en/docs/tutorial/response-model.md | 5 +++++ docs/en/docs/tutorial/sql-databases.md | 5 +++++ 5 files changed, 35 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md index 697167f790267..0e2ccce78dbc3 100644 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ b/docs/en/docs/how-to/async-sql-encode-databases.md @@ -114,6 +114,11 @@ Create the *path operation function* to create notes: {!../../../docs_src/async_sql_databases/tutorial001.py!} ``` +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + !!! Note Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 3341f2d5d88b4..39d133c55f3dd 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -59,9 +59,14 @@ This means that you can send only the data that you want to update, leaving the ### Using Pydantic's `exclude_unset` parameter -If you want to receive partial updates, it's very useful to use the parameter `exclude_unset` in Pydantic's model's `.dict()`. +If you want to receive partial updates, it's very useful to use the parameter `exclude_unset` in Pydantic's model's `.model_dump()`. -Like `item.dict(exclude_unset=True)`. +Like `item.model_dump(exclude_unset=True)`. + +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. That would generate a `dict` with only the data that was set when creating the `item` model, excluding default values. @@ -87,9 +92,14 @@ Then you can use this to generate a `dict` with only the data that was set (sent ### Using Pydantic's `update` parameter -Now, you can create a copy of the existing model using `.copy()`, and pass the `update` parameter with a `dict` containing the data to update. +Now, you can create a copy of the existing model using `.model_copy()`, and pass the `update` parameter with a `dict` containing the data to update. + +!!! info + In Pydantic v1 the method was called `.copy()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_copy()`. + + The examples here use `.copy()` for compatibility with Pydantic v1, but you should use `.model_copy()` instead if you can use Pydantic v2. -Like `stored_item_model.copy(update=update_data)`: +Like `stored_item_model.model_copy(update=update_data)`: === "Python 3.10+" @@ -120,7 +130,7 @@ In summary, to apply partial updates you would: * This way you can update only the values actually set by the user, instead of overriding values already stored with default values in your model. * Create a copy of the stored model, updating it's attributes with the received partial updates (using the `update` parameter). * Convert the copied model to something that can be stored in your DB (for example, using the `jsonable_encoder`). - * This is comparable to using the model's `.dict()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`. + * This is comparable to using the model's `.model_dump()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`. * Save the data to your DB. * Return the updated model. diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index 590d095bd2457..d83b6bc8594bb 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -29,6 +29,11 @@ Here's a general idea of how the models could look like with their password fiel {!> ../../../docs_src/extra_models/tutorial001.py!} ``` +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + ### About `**user_in.dict()` #### Pydantic's `.dict()` diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index d6d3d61cb4b24..d5683ac7f2e8a 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -377,6 +377,11 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t } ``` +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + !!! info FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this. diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index ce6507912252e..1bc87a702d1b8 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -451,6 +451,11 @@ The steps are: {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + !!! tip The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password. From 91d7fb6d255156a753108b4f762a4f12b8861961 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 10 Jan 2024 19:14:15 +0000 Subject: [PATCH 114/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b0a6c8dc6f38a..ab64e33d0ae84 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add notes about Pydantic v2's new `.model_dump()`. PR [#10929](https://github.com/tiangolo/fastapi/pull/10929) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix broken link in `docs/en/docs/tutorial/sql-databases.md`. PR [#10765](https://github.com/tiangolo/fastapi/pull/10765) by [@HurSungYun](https://github.com/HurSungYun). * 📝 Add External Link: FastAPI application monitoring made easy. PR [#10917](https://github.com/tiangolo/fastapi/pull/10917) by [@tiangolo](https://github.com/tiangolo). * ✹ Generate automatic language names for docs translations. PR [#5354](https://github.com/tiangolo/fastapi/pull/5354) by [@jakul](https://github.com/jakul). From 07f8d31ec9d6e2234e12515f3373f57020b1726d Mon Sep 17 00:00:00 2001 From: Aliaksei Urbanski Date: Wed, 10 Jan 2024 23:55:45 +0300 Subject: [PATCH 115/217] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20Pytho?= =?UTF-8?q?n=203.12=20(#10666)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- .github/workflows/test.yml | 7 ++++++- docs_src/security/tutorial004.py | 6 +++--- docs_src/security/tutorial004_an.py | 6 +++--- docs_src/security/tutorial004_an_py310.py | 6 +++--- docs_src/security/tutorial004_an_py39.py | 6 +++--- docs_src/security/tutorial004_py310.py | 6 +++--- docs_src/security/tutorial005.py | 6 +++--- docs_src/security/tutorial005_an.py | 6 +++--- docs_src/security/tutorial005_an_py310.py | 6 +++--- docs_src/security/tutorial005_an_py39.py | 6 +++--- docs_src/security/tutorial005_py310.py | 6 +++--- docs_src/security/tutorial005_py39.py | 6 +++--- pyproject.toml | 10 ++++++++++ 13 files changed, 49 insertions(+), 34 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7ebb80efdfc99..032db9c9c85b4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -42,7 +42,12 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.8", "3.9", "3.10", "3.11"] + python-version: + - "3.12" + - "3.11" + - "3.10" + - "3.9" + - "3.8" pydantic-version: ["pydantic-v1", "pydantic-v2"] fail-fast: false steps: diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index 64099abe9cffe..134c15c5a0369 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Union from fastapi import Depends, FastAPI, HTTPException, status @@ -78,9 +78,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index ca350343d2082..204151a566485 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Union from fastapi import Depends, FastAPI, HTTPException, status @@ -79,9 +79,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 8bf5f3b7185cd..64dfa15c62718 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, status @@ -78,9 +78,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index a634e23de9843..631a8366eb81b 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated, Union from fastapi import Depends, FastAPI, HTTPException, status @@ -78,9 +78,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 797d56d0431ab..470f22e29f03b 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm @@ -77,9 +77,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py index bd0a33581c21c..ece461bc8ac36 100644 --- a/docs_src/security/tutorial005.py +++ b/docs_src/security/tutorial005.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import List, Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index ec4fa1a07e2cd..c5b5609e525e0 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import List, Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -94,9 +94,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 45f3fc0bd6de1..5e81a50e12d63 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index ecb5ed5160d86..ae9811c689f5b 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated, List, Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index ba756ef4f4d67..0fcdda4c004c6 100644 --- a/docs_src/security/tutorial005_py310.py +++ b/docs_src/security/tutorial005_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( @@ -92,9 +92,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py index 9e4dbcffba38d..d756c0b6b87f9 100644 --- a/docs_src/security/tutorial005_py39.py +++ b/docs_src/security/tutorial005_py39.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt diff --git a/pyproject.toml b/pyproject.toml index 38728d99e945b..2fde7553a8759 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,6 +36,7 @@ classifiers = [ "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "Topic :: Internet :: WWW/HTTP :: HTTP Servers", "Topic :: Internet :: WWW/HTTP", ] @@ -111,6 +112,15 @@ filterwarnings = [ "ignore::trio.TrioDeprecationWarning", # TODO remove pytest-cov 'ignore::pytest.PytestDeprecationWarning:pytest_cov', + # TODO: remove after upgrading SQLAlchemy to a version that includes the following changes + # https://github.com/sqlalchemy/sqlalchemy/commit/59521abcc0676e936b31a523bd968fc157fef0c2 + 'ignore:datetime\.datetime\.utcfromtimestamp\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:sqlalchemy', + # TODO: remove after upgrading python-jose to a version that explicitly supports Python 3.12 + # also, if it won't receive an update, consider replacing python-jose with some alternative + # related issues: + # - https://github.com/mpdavis/python-jose/issues/332 + # - https://github.com/mpdavis/python-jose/issues/334 + 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', ] [tool.coverage.run] From 21145d8e9f896502ae227678c63467fb00384cfa Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 10 Jan 2024 20:56:59 +0000 Subject: [PATCH 116/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ab64e33d0ae84..25219b32800af 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Features + +* ✹ Add support for Python 3.12. PR [#10666](https://github.com/tiangolo/fastapi/pull/10666) by [@Jamim](https://github.com/Jamim). + ### Docs * 📝 Add notes about Pydantic v2's new `.model_dump()`. PR [#10929](https://github.com/tiangolo/fastapi/pull/10929) by [@tiangolo](https://github.com/tiangolo). From 135dcba746cdaf2b4726f4f10fad9eb8bb91e342 Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Wed, 10 Jan 2024 22:00:32 +0100 Subject: [PATCH 117/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20VS=20Code=20tutori?= =?UTF-8?q?al=20link=20(#10592)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index d9cfe3431d093..f15560d1b6a8b 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ Articles: English: + - author: Visual Studio Code Team + author_link: https://code.visualstudio.com/ + link: https://code.visualstudio.com/docs/python/tutorial-fastapi + title: FastAPI Tutorial in Visual Studio Code - author: Apitally author_link: https://apitally.io link: https://blog.apitally.io/fastapi-application-monitoring-made-easy From 0da980cb0b73c8cb5713d95d44620c41c0a29b5d Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 10 Jan 2024 21:00:51 +0000 Subject: [PATCH 118/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 25219b32800af..b523be75dfc7c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* 📝 Add VS Code tutorial link. PR [#10592](https://github.com/tiangolo/fastapi/pull/10592) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add notes about Pydantic v2's new `.model_dump()`. PR [#10929](https://github.com/tiangolo/fastapi/pull/10929) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix broken link in `docs/en/docs/tutorial/sql-databases.md`. PR [#10765](https://github.com/tiangolo/fastapi/pull/10765) by [@HurSungYun](https://github.com/HurSungYun). * 📝 Add External Link: FastAPI application monitoring made easy. PR [#10917](https://github.com/tiangolo/fastapi/pull/10917) by [@tiangolo](https://github.com/tiangolo). From 69cb005f61239a378a7e0715cc5e3ff4b713ab4d Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Thu, 11 Jan 2024 15:33:05 +0100 Subject: [PATCH 119/217] =?UTF-8?q?=F0=9F=93=9D=20Replace=20`email`=20with?= =?UTF-8?q?=20`username`=20in=20`docs=5Fsrc/security/tutorial007`=20code?= =?UTF-8?q?=20examples=20(#10649)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/security/http-basic-auth.md | 6 +++--- docs_src/security/tutorial007.py | 2 +- docs_src/security/tutorial007_an.py | 2 +- docs_src/security/tutorial007_an_py39.py | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md index 6f9002f608022..680f4dff53e6c 100644 --- a/docs/en/docs/advanced/security/http-basic-auth.md +++ b/docs/en/docs/advanced/security/http-basic-auth.md @@ -105,7 +105,7 @@ if "johndoe" == "stanleyjobson" and "love123" == "swordfish": ... ``` -But right at the moment Python compares the first `j` in `johndoe` to the first `s` in `stanleyjobson`, it will return `False`, because it already knows that those two strings are not the same, thinking that "there's no need to waste more computation comparing the rest of the letters". And your application will say "incorrect user or password". +But right at the moment Python compares the first `j` in `johndoe` to the first `s` in `stanleyjobson`, it will return `False`, because it already knows that those two strings are not the same, thinking that "there's no need to waste more computation comparing the rest of the letters". And your application will say "Incorrect username or password". But then the attackers try with username `stanleyjobsox` and password `love123`. @@ -116,11 +116,11 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ... ``` -Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "incorrect user or password". +Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "Incorrect username or password". #### The time to answer helps the attackers -At that point, by noticing that the server took some microseconds longer to send the "incorrect user or password" response, the attackers will know that they got _something_ right, some of the initial letters were right. +At that point, by noticing that the server took some microseconds longer to send the "Incorrect username or password" response, the attackers will know that they got _something_ right, some of the initial letters were right. And then they can try again knowing that it's probably something more similar to `stanleyjobsox` than to `johndoe`. diff --git a/docs_src/security/tutorial007.py b/docs_src/security/tutorial007.py index 790ee10bc6b1d..ac816eb0c19d2 100644 --- a/docs_src/security/tutorial007.py +++ b/docs_src/security/tutorial007.py @@ -22,7 +22,7 @@ def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", + detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username diff --git a/docs_src/security/tutorial007_an.py b/docs_src/security/tutorial007_an.py index 5fb7c8e57560c..9e9c3cd7020f0 100644 --- a/docs_src/security/tutorial007_an.py +++ b/docs_src/security/tutorial007_an.py @@ -25,7 +25,7 @@ def get_current_username( if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", + detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username diff --git a/docs_src/security/tutorial007_an_py39.py b/docs_src/security/tutorial007_an_py39.py index 17177dabf9e47..3d9ea27269eed 100644 --- a/docs_src/security/tutorial007_an_py39.py +++ b/docs_src/security/tutorial007_an_py39.py @@ -25,7 +25,7 @@ def get_current_username( if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", + detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username From 5b1e6865c50207ad24d26b55f3577b5c3b8244b3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 14:33:27 +0000 Subject: [PATCH 120/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b523be75dfc7c..f95ccff5672b1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* 📝 Replace `email` with `username` in `docs_src/security/tutorial007` code examples. PR [#10649](https://github.com/tiangolo/fastapi/pull/10649) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add VS Code tutorial link. PR [#10592](https://github.com/tiangolo/fastapi/pull/10592) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add notes about Pydantic v2's new `.model_dump()`. PR [#10929](https://github.com/tiangolo/fastapi/pull/10929) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix broken link in `docs/en/docs/tutorial/sql-databases.md`. PR [#10765](https://github.com/tiangolo/fastapi/pull/10765) by [@HurSungYun](https://github.com/HurSungYun). From c46eba8004cc688ebfb4d9bf4074ccc8c6f0ca3e Mon Sep 17 00:00:00 2001 From: s111d Date: Thu, 11 Jan 2024 17:33:57 +0300 Subject: [PATCH 121/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`docs/en/docs/alternatives.md`=20(#10931)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/docs/alternatives.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index e02b3b55a113b..70bbcac91c3cb 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -191,7 +191,7 @@ This solved having to write YAML (another syntax) inside of Python docstrings. This combination of Flask, Flask-apispec with Marshmallow and Webargs was my favorite backend stack until building **FastAPI**. -Using it led to the creation of several Flask full-stack generators. These are the main stack I (and several external teams) have been using up to now: +Using it led to the creation of several Flask full-stack generators. These are the main stacks I (and several external teams) have been using up to now: * https://github.com/tiangolo/full-stack * https://github.com/tiangolo/full-stack-flask-couchbase @@ -211,7 +211,7 @@ This isn't even Python, NestJS is a JavaScript (TypeScript) NodeJS framework ins It achieves something somewhat similar to what can be done with Flask-apispec. -It has an integrated dependency injection system, inspired by Angular two. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition. +It has an integrated dependency injection system, inspired by Angular 2. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition. As the parameters are described with TypeScript types (similar to Python type hints), editor support is quite good. From c3e062542375f1c8c9e645ca1889872e51e97ed4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 14:35:15 +0000 Subject: [PATCH 122/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f95ccff5672b1..0ec3fd4f51f8a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* ✏ Fix typo in `docs/en/docs/alternatives.md`. PR [#10931](https://github.com/tiangolo/fastapi/pull/10931) by [@s111d](https://github.com/s111d). * 📝 Replace `email` with `username` in `docs_src/security/tutorial007` code examples. PR [#10649](https://github.com/tiangolo/fastapi/pull/10649) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add VS Code tutorial link. PR [#10592](https://github.com/tiangolo/fastapi/pull/10592) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add notes about Pydantic v2's new `.model_dump()`. PR [#10929](https://github.com/tiangolo/fastapi/pull/10929) by [@tiangolo](https://github.com/tiangolo). From 5e583199b3ad252a3539f1d865e36d3c9ae61318 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 11 Jan 2024 19:29:54 +0400 Subject: [PATCH 123/217] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20Starlett?= =?UTF-8?q?e=20to=20>=3D0.35.0,<0.36.0=20(#10938)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 2fde7553a8759..8e7f8bbbe5914 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.29.0,<0.33.0", + "starlette>=0.35.0,<0.36.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] @@ -121,6 +121,9 @@ filterwarnings = [ # - https://github.com/mpdavis/python-jose/issues/332 # - https://github.com/mpdavis/python-jose/issues/334 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', + # TODO: remove after upgrading Starlette to a version including https://github.com/encode/starlette/pull/2406 + # Probably Starlette 0.36.0 + "ignore: The 'method' parameter is not used, and it will be removed.:DeprecationWarning:starlette", ] [tool.coverage.run] From 7c1aeb5db21593421d96fa226461569c77f973eb Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 15:30:35 +0000 Subject: [PATCH 124/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0ec3fd4f51f8a..3395215af38db 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * ✹ Add support for Python 3.12. PR [#10666](https://github.com/tiangolo/fastapi/pull/10666) by [@Jamim](https://github.com/Jamim). +### Upgrades + +* ⬆ Upgrade Starlette to >=0.35.0,<0.36.0. PR [#10938](https://github.com/tiangolo/fastapi/pull/10938) by [@tiangolo](https://github.com/tiangolo). + ### Docs * ✏ Fix typo in `docs/en/docs/alternatives.md`. PR [#10931](https://github.com/tiangolo/fastapi/pull/10931) by [@s111d](https://github.com/s111d). From cb95d1cb8927292fc096834a62c3aa46af46e4ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 11 Jan 2024 16:32:00 +0100 Subject: [PATCH 125/217] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.10?= =?UTF-8?q?9.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3395215af38db..d75d9e3bd90f2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.109.0 + ### Features * ✹ Add support for Python 3.12. PR [#10666](https://github.com/tiangolo/fastapi/pull/10666) by [@Jamim](https://github.com/Jamim). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 02ac83b5e4aee..f457fafd4aa64 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.108.0" +__version__ = "0.109.0" from starlette import status as status From 6bda1326a47968a1e81888da39397c4460368bb8 Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Thu, 11 Jan 2024 16:59:27 +0100 Subject: [PATCH 126/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20location=20info=20?= =?UTF-8?q?to=20`tutorial/bigger-applications.md`=20(#10552)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/em/docs/tutorial/bigger-applications.md | 26 ++++++++--------- docs/en/docs/tutorial/bigger-applications.md | 30 ++++++++++---------- docs/zh/docs/tutorial/bigger-applications.md | 26 ++++++++--------- 3 files changed, 41 insertions(+), 41 deletions(-) diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index 7b4694387dd9b..c30bba106afa4 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -79,7 +79,7 @@ 👆 🗄 ⚫ & ✍ "👐" 🎏 🌌 👆 🔜 ⏮ 🎓 `FastAPI`: -```Python hl_lines="1 3" +```Python hl_lines="1 3" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -89,7 +89,7 @@ ⚙ ⚫ 🎏 🌌 👆 🔜 ⚙ `FastAPI` 🎓: -```Python hl_lines="6 11 16" +```Python hl_lines="6 11 16" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -112,7 +112,7 @@ 👥 🔜 🔜 ⚙ 🙅 🔗 ✍ 🛃 `X-Token` 🎚: -```Python hl_lines="1 4-6" +```Python hl_lines="1 4-6" title="app/dependencies.py" {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` @@ -143,7 +143,7 @@ , ↩ ❎ 🌐 👈 🔠 *➡ 🛠*, 👥 💪 🚮 ⚫ `APIRouter`. -```Python hl_lines="5-10 16 21" +```Python hl_lines="5-10 16 21" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -195,7 +195,7 @@ async def read_item(item_id: str): 👥 ⚙ ⚖ 🗄 ⏮ `..` 🔗: -```Python hl_lines="3" +```Python hl_lines="3" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -265,7 +265,7 @@ that 🔜 ⛓: ✋ 👥 💪 🚮 _🌅_ `tags` 👈 🔜 ✔ 🎯 *➡ 🛠*, & ➕ `responses` 🎯 👈 *➡ 🛠*: -```Python hl_lines="30-31" +```Python hl_lines="30-31" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -290,7 +290,7 @@ that 🔜 ⛓: & 👥 💪 📣 [🌐 🔗](dependencies/global-dependencies.md){.internal-link target=_blank} 👈 🔜 🌀 ⏮ 🔗 🔠 `APIRouter`: -```Python hl_lines="1 3 7" +```Python hl_lines="1 3 7" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -298,7 +298,7 @@ that 🔜 ⛓: 🔜 👥 🗄 🎏 🔁 👈 ✔ `APIRouter`Ⓜ: -```Python hl_lines="5" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -360,7 +360,7 @@ from .routers.users import router , 💪 ⚙ 👯‍♂ 👫 🎏 📁, 👥 🗄 🔁 🔗: -```Python hl_lines="4" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -368,7 +368,7 @@ from .routers.users import router 🔜, ➡ 🔌 `router`Ⓜ ⚪➡ 🔁 `users` & `items`: -```Python hl_lines="10-11" +```Python hl_lines="10-11" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -401,7 +401,7 @@ from .routers.users import router 👉 🖌 ⚫ 🔜 💎 🙅. ✋ ➡ 💬 👈 ↩ ⚫ 💰 ⏮ 🎏 🏗 🏢, 👥 🚫🔜 🔀 ⚫ & 🚮 `prefix`, `dependencies`, `tags`, ♒. 🔗 `APIRouter`: -```Python hl_lines="3" +```Python hl_lines="3" title="app/internal/admin.py" {!../../../docs_src/bigger_applications/app/internal/admin.py!} ``` @@ -409,7 +409,7 @@ from .routers.users import router 👥 💪 📣 🌐 👈 🍵 ✔ 🔀 ⏮ `APIRouter` 🚶‍♀ 👈 🔢 `app.include_router()`: -```Python hl_lines="14-17" +```Python hl_lines="14-17" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -432,7 +432,7 @@ from .routers.users import router 📥 👥 ⚫... 🎊 👈 👥 💪 🀷: -```Python hl_lines="21-23" +```Python hl_lines="21-23" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 1cf7e50e02c50..9ec3720c8d714 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -79,7 +79,7 @@ You can create the *path operations* for that module using `APIRouter`. You import it and create an "instance" the same way you would with the class `FastAPI`: -```Python hl_lines="1 3" +```Python hl_lines="1 3" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -89,7 +89,7 @@ And then you use it to declare your *path operations*. Use it the same way you would use the `FastAPI` class: -```Python hl_lines="6 11 16" +```Python hl_lines="6 11 16" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -114,13 +114,13 @@ We will now use a simple dependency to read a custom `X-Token` header: === "Python 3.9+" - ```Python hl_lines="3 6-8" + ```Python hl_lines="3 6-8" title="app/dependencies.py" {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} ``` === "Python 3.8+" - ```Python hl_lines="1 5-7" + ```Python hl_lines="1 5-7" title="app/dependencies.py" {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} ``` @@ -129,7 +129,7 @@ We will now use a simple dependency to read a custom `X-Token` header: !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="1 4-6" + ```Python hl_lines="1 4-6" title="app/dependencies.py" {!> ../../../docs_src/bigger_applications/app/dependencies.py!} ``` @@ -160,7 +160,7 @@ We know all the *path operations* in this module have the same: So, instead of adding all that to each *path operation*, we can add it to the `APIRouter`. -```Python hl_lines="5-10 16 21" +```Python hl_lines="5-10 16 21" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -212,7 +212,7 @@ And we need to get the dependency function from the module `app.dependencies`, t So we use a relative import with `..` for the dependencies: -```Python hl_lines="3" +```Python hl_lines="3" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -282,7 +282,7 @@ We are not adding the prefix `/items` nor the `tags=["items"]` to each *path ope But we can still add _more_ `tags` that will be applied to a specific *path operation*, and also some extra `responses` specific to that *path operation*: -```Python hl_lines="30-31" +```Python hl_lines="30-31" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -307,7 +307,7 @@ You import and create a `FastAPI` class as normally. And we can even declare [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank} that will be combined with the dependencies for each `APIRouter`: -```Python hl_lines="1 3 7" +```Python hl_lines="1 3 7" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -315,7 +315,7 @@ And we can even declare [global dependencies](dependencies/global-dependencies.m Now we import the other submodules that have `APIRouter`s: -```Python hl_lines="5" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -377,7 +377,7 @@ The `router` from `users` would overwrite the one from `items` and we wouldn't b So, to be able to use both of them in the same file, we import the submodules directly: -```Python hl_lines="5" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -385,7 +385,7 @@ So, to be able to use both of them in the same file, we import the submodules di Now, let's include the `router`s from the submodules `users` and `items`: -```Python hl_lines="10-11" +```Python hl_lines="10-11" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -418,7 +418,7 @@ It contains an `APIRouter` with some admin *path operations* that your organizat For this example it will be super simple. But let's say that because it is shared with other projects in the organization, we cannot modify it and add a `prefix`, `dependencies`, `tags`, etc. directly to the `APIRouter`: -```Python hl_lines="3" +```Python hl_lines="3" title="app/internal/admin.py" {!../../../docs_src/bigger_applications/app/internal/admin.py!} ``` @@ -426,7 +426,7 @@ But we still want to set a custom `prefix` when including the `APIRouter` so tha We can declare all that without having to modify the original `APIRouter` by passing those parameters to `app.include_router()`: -```Python hl_lines="14-17" +```Python hl_lines="14-17" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -449,7 +449,7 @@ We can also add *path operations* directly to the `FastAPI` app. Here we do it... just to show that we can 🀷: -```Python hl_lines="21-23" +```Python hl_lines="21-23" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 9f0134f683c9e..1389595669313 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -79,7 +79,7 @@ 䜠可以富入它并通过䞎 `FastAPI` 类盞同的方匏创建䞀䞪「实䟋」 -```Python hl_lines="1 3" +```Python hl_lines="1 3" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -89,7 +89,7 @@ 䜿甚方匏䞎 `FastAPI` 类盞同 -```Python hl_lines="6 11 16" +```Python hl_lines="6 11 16" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -112,7 +112,7 @@ 现圚我们将䜿甚䞀䞪简单的䟝赖项来读取䞀䞪自定义的 `X-Token` 请求銖郚 -```Python hl_lines="1 4-6" +```Python hl_lines="1 4-6" title="app/dependencies.py" {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` @@ -143,7 +143,7 @@ 因歀我们可以将其添加到 `APIRouter` 䞭而䞍是将其添加到每䞪路埄操䜜䞭。 -```Python hl_lines="5-10 16 21" +```Python hl_lines="5-10 16 21" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -195,7 +195,7 @@ async def read_item(item_id: str): 因歀我们通过 `..` 对䟝赖项䜿甚了盞对富入 -```Python hl_lines="3" +```Python hl_lines="3" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -265,7 +265,7 @@ from ...dependencies import get_token_header 䜆是我们仍然可以添加*曎倚*将䌚应甚于特定的*路埄操䜜*的 `tags`以及䞀些特定于该*路埄操䜜*的额倖 `responses` -```Python hl_lines="30-31" +```Python hl_lines="30-31" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -290,7 +290,7 @@ from ...dependencies import get_token_header 我们甚至可以声明[党局䟝赖项](dependencies/global-dependencies.md){.internal-link target=_blank}它䌚和每䞪 `APIRouter` 的䟝赖项组合圚䞀起 -```Python hl_lines="1 3 7" +```Python hl_lines="1 3 7" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -298,7 +298,7 @@ from ...dependencies import get_token_header 现圚我们富入具有 `APIRouter` 的其他子暡块 -```Python hl_lines="5" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -360,7 +360,7 @@ from .routers.users import router 因歀䞺了胜借圚同䞀䞪文件䞭䜿甚它们我们盎接富入子暡块 -```Python hl_lines="4" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -368,7 +368,7 @@ from .routers.users import router 现圚让我们来包含来自 `users` 和 `items` 子暡块的 `router`。 -```Python hl_lines="10-11" +```Python hl_lines="10-11" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -401,7 +401,7 @@ from .routers.users import router 对于歀瀺䟋它将非垞简单。䜆是假讟由于它是䞎组织䞭的其他项目所共享的因歀我们无法对其进行修改以及盎接圚 `APIRouter` 䞭添加 `prefix`、`dependencies`、`tags` 等 -```Python hl_lines="3" +```Python hl_lines="3" title="app/internal/admin.py" {!../../../docs_src/bigger_applications/app/internal/admin.py!} ``` @@ -409,7 +409,7 @@ from .routers.users import router 我们可以通过将这些参数䌠递给 `app.include_router()` 来完成所有的声明而䞍必修改原始的 `APIRouter` -```Python hl_lines="14-17" +```Python hl_lines="14-17" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -432,7 +432,7 @@ from .routers.users import router 这里我们这样做了...只是䞺了衚明我们可以做到🀷 -```Python hl_lines="21-23" +```Python hl_lines="21-23" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` From fedee4d028e8c5ff634f91ca742fb404641adb40 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 15:59:47 +0000 Subject: [PATCH 127/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d75d9e3bd90f2..8d789b1373ee8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann). + ## 0.109.0 ### Features From 1369c45c2e047fe349c18fd0d4a29451de02106f Mon Sep 17 00:00:00 2001 From: Jeny Sadadia Date: Thu, 11 Jan 2024 21:37:05 +0530 Subject: [PATCH 128/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20Talk=20by=20Jeny=20Sadadia=20(#10265)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jeny Sadadia Co-authored-by: Sebastián Ramírez --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index f15560d1b6a8b..ed512b733b881 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -349,6 +349,10 @@ Podcasts: title: FastAPI on PythonBytes Talks: English: + - author: Jeny Sadadia + author_link: https://github.com/JenySadadia + link: https://www.youtube.com/watch?v=uZdTe8_Z6BQ + title: 'PyCon AU 2023: Testing asynchronous applications with FastAPI and pytest' - author: Sebastián Ramírez (tiangolo) author_link: https://twitter.com/tiangolo link: https://www.youtube.com/watch?v=PnpTY1f4k2U From facdc9162933acec437eecb0318d8d2bfdec2d6b Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 16:07:29 +0000 Subject: [PATCH 129/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8d789b1373ee8..692890d73b2ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). * 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann). ## 0.109.0 From 838e9c964eaef85f47ec8b22b4d1feb124a3a039 Mon Sep 17 00:00:00 2001 From: malicious <38064672+malicious@users.noreply.github.com> Date: Thu, 11 Jan 2024 16:31:18 +0000 Subject: [PATCH 130/217] =?UTF-8?q?=F0=9F=93=9D=20Reword=20in=20docs,=20fr?= =?UTF-8?q?om=20"have=20in=20mind"=20to=20"keep=20in=20mind"=20(#10376)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/docs/advanced/additional-responses.md | 2 +- docs/en/docs/advanced/behind-a-proxy.md | 4 ++-- docs/en/docs/advanced/custom-response.md | 2 +- docs/en/docs/advanced/dataclasses.md | 2 +- docs/en/docs/advanced/events.md | 2 +- docs/en/docs/advanced/response-change-status-code.md | 2 +- docs/en/docs/advanced/response-cookies.md | 2 +- docs/en/docs/advanced/response-headers.md | 2 +- docs/en/docs/advanced/websockets.md | 2 +- docs/en/docs/benchmarks.md | 2 +- docs/en/docs/deployment/concepts.md | 4 ++-- docs/en/docs/deployment/https.md | 2 +- docs/en/docs/deployment/index.md | 4 ++-- docs/en/docs/deployment/manually.md | 4 ++-- docs/en/docs/help-fastapi.md | 6 +++--- docs/en/docs/how-to/sql-databases-peewee.md | 4 ++-- docs/en/docs/release-notes.md | 2 +- docs/en/docs/tutorial/body-nested-models.md | 2 +- docs/en/docs/tutorial/middleware.md | 2 +- docs/en/docs/tutorial/path-params-numeric-validations.md | 4 ++-- docs/en/docs/tutorial/query-params-str-validations.md | 8 ++++---- docs/en/docs/tutorial/request-files.md | 2 +- docs/en/docs/tutorial/security/get-current-user.md | 2 +- docs/en/docs/tutorial/security/oauth2-jwt.md | 2 +- docs/en/docs/tutorial/sql-databases.md | 2 +- 25 files changed, 36 insertions(+), 36 deletions(-) diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 624036ce974c5..41b39c18e6bc1 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -28,7 +28,7 @@ For example, to declare another response with a status code `404` and a Pydantic ``` !!! note - Have in mind that you have to return the `JSONResponse` directly. + Keep in mind that you have to return the `JSONResponse` directly. !!! info The `model` key is not part of OpenAPI. diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index e7af77f3da1af..01998cc912626 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -125,7 +125,7 @@ Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--r ### About `root_path` -Have in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app. +Keep in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app. But if you go with your browser to http://127.0.0.1:8000/app you will see the normal response: @@ -142,7 +142,7 @@ Uvicorn will expect the proxy to access Uvicorn at `http://127.0.0.1:8000/app`, ## About proxies with a stripped path prefix -Have in mind that a proxy with stripped path prefix is only one of the ways to configure it. +Keep in mind that a proxy with stripped path prefix is only one of the ways to configure it. Probably in many cases the default will be that the proxy doesn't have a stripped path prefix. diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index ce2619e8de5fc..827776f5e52b6 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -101,7 +101,7 @@ But as you passed the `HTMLResponse` in the `response_class` too, **FastAPI** wi Here are some of the available responses. -Have in mind that you can use `Response` to return anything else, or even create a custom sub-class. +Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class. !!! note "Technical Details" You could also use `from starlette.responses import HTMLResponse`. diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 72daca06ad9f7..ed1d5610fc279 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -21,7 +21,7 @@ And of course, it supports the same: This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic. !!! info - Have in mind that dataclasses can't do everything Pydantic models can do. + Keep in mind that dataclasses can't do everything Pydantic models can do. So, you might still need to use Pydantic models. diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index 6b7de41309bbe..6df1411d1f317 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -159,4 +159,4 @@ Underneath, in the ASGI technical specification, this is part of the using the 'X-' prefix. +Keep in mind that custom proprietary headers can be added using the 'X-' prefix. But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations (read more in [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), using the parameter `expose_headers` documented in Starlette's CORS docs. diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 49b8fba899015..b8dfab1d1f69f 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -212,7 +212,7 @@ Client #1596980209979 left the chat !!! tip The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. - But have in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. + But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster. diff --git a/docs/en/docs/benchmarks.md b/docs/en/docs/benchmarks.md index e05fec8406621..d746b6d7c4e24 100644 --- a/docs/en/docs/benchmarks.md +++ b/docs/en/docs/benchmarks.md @@ -2,7 +2,7 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*) -But when checking benchmarks and comparisons you should have the following in mind. +But when checking benchmarks and comparisons you should keep the following in mind. ## Benchmarks and speed diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index 77419f8b0dfd9..cc01fb24e1584 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -258,7 +258,7 @@ And you will have to make sure that it's a single process running those previous Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle. !!! tip - Also, have in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. + Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. In that case, you wouldn't have to worry about any of this. 🀷 @@ -297,7 +297,7 @@ You can use simple tools like `htop` to see the CPU and RAM used in your server ## Recap -You have been reading here some of the main concepts that you would probably need to have in mind when deciding how to deploy your application: +You have been reading here some of the main concepts that you would probably need to keep in mind when deciding how to deploy your application: * Security - HTTPS * Running on startup diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md index 790976a718f78..5cf76c1111d6e 100644 --- a/docs/en/docs/deployment/https.md +++ b/docs/en/docs/deployment/https.md @@ -9,7 +9,7 @@ But it is way more complex than that. To **learn the basics of HTTPS**, from a consumer perspective, check https://howhttps.works/. -Now, from a **developer's perspective**, here are several things to have in mind while thinking about HTTPS: +Now, from a **developer's perspective**, here are several things to keep in mind while thinking about HTTPS: * For HTTPS, **the server** needs to **have "certificates"** generated by a **third party**. * Those certificates are actually **acquired** from the third party, not "generated". diff --git a/docs/en/docs/deployment/index.md b/docs/en/docs/deployment/index.md index 6c43d8abbe4db..b43bd050a37ab 100644 --- a/docs/en/docs/deployment/index.md +++ b/docs/en/docs/deployment/index.md @@ -16,6 +16,6 @@ There are several ways to do it depending on your specific use case and the tool You could **deploy a server** yourself using a combination of tools, you could use a **cloud service** that does part of the work for you, or other possible options. -I will show you some of the main concepts you should probably have in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application). +I will show you some of the main concepts you should probably keep in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application). -You will see more details to have in mind and some of the techniques to do it in the next sections. ✹ +You will see more details to keep in mind and some of the techniques to do it in the next sections. ✹ diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index d6892b2c14ad6..b10a3686d7565 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -10,11 +10,11 @@ There are 3 main alternatives: ## Server Machine and Server Program -There's a small detail about names to have in mind. 💡 +There's a small detail about names to keep in mind. 💡 The word "**server**" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn). -Just have that in mind when you read "server" in general, it could refer to one of those two things. +Just keep in mind that when you read "server" in general, it could refer to one of those two things. When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index 8199c9b9a9b1b..71c580409708c 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -106,7 +106,7 @@ In many cases they will only copy a fragment of the code, but that's not enough * You can ask them to provide a minimal, reproducible, example, that you can **copy-paste** and run locally to see the same error or behavior they are seeing, or to understand their use case better. -* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just have in mind that this might take a lot of time and it might be better to ask them to clarify the problem first. +* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just keep in mind that this might take a lot of time and it might be better to ask them to clarify the problem first. ### Suggest solutions @@ -148,7 +148,7 @@ Again, please try your best to be kind. 🀗 --- -Here's what to have in mind and how to review a pull request: +Here's what to keep in mind and how to review a pull request: ### Understand the problem @@ -233,7 +233,7 @@ Join the 👥 `contextvars` that can create a local variable very similar to `threading.local`, but also supporting these async features. -There are several things to have in mind. +There are several things to keep in mind. The `ContextVar` has to be created at the top of the module, like: diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 692890d73b2ad..6431ed2c3bebc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -3379,7 +3379,7 @@ Note: all the previous parameters are still there, so it's still possible to dec * Add OAuth2 redirect page for Swagger UI. This allows having delegated authentication in the Swagger UI docs. For this to work, you need to add `{your_origin}/docs/oauth2-redirect` to the allowed callbacks in your OAuth2 provider (in Auth0, Facebook, Google, etc). * For example, during development, it could be `http://localhost:8000/docs/oauth2-redirect`. - * Have in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`. + * Keep in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`. * This is only to allow delegated authentication in the API docs with Swagger UI. * PR [#198](https://github.com/tiangolo/fastapi/pull/198) by [@steinitzu](https://github.com/steinitzu). diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index 387f0de9aaed7..7058d4ad040c5 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -361,7 +361,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo ``` !!! tip - Have in mind that JSON only supports `str` as keys. + Keep in mind that JSON only supports `str` as keys. But Pydantic has automatic data conversion. diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 3c6868fe4de73..492a1b065e515 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -33,7 +33,7 @@ The middleware function receives: ``` !!! tip - Have in mind that custom proprietary headers can be added using the 'X-' prefix. + Keep in mind that custom proprietary headers can be added using the 'X-' prefix. But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in Starlette's CORS docs. diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index 57ad20b137ea0..b5b13cfbe6f81 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -126,7 +126,7 @@ So, you can declare your function as: {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` -But have in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. +But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. === "Python 3.9+" @@ -166,7 +166,7 @@ Python won't do anything with that `*`, but it will know that all the following ### Better with `Annotated` -Have in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. +Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. === "Python 3.9+" diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 91ae615fffb68..7a9bc487541f9 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -173,7 +173,7 @@ q: str | None = None But it declares it explicitly as being a query parameter. !!! info - Have in mind that the most important part to make a parameter optional is the part: + Keep in mind that the most important part to make a parameter optional is the part: ```Python = None @@ -199,7 +199,7 @@ This will validate the data, show a clear error when the data is not valid, and ### `Query` as the default value or in `Annotated` -Have in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`. +Keep in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`. Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent. @@ -659,7 +659,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho ``` !!! note - Have in mind that in this case, FastAPI won't check the contents of the list. + Keep in mind that in this case, FastAPI won't check the contents of the list. For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. @@ -670,7 +670,7 @@ You can add more information about the parameter. That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools. !!! note - Have in mind that different tools might have different levels of OpenAPI support. + Keep in mind that different tools might have different levels of OpenAPI support. Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development. diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index c85a68ed60631..8eb8ace64850c 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -71,7 +71,7 @@ The files will be uploaded as "form data". If you declare the type of your *path operation function* parameter as `bytes`, **FastAPI** will read the file for you and you will receive the contents as `bytes`. -Have in mind that this means that the whole contents will be stored in memory. This will work well for small files. +Keep in mind that this means that the whole contents will be stored in memory. This will work well for small files. But there are several cases in which you might benefit from using `UploadFile`. diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index e99a800c6d50c..dc6d87c9caaf8 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -227,7 +227,7 @@ Just use any kind of model, any kind of class, any kind of database that you nee ## Code size -This example might seem verbose. Have in mind that we are mixing security, data models, utility functions and *path operations* in the same file. +This example might seem verbose. Keep in mind that we are mixing security, data models, utility functions and *path operations* in the same file. But here's the key point. diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 0a347fed3eb83..4159b36591942 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -318,7 +318,7 @@ In those cases, several of those entities could have the same ID, let's say `foo So, to avoid ID collisions, when creating the JWT token for the user, you could prefix the value of the `sub` key, e.g. with `username:`. So, in this example, the value of `sub` could have been: `username:johndoe`. -The important thing to have in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string. +The important thing to keep in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string. ## Check it diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 1bc87a702d1b8..161d5491d7795 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -301,7 +301,7 @@ while Pydantic *models* declare the types using `:`, the new type annotation syn name: str ``` -Have it in mind, so you don't get confused when using `=` and `:` with them. +Keep these in mind, so you don't get confused when using `=` and `:` with them. ### Create Pydantic *models* / schemas for reading / returning From 6761fc1fa4ffce2cc0c73117aeadce81fa3a659c Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 16:31:38 +0000 Subject: [PATCH 131/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6431ed2c3bebc..9cdb82e199839 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious). * 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). * 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann). From abe7db6b2489052e73b2386d6c5372922f9a7cee Mon Sep 17 00:00:00 2001 From: Mikhail Rozhkov Date: Thu, 11 Jan 2024 18:29:24 +0100 Subject: [PATCH 132/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20ML=20serving=20and=20monitoring=20with=20FastAPI=20and=20Evi?= =?UTF-8?q?dently=20(#9701)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index ed512b733b881..aea400dfcd726 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ Articles: English: + - author: Mikhail Rozhkov, Elena Samuylova + author_link: https://www.linkedin.com/in/mnrozhkov/ + link: https://www.evidentlyai.com/blog/fastapi-tutorial + title: ML serving and monitoring with FastAPI and Evidently - author: Visual Studio Code Team author_link: https://code.visualstudio.com/ link: https://code.visualstudio.com/docs/python/tutorial-fastapi From 3325635eed6ab45e81de31766863e63ab3a7662a Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 17:29:48 +0000 Subject: [PATCH 133/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9cdb82e199839..ccb2d15933c6f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov). * 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious). * 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). * 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann). From 0380ca3e69efe642149bda481d05906f99f4da69 Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Thu, 11 Jan 2024 18:42:43 +0100 Subject: [PATCH 134/217] =?UTF-8?q?=F0=9F=93=9D=20Review=20and=20rewording?= =?UTF-8?q?=20of=20`en/docs/contributing.md`=20(#10480)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/contributing.md | 71 ++++++++++++++++++++---------------- 1 file changed, 40 insertions(+), 31 deletions(-) diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 35bc1c50197d4..2d308a9dbd801 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -4,11 +4,11 @@ First, you might want to see the basic ways to [help FastAPI and get help](help- ## Developing -If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment. +If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment. ### Virtual environment with `venv` -You can create a virtual environment in a directory using Python's `venv` module: +You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is):
@@ -18,7 +18,7 @@ $ python -m venv env
-That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment. +That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment. ### Activate the environment @@ -84,7 +84,7 @@ To check it worked, use: If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 -Make sure you have the latest pip version on your virtual environment to avoid errors on the next steps: +Make sure you have the latest pip version on your local environment to avoid errors on the next steps:
@@ -101,7 +101,7 @@ $ python -m pip install --upgrade pip This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. -### pip +### Install requirements using pip After activating the environment as described above: @@ -117,20 +117,20 @@ $ pip install -r requirements.txt It will install all the dependencies and your local FastAPI in your local environment. -#### Using your local FastAPI +### Using your local FastAPI -If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code. +If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your cloned local FastAPI source code. And if you update that local FastAPI source code when you run that Python file again, it will use the fresh version of FastAPI you just edited. That way, you don't have to "install" your local version to be able to test every change. !!! note "Technical Details" - This only happens when you install using this included `requirements.txt` instead of installing `pip install fastapi` directly. + This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. - That is because inside of the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. + That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. -### Format +### Format the code There is a script that you can run that will format and clean all your code: @@ -227,15 +227,13 @@ And those Python files are included/injected in the documentation when generatin Most of the tests actually run against the example source files in the documentation. -This helps making sure that: +This helps to make sure that: -* The documentation is up to date. +* The documentation is up-to-date. * The documentation examples can be run as is. * Most of the features are covered by the documentation, ensured by test coverage. - - -### Apps and docs at the same time +#### Apps and docs at the same time If you run the examples with, e.g.: @@ -259,7 +257,9 @@ Here are the steps to help with translations. #### Tips and guidelines -* Check the currently existing pull requests for your language and add reviews requesting changes or approving them. +* Check the currently existing pull requests for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is `lang-es`. + +* Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging. !!! tip You can add comments with change suggestions to existing pull requests. @@ -268,19 +268,9 @@ Here are the steps to help with translations. * Check if there's a GitHub Discussion to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. -* Add a single pull request per page translated. That will make it much easier for others to review it. - -For the languages I don't speak, I'll wait for several others to review the translation before merging. +* If you translate pages, add a single pull request per page translated. That will make it much easier for others to review it. -* You can also check if there are translations for your language and add a review to them, that will help me know that the translation is correct and I can merge it. - * You could check in the GitHub Discussions for your language. - * Or you can filter the existing PRs by the ones with the label for your language, for example, for Spanish, the label is `lang-es`. - -* Use the same Python examples and only translate the text in the docs. You don't have to change anything for this to work. - -* Use the same images, file names, and links. You don't have to change anything for it to work. - -* To check the 2-letter code for the language you want to translate you can use the table List of ISO 639-1 codes. +* To check the 2-letter code for the language you want to translate, you can use the table List of ISO 639-1 codes. #### Existing language @@ -323,7 +313,7 @@ $ python ./scripts/docs.py live es Now you can go to http://127.0.0.1:8008 and see your changes live. -You will see that every language has all the pages. But some pages are not translated and have a notification about the missing translation. +You will see that every language has all the pages. But some pages are not translated and have an info box at the top, about the missing translation. Now let's say that you want to add a translation for the section [Features](features.md){.internal-link target=_blank}. @@ -342,7 +332,7 @@ docs/es/docs/features.md !!! tip Notice that the only change in the path and file name is the language code, from `en` to `es`. -If you go to your browser you will see that now the docs show your new section. 🎉 +If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉 Now you can translate it all and see how it looks as you save the file. @@ -386,7 +376,7 @@ You can make the first pull request with those two files, `docs/ht/mkdocs.yml` a #### Preview the result -You can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`). +As already mentioned above, you can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`). Once you are done, you can also test it all as it would look online, including all the other languages. @@ -423,6 +413,25 @@ Serving at: http://127.0.0.1:8008
+#### Translation specific tips and guidelines + +* Translate only the Markdown documents (`.md`). Do not translate the code examples at `./docs_src`. + +* In code blocks within the Markdown document, translate comments (`# a comment`), but leave the rest unchanged. + +* Do not change anything enclosed in "``" (inline code). + +* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged. + +* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box. + +* Do not change the paths in links to images, code files, Markdown documents. + +* However, when a Markdown document is translated, the `#hash-parts` in links to its headings may change. Update these links if possible. + * Search for such links in the translated document using the regex `#[^# ]`. + * Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files". + * When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents. + ## Tests There is a script that you can run locally to test all the code and generate coverage reports in HTML: From 0be64abac748116f12d68ca766915ec46ff879df Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 17:43:08 +0000 Subject: [PATCH 135/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ccb2d15933c6f..65a81f7d31e2f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov). * 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious). * 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). From e6759aa6044929d1aaaea8280dd2e576a2339dc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B3=20Lino?= Date: Thu, 11 Jan 2024 20:52:15 +0100 Subject: [PATCH 136/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20Instrument=20a=20FastAPI=20service=20adding=20tracing=20with?= =?UTF-8?q?=20OpenTelemetry=20and=20send/show=20traces=20in=20Grafana=20Te?= =?UTF-8?q?mpo=20(#9440)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Carol Willing Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index aea400dfcd726..4121564426ce7 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ Articles: English: + - author: Nicoló Lino + author_link: https://www.nlino.com + link: https://github.com/softwarebloat/python-tracing-demo + title: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo - author: Mikhail Rozhkov, Elena Samuylova author_link: https://www.linkedin.com/in/mnrozhkov/ link: https://www.evidentlyai.com/blog/fastapi-tutorial From 4dde172a969644e4e4f88b5d6c29b1d4d2e95303 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 19:52:37 +0000 Subject: [PATCH 137/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 65a81f7d31e2f..23dbeb5b3ca9a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat). * 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov). * 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious). From f74aeb00674d35d10e4f9f0ecd34a8e36a0df131 Mon Sep 17 00:00:00 2001 From: Hungtsetse <33526088+hungtsetse@users.noreply.github.com> Date: Fri, 12 Jan 2024 03:56:09 +0800 Subject: [PATCH 138/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20hyperlink=20to=20`?= =?UTF-8?q?docs/en/docs/tutorial/static-files.md`=20(#10243)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/static-files.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md index 7a0c36af3f4c5..311d2b1c8de14 100644 --- a/docs/en/docs/tutorial/static-files.md +++ b/docs/en/docs/tutorial/static-files.md @@ -22,7 +22,7 @@ You can serve static files automatically from a directory using `StaticFiles`. This is different from using an `APIRouter` as a mounted application is completely independent. The OpenAPI and docs from your main application won't include anything from the mounted application, etc. -You can read more about this in the **Advanced User Guide**. +You can read more about this in the [Advanced User Guide](../advanced/index.md){.internal-link target=_blank}. ## Details From 99769b966975b85321a8213b48a57828fac9453c Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 19:57:48 +0000 Subject: [PATCH 139/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 23dbeb5b3ca9a..66b7f260e6c87 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse). * 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat). * 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann). * 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov). From b62e379a55488d523c42718616f0ad7eea526850 Mon Sep 17 00:00:00 2001 From: Ankit Anchlia Date: Thu, 11 Jan 2024 13:59:29 -0600 Subject: [PATCH 140/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20Explore=20How=20to=20Effectively=20Use=20JWT=20With=20FastAP?= =?UTF-8?q?I=20(#10212)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ankit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 4121564426ce7..b4b8687c4d7f3 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ Articles: English: + - author: Ankit Anchlia + author_link: https://linkedin.com/in/aanchlia21 + link: https://hackernoon.com/explore-how-to-effectively-use-jwt-with-fastapi + title: Explore How to Effectively Use JWT With FastAPI - author: Nicoló Lino author_link: https://www.nlino.com link: https://github.com/softwarebloat/python-tracing-demo From cbcd3fe863a4ee537facb65acf0e8ef9e2b6da23 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 20:01:57 +0000 Subject: [PATCH 141/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 66b7f260e6c87..b4b137a301bd6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia). * 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse). * 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat). * 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann). From d192ddacec3ffc2d0ff5ec43bc7f816358ab769c Mon Sep 17 00:00:00 2001 From: Pedro Augusto de Paula Barbosa Date: Thu, 11 Jan 2024 17:18:07 -0300 Subject: [PATCH 142/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Update=20highlight?= =?UTF-8?q?ed=20line=20in=20`docs/en/docs/tutorial/bigger-applications.md`?= =?UTF-8?q?=20(#5490)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/docs/tutorial/bigger-applications.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 9ec3720c8d714..b2d92840523a3 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -315,7 +315,7 @@ And we can even declare [global dependencies](dependencies/global-dependencies.m Now we import the other submodules that have `APIRouter`s: -```Python hl_lines="5" title="app/main.py" +```Python hl_lines="4-5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` From 53a3dd740826362dd874c92d5c08fb5f607e2bc0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 20:18:31 +0000 Subject: [PATCH 143/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b4b137a301bd6..80a581865240d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb). * 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia). * 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse). * 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat). From fd97e8efe43baced1c040cac3627904b37f2380b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Szaci=C5=82owski?= <44623605+piotrszacilowski@users.noreply.github.com> Date: Thu, 11 Jan 2024 22:21:35 +0100 Subject: [PATCH 144/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20usage=20of=20To?= =?UTF-8?q?ken=20model=20in=20security=20docs=20(#9313)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra Sánchez Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../em/docs/advanced/security/oauth2-scopes.md | 6 +++--- docs/em/docs/tutorial/security/oauth2-jwt.md | 4 ++-- .../en/docs/advanced/security/oauth2-scopes.md | 18 +++++++++--------- docs/en/docs/tutorial/security/oauth2-jwt.md | 4 ++-- docs/ja/docs/tutorial/security/oauth2-jwt.md | 2 +- docs/zh/docs/tutorial/security/oauth2-jwt.md | 2 +- docs_src/security/tutorial004.py | 8 +++++--- docs_src/security/tutorial004_an.py | 6 +++--- docs_src/security/tutorial004_an_py310.py | 6 +++--- docs_src/security/tutorial004_an_py39.py | 6 +++--- docs_src/security/tutorial004_py310.py | 8 +++++--- docs_src/security/tutorial005.py | 8 +++++--- docs_src/security/tutorial005_an.py | 6 +++--- docs_src/security/tutorial005_an_py310.py | 6 +++--- docs_src/security/tutorial005_an_py39.py | 6 +++--- docs_src/security/tutorial005_py310.py | 8 +++++--- docs_src/security/tutorial005_py39.py | 8 +++++--- 17 files changed, 61 insertions(+), 51 deletions(-) diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index a4684352ccd4d..d82fe152bef31 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -56,7 +56,7 @@ Oauth2⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 🥇, ➡ 🔜 👀 🍕 👈 🔀 ⚪➡ 🖌 👑 **🔰 - 👩‍💻 🊮** [Oauth2⃣ ⏮ 🔐 (& 🔁), 📚 ⏮ 🥙 🀝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙ Oauth2⃣ ↔: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!../../../docs_src/security/tutorial005.py!} ``` @@ -93,7 +93,7 @@ Oauth2⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. ✋ 👆 🈞, 💂‍♂, 👆 🔜 ⚒ 💭 👆 🕎 🚮 ↔ 👈 👩‍💻 🀙 💪 ✔, ⚖ 🕐 👆 ✔ 🔁. -```Python hl_lines="153" +```Python hl_lines="155" {!../../../docs_src/security/tutorial005.py!} ``` @@ -118,7 +118,7 @@ Oauth2⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👥 🔚 ⚫ 📥 🎊 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚. -```Python hl_lines="4 139 166" +```Python hl_lines="4 139 168" {!../../../docs_src/security/tutorial005.py!} ``` diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index bc207c5666d90..bc3c943f86dc6 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -192,13 +192,13 @@ $ openssl rand -hex 32 === "🐍 3⃣.6⃣ & 🔛" - ```Python hl_lines="115-128" + ```Python hl_lines="115-130" {!> ../../../docs_src/security/tutorial004.py!} ``` === "🐍 3⃣.1⃣0⃣ & 🔛" - ```Python hl_lines="114-127" + ```Python hl_lines="114-129" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 304a46090e1d7..b93d2991c4dcb 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -79,7 +79,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 152" + ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -88,7 +88,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -97,7 +97,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -199,7 +199,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="152" + ```Python hl_lines="154" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -208,7 +208,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="153" + ```Python hl_lines="155" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -217,7 +217,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="153" + ```Python hl_lines="155" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -265,7 +265,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 138 165" + ```Python hl_lines="3 138 167" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -274,7 +274,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 139 166" + ```Python hl_lines="4 139 168" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -283,7 +283,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 139 166" + ```Python hl_lines="4 139 168" {!> ../../../docs_src/security/tutorial005.py!} ``` diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 4159b36591942..1c792e3d9e599 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -285,7 +285,7 @@ Create a real JWT access token and return it !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="114-127" + ```Python hl_lines="114-129" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -294,7 +294,7 @@ Create a real JWT access token and return it !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="115-128" + ```Python hl_lines="115-130" {!> ../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index 348ffda0163e9..d5b179aa05abf 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -167,7 +167,7 @@ JWTトヌクンの眲名に䜿甚するアルゎリズム`"HS256"`を指定し JWTアクセストヌクンを䜜成し、それを返したす。 -```Python hl_lines="115-128" +```Python hl_lines="115-130" {!../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 054198545ef8e..33a4d7fc76171 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -170,7 +170,7 @@ $ openssl rand -hex 32 创建并返回真正的 JWT 访问什牌。 -```Python hl_lines="115-128" +```Python hl_lines="115-130" {!../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index 134c15c5a0369..044eec70037da 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -112,8 +112,10 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -125,7 +127,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index 204151a566485..c78e8496c6427 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -115,10 +115,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -130,7 +130,7 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 64dfa15c62718..36dbc677e0638 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -114,10 +114,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -129,7 +129,7 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index 631a8366eb81b..23fc04a721433 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -114,10 +114,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -129,7 +129,7 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 470f22e29f03b..8363d45ab5349 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -111,8 +111,10 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -124,7 +126,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py index ece461bc8ac36..b16bf440a51c1 100644 --- a/docs_src/security/tutorial005.py +++ b/docs_src/security/tutorial005.py @@ -143,8 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -153,7 +155,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index c5b5609e525e0..95e406b32f748 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -144,10 +144,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -156,7 +156,7 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 5e81a50e12d63..c6116a5ed120f 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -143,10 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -155,7 +155,7 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index ae9811c689f5b..af51c08b5081d 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -143,10 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -155,7 +155,7 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index 0fcdda4c004c6..37a22c70907f6 100644 --- a/docs_src/security/tutorial005_py310.py +++ b/docs_src/security/tutorial005_py310.py @@ -142,8 +142,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -152,7 +154,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py index d756c0b6b87f9..c275807636c4b 100644 --- a/docs_src/security/tutorial005_py39.py +++ b/docs_src/security/tutorial005_py39.py @@ -143,8 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -153,7 +155,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) From 22e68b151d92aff6d6e0cdf001b08a792e20020d Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 21:21:57 +0000 Subject: [PATCH 145/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 80a581865240d..945d342d95279 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski). * ✏ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb). * 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia). * 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse). From 0c796747a3d652f7d5d7fc59c5fbb68512b64ccf Mon Sep 17 00:00:00 2001 From: Ezzeddin Abdullah Date: Fri, 12 Jan 2024 00:25:37 +0200 Subject: [PATCH 146/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20template=20docs?= =?UTF-8?q?=20with=20more=20info=20about=20`url=5Ffor`=20(#5937)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/advanced/templates.md | 48 +++++++++++++++++-- docs_src/templates/templates/item.html | 2 +- .../test_templates/test_tutorial001.py | 5 +- 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 583abda7fb0e4..6055b30170db6 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -46,21 +46,61 @@ $ pip install jinja2 ## Writing templates -Then you can write a template at `templates/item.html` with: +Then you can write a template at `templates/item.html` with, for example: ```jinja hl_lines="7" {!../../../docs_src/templates/templates/item.html!} ``` -It will show the `id` taken from the "context" `dict` you passed: +### Template Context Values + +In the HTML that contains: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...it will show the `id` taken from the "context" `dict` you passed: ```Python -{"request": request, "id": id} +{"id": id} +``` + +For example, with an ID of `42`, this would render: + +```html +Item ID: 42 +``` + +### Template `url_for` Arguments + +You can also use `url_for()` inside of the template, it takes as arguments the same arguments that would be used by your *path operation function*. + +So, the section with: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...will generate a link to the same URL that would be handled by the *path operation function* `read_item(id=id)`. + +For example, with an ID of `42`, this would render: + +```html + ``` ## Templates and static files -You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted. +You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`. ```jinja hl_lines="4" {!../../../docs_src/templates/templates/item.html!} diff --git a/docs_src/templates/templates/item.html b/docs_src/templates/templates/item.html index a70287e77d345..27994ca994b00 100644 --- a/docs_src/templates/templates/item.html +++ b/docs_src/templates/templates/item.html @@ -4,6 +4,6 @@ -

Item ID: {{ id }}

+

Item ID: {{ id }}

diff --git a/tests/test_tutorial/test_templates/test_tutorial001.py b/tests/test_tutorial/test_templates/test_tutorial001.py index bfee5c0902dbc..4d4729425e845 100644 --- a/tests/test_tutorial/test_templates/test_tutorial001.py +++ b/tests/test_tutorial/test_templates/test_tutorial001.py @@ -16,7 +16,10 @@ def test_main(): client = TestClient(app) response = client.get("/items/foo") assert response.status_code == 200, response.text - assert b"

Item ID: foo

" in response.content + assert ( + b'

Item ID: foo

' + in response.content + ) response = client.get("/static/styles.css") assert response.status_code == 200, response.text assert b"color: green;" in response.content From 5f37d3870bd101bdda65e6dbda06ca969f6ef510 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 11 Jan 2024 22:25:58 +0000 Subject: [PATCH 147/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 945d342d95279..af3d2e2b29510 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin). * 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski). * ✏ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb). * 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia). From ea84587a2f0431a7fad42395fd1dadee3dae3fed Mon Sep 17 00:00:00 2001 From: Turabek Gaybullaev <43612265+Torabek@users.noreply.github.com> Date: Fri, 12 Jan 2024 20:10:55 +0900 Subject: [PATCH 148/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Remove=20broken=20?= =?UTF-8?q?links=20from=20`external=5Flinks.yml`=20(#10943)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index b4b8687c4d7f3..00d6f696dea73 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -40,10 +40,6 @@ Articles: author_link: https://dev.to/ link: https://dev.to/teresafds/authorization-on-fastapi-with-casbin-41og title: Authorization on FastAPI with Casbin - - author: WayScript - author_link: https://www.wayscript.com - link: https://blog.wayscript.com/fast-api-quickstart/ - title: Quickstart Guide to Build and Host Responsive APIs with Fast API and WayScript - author: New Relic author_link: https://newrelic.com link: https://newrelic.com/instant-observability/fastapi/e559ec64-f765-4470-a15f-1901fcebb468 @@ -96,10 +92,6 @@ Articles: author_link: https://dev.to/factorlive link: https://dev.to/factorlive/python-facebook-messenger-webhook-with-fastapi-on-glitch-4n90 title: Python Facebook messenger webhook with FastAPI on Glitch - - author: Dom Patmore - author_link: https://twitter.com/dompatmore - link: https://dompatmore.com/blog/authenticate-your-fastapi-app-with-auth0 - title: Authenticate Your FastAPI App with auth0 - author: Valon Januzaj author_link: https://www.linkedin.com/in/valon-januzaj-b02692187/ link: https://valonjanuzaj.medium.com/deploy-a-dockerized-fastapi-application-to-aws-cc757830ba1b @@ -112,10 +104,6 @@ Articles: author_link: https://twitter.com/louis_guitton link: https://guitton.co/posts/fastapi-monitoring/ title: How to monitor your FastAPI service - - author: Julien Harbulot - author_link: https://julienharbulot.com/ - link: https://julienharbulot.com/notification-server.html - title: HTTP server to display desktop notifications - author: Precious Ndubueze author_link: https://medium.com/@gabbyprecious2000 link: https://medium.com/@gabbyprecious2000/creating-a-crud-app-with-fastapi-part-one-7c049292ad37 @@ -164,18 +152,10 @@ Articles: author_link: https://wuilly.com/ link: https://wuilly.com/2019/10/real-time-notifications-with-python-and-postgres/ title: Real-time Notifications with Python and Postgres - - author: Benjamin Ramser - author_link: https://iwpnd.pw - link: https://iwpnd.pw/articles/2020-03/apache-kafka-fastapi-geostream - title: Apache Kafka producer and consumer with FastAPI and aiokafka - author: Navule Pavan Kumar Rao author_link: https://www.linkedin.com/in/navule/ link: https://www.tutlinks.com/create-and-deploy-fastapi-app-to-heroku/ title: Create and Deploy FastAPI app to Heroku without using Docker - - author: Benjamin Ramser - author_link: https://iwpnd.pw - link: https://iwpnd.pw/articles/2020-01/deploy-fastapi-to-aws-lambda - title: How to continuously deploy a FastAPI to AWS Lambda with AWS SAM - author: Arthur Henrique author_link: https://twitter.com/arthurheinrique link: https://medium.com/@arthur393/another-boilerplate-to-fastapi-azure-pipeline-ci-pytest-3c8d9a4be0bb @@ -200,10 +180,6 @@ Articles: author_link: https://dev.to/dbanty link: https://dev.to/dbanty/why-i-m-leaving-flask-3ki6 title: Why I'm Leaving Flask - - author: Rob Wagner - author_link: https://robwagner.dev/ - link: https://robwagner.dev/tortoise-fastapi-setup/ - title: Setting up Tortoise ORM with FastAPI - author: Mike Moritz author_link: https://medium.com/@mike.p.moritz link: https://medium.com/@mike.p.moritz/using-docker-compose-to-deploy-a-lightweight-python-rest-api-with-a-job-queue-37e6072a209b From e0eaaee7496e3f95cd0e1c47c5473c989f390ed6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 11:11:15 +0000 Subject: [PATCH 149/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index af3d2e2b29510..671e632161018 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Remove broken links from `external_links.yml`. PR [#10943](https://github.com/tiangolo/fastapi/pull/10943) by [@Torabek](https://github.com/Torabek). * 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin). * 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski). * ✏ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb). From 3ca38568c1a31628c3f5863fb67a99b6b44cec9d Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov Date: Fri, 12 Jan 2024 14:12:19 +0300 Subject: [PATCH 150/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/dependencies/classes-as-depe?= =?UTF-8?q?ndencies.md`=20(#10410)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Vladislav Kramorenko <85196001+Xewus@users.noreply.github.com> --- .../dependencies/classes-as-dependencies.md | 478 ++++++++++++++++++ 1 file changed, 478 insertions(+) create mode 100644 docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 0000000000000..b6ad25dafcc95 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,478 @@ +# Классы как завОсОЌПстО + +ПрежЎе чеЌ углубОться в сОстеЌу **ВМеЎреМОя ЗавОсОЌПстей**, Ўавайте ПбМПвОЌ преЎыЎущОй прОЌер. + +## `СлПварь` Оз преЎыЎущегП прОЌера + +В преЎыЎущеЌ прОЌере Ќы вПзвращалО `слПварь` Оз Машей завОсОЌПстО: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +НП затеЌ Ќы пПлучаеЌ `слПварь` в параЌетре `commons` *фуМкцОО ПперацОО путО*. И Ќы зМаеЌ, чтП реЎактПры Ме ЌПгут ПбеспечОть ЎПстатПчМую пПЎЎержку Ўля `слПваря`, пПскПльку ПМО Ме ЌПгут зМать Ох ключО О тОпы зМачеМОй. + +Мы ЌПжеЌ сЎелать лучше... + +## ЧтП Ўелает завОсОЌПсть + +ДП сОх пПр вы вОЎелО завОсОЌПстО, ПбъявлеММые как фуМкцОО. + +НП этП Ме еЎОМствеММый спПсПб ПбъявлеМОя завОсОЌПстей (хПтя, верПятМП, бПлее распрПстраМеММый). + +КлючевыЌ фактПрПЌ является тП, чтП завОсОЌПсть ЎПлжМа быть "вызываеЌПй". + +В Python "**вызываеЌый**" - этП все, чтП Python ЌПжет "вызвать", как фуМкцОю. + +Так, еслО у вас есть Пбъект `something` (кПтПрый ЌПжет _Ме_ быть фуМкцОей) О вы ЌПжете "вызвать" егП (выпПлМОть) как: + +```Python +something() +``` + +ОлО + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +в такПЌ случае ПМ является "вызываеЌыЌ". + +## Классы как завОсОЌПстО + +Вы ЌПжете заЌетОть, чтП Ўля сПзЎаМОя экзеЌпляра класса в Python ОспПльзуется тПт же сОМтаксОс. + +НапрОЌер: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +В ЎаММПЌ случае `fluffy` является экзеЌплярПЌ класса `Cat`. + +А чтПбы сПзЎать `fluffy`, вы "вызываете" `Cat`. + +ТакОЌ ПбразПЌ, класс в Python также является **вызываеЌыЌ**. + +ТПгЎа в **FastAPI** в качестве завОсОЌПстО ЌПжМП ОспПльзПвать класс Python. + +На саЌПЌ Ўеле FastAPI прПверяет, чтП переЎаММый Пбъект является "вызываеЌыЌ" (фуМкцОя, класс ОлО чтП-лОбП еще) О указаМы МеПбхПЎОЌые Ўля егП вызПва параЌетры. + +ЕслО вы переЎаёте чтП-тП, чтП ЌПжМП "вызывать" в качестве завОсОЌПстО в **FastAPI**, тП ПМ буЎет аМалОзОрПвать параЌетры, МеПбхПЎОЌые Ўля "вызПва" этПгП Пбъекта О Пбрабатывать Ох так же, как параЌетры *фуМкцОО ПперацОО путО*. Включая пПЎзавОсОЌПстО. + +ЭтП ПтМПсОтся О к вызываеЌыЌ ПбъектаЌ без параЌетрПв. РабПта с МОЌО прПОсхПЎОт тПчМП так же, как О Ўля *фуМкцОй ПперацОО путО* без параЌетрПв. + +Теперь Ќы ЌПжеЌ ОзЌеМОть завОсОЌПсть `common_parameters`, указаММую выше, Ма класс `CommonQueryParams`: + +=== "Python 3.10+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12-16" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="9-13" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +ОбратОте вМОЌаМОе Ма ЌетПЎ `__init__`, ОспПльзуеЌый Ўля сПзЎаМОя экзеЌпляра класса: + +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +...ОЌеет те же параЌетры, чтП О раМее ОспПльзуеЌая фуМкцОя `common_parameters`: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="6" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +ЭтО параЌетры О буЎут ОспПльзПваться **FastAPI** Ўля "решеМОя" завОсОЌПстО. + +В ПбПОх случаях ПМа буЎет ОЌеть: + +* НеПбязательМый параЌетр запрПса `q`, преЎставляющОй сПбПй `str`. +* ПараЌетр запрПса `skip`, преЎставляющОй сПбПй `int`, пП уЌПлчаМОю `0`. +* ПараЌетр запрПса `limit`, преЎставляющОй сПбПй `int`, пП уЌПлчаМОю равМый `100`. + +В ПбПОх случаях ЎаММые буЎут кПМвертОрПваМы, валОЎОрПваМы, ЎПкуЌеМтОрПваМы пП схеЌе OpenAPI О т.ÐŽ. + +## Как этП ОспПльзПвать + +Теперь вы ЌПжете ПбъявОть свПю завОсОЌПсть, ОспПльзуя этПт класс. + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +**FastAPI** вызывает класс `CommonQueryParams`. ПрО этПЌ сПзЎается "экзеЌпляр" этПгП класса, кПтПрый буЎет переЎаМ в качестве параЌетра `commons` в вашу фуМкцОю. + +## АММПтацОя тОпа ОлО `Depends` + +ОбратОте вМОЌаМОе, чтП в прОвеЎеММПЌ выше кПЎе Ќы Ўва раза пОшеЌ `CommonQueryParams`: + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +ППслеЎМОй параЌетр `CommonQueryParams`, в: + +```Python +... Depends(CommonQueryParams) +``` + +...этП тП, чтП **FastAPI** буЎет ОспПльзПвать, чтПбы узМать, чтП является завОсОЌПстью. + +Из МегП FastAPI Озвлечёт ПбъявлеММые параЌетры О ОЌеММП Ох буЎет вызывать. + +--- + +В этПЌ случае первый `CommonQueryParams`, в: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, ... + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons: CommonQueryParams ... + ``` + +...Ме ОЌеет МОкакПгП спецОальМПгП зМачеМОя Ўля **FastAPI**. FastAPI Ме буЎет ОспПльзПвать егП Ўля преПбразПваМОя ЎаММых, валОЎацОО О т.ÐŽ. (пПскПльку Ўля этПгП ОспПльзуется `Depends(CommonQueryParams)`). + +На саЌПЌ Ўеле ЌПжМП МапОсать прПстП: + +=== "Python 3.6+" + + ```Python + commons: Annotated[Any, Depends(CommonQueryParams)] + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons = Depends(CommonQueryParams) + ``` + +...как тут: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial003_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial003_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003.py!} + ``` + +НП ПбъявлеМОе тОпа прОветствуется, так как в этПЌ случае ваш реЎактПр буЎет зМать, чтП буЎет переЎаМП в качестве параЌетра `commons`, О тПгЎа ПМ сЌПжет пПЌПчь ваЌ с автПЎПпПлМеМОеЌ, прПверкПй тОпПв О т.ÐŽ: + + + +## СПкращеМОе + +НП вы вОЎОте, чтП зЎесь Ќы ОЌееЌ МекПтПрПе пПвтПреМОе кПЎа, ЎважЎы МапОсав `CommonQueryParams`: + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +Для случаев, кПгЎа завОсОЌПстью является *кПМкретМый* класс, кПтПрый **FastAPI** "вызПвет" Ўля сПзЎаМОя экзеЌпляра этПгП класса, ЌПжМП ОспПльзПвать укПрПчеММую запОсь. + + +ВЌестП тПгП чтПбы пОсать: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +...слеЎует МапОсать: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends()] + ``` + +=== "Python 3.6 без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python + commons: CommonQueryParams = Depends() + ``` + +Вы Пбъявляете завОсОЌПсть как тОп параЌетра О ОспПльзуете `Depends()` без какПгП-лОбП параЌетра, вЌестП тПгП чтПбы *сМПва* пОсать пПлМый класс вМутрО `Depends(CommonQueryParams)`. + +АМалПгОчМый прОЌер буЎет выгляЎеть слеЎующОЌ ПбразПЌ: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial004_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial004_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "ППЎсказка" + РекПЌеМЎуется ОспПльзПвать версОю с `Annotated` еслО вПзЌПжМП. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004.py!} + ``` + +...О **FastAPI** буЎет зМать, чтП Ўелать. + +!!! tip "ППЎсказка" + ЕслО этП пПкажется ваЌ бПлее запутаММыЌ, чеЌ пПлезМыЌ, Ме Пбращайте вМОЌаМОя, этП ваЌ Ме *МужМП*. + + ЭтП прПстП сПкращеМОе. ППтПЌу чтП **FastAPI** забПтОтся П тПЌ, чтПбы пПЌПчь ваЌ свестО к ЌОМОЌуЌу пПвтПреМОе кПЎа. From 4c231854dc2dc7336f8ad3ed399b806f6dc7d498 Mon Sep 17 00:00:00 2001 From: HiemalBeryl <63165207+HiemalBeryl@users.noreply.github.com> Date: Fri, 12 Jan 2024 19:13:04 +0800 Subject: [PATCH 151/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typos=20in?= =?UTF-8?q?=20`docs/zh/docs/tutorial/extra-data-types.md`=20(#10727)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/extra-data-types.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index a74efa61be48c..f4a77050ca6e0 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -44,11 +44,11 @@ * 产生的暡匏将指定那些 `set` 的倌是唯䞀的 (䜿甚 JSON 暡匏的 `uniqueItems`)。 * `bytes`: * 标准的 Python `bytes`。 - * 圚请求和盞应䞭被圓䜜 `str` 倄理。 + * 圚请求和响应䞭被圓䜜 `str` 倄理。 * 生成的暡匏将指定这䞪 `str` 是 `binary` "栌匏"。 * `Decimal`: * 标准的 Python `Decimal`。 - * 圚请求和盞应䞭被圓做 `float` 䞀样倄理。 + * 圚请求和响应䞭被圓做 `float` 䞀样倄理。 * 悚可以圚这里检查所有有效的pydantic数据类型: Pydantic data types. ## 䟋子 From 6a4aed45f05c7e0c9db635e74b29e76ecae6ca5c Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 11:13:22 +0000 Subject: [PATCH 152/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 671e632161018..457bc5e983ea8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,10 @@ hide: * 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). * 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann). +### Translations + +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). + ## 0.109.0 ### Features From 753c8136d8b5ecffe27f7b2ac18e02687f2c269b Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 11:15:04 +0000 Subject: [PATCH 153/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 457bc5e983ea8..628e18b108e69 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -24,6 +24,7 @@ hide: ### Translations +* ✏ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). ## 0.109.0 From f1329abf9930165f4c53cb760fd9f809b4ed6266 Mon Sep 17 00:00:00 2001 From: theoohoho <31537466+theoohoho@users.noreply.github.com> Date: Fri, 12 Jan 2024 21:39:54 +0800 Subject: [PATCH 154/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20broken=20lin?= =?UTF-8?q?k=20in=20`docs/tutorial/sql-databases.md`=20in=20several=20lang?= =?UTF-8?q?uages=20(#10716)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/em/docs/tutorial/sql-databases.md | 2 +- docs/en/docs/tutorial/sql-databases.md | 2 +- docs/zh/docs/tutorial/sql-databases.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index 9d46c2460843a..e3ced7ef4c890 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -501,7 +501,7 @@ current_user.items "🛠" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇞🇲 🏷, 🚮 🆕 🔢, ♒. 🔁 👈 🔀 💜, 🚮 🆕 🏓, 🆕 🏓, ♒. -👆 💪 🔎 🖌 ⚗ FastAPI 🏗 📄 ⚪➡ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. +👆 💪 🔎 🖌 ⚗ FastAPI 🏗 📄 ⚪➡ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. ### ✍ 🔗 diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 161d5491d7795..70d9482df2257 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -513,7 +513,7 @@ And you would also use Alembic for "migrations" (that's its main job). A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc. -You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. +You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. ### Create a dependency diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index a936eb27b4d6a..c49374971eaa0 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -499,7 +499,7 @@ current_user.items “迁移”是每圓悚曎改 SQLAlchemy 暡型的结构、添加新属性等以圚数据库䞭倍制这些曎改、添加新列、新衚等时所需的䞀组步骀。 -悚可以圚[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的暡板䞭扟到䞀䞪 FastAPI 项目䞭的 Alembic 瀺䟋。具䜓圚[`alembic`代码目圕䞭](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/alembic/)。 +悚可以圚[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的暡板䞭扟到䞀䞪 FastAPI 项目䞭的 Alembic 瀺䟋。具䜓圚[`alembic`代码目圕䞭](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/)。 ### 创建䟝赖项 From dc704036a2dd646c30fb9d58ec8a707236135f84 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 13:40:15 +0000 Subject: [PATCH 155/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 628e18b108e69..55b6a68948e54 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏ Fix broken link in `docs/tutorial/sql-databases.md` in several languages. PR [#10716](https://github.com/tiangolo/fastapi/pull/10716) by [@theoohoho](https://github.com/theoohoho). * ✏ Remove broken links from `external_links.yml`. PR [#10943](https://github.com/tiangolo/fastapi/pull/10943) by [@Torabek](https://github.com/Torabek). * 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin). * 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski). From 7e0e16fa3669d83a9992ff5aee669135ebb41fc1 Mon Sep 17 00:00:00 2001 From: Jacob McDonald <48448372+jacob-indigo@users.noreply.github.com> Date: Fri, 12 Jan 2024 09:03:25 -0500 Subject: [PATCH 156/217] =?UTF-8?q?=F0=9F=93=9D=20Add=20warning=20about=20?= =?UTF-8?q?lifespan=20functions=20and=20backwards=20compatibility=20with?= =?UTF-8?q?=20events=20(#10734)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/docs/advanced/events.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index 6df1411d1f317..ca9d86ae41e99 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -92,7 +92,7 @@ The `lifespan` parameter of the `FastAPI` app takes an **async context manager** ## Alternative Events (deprecated) !!! warning - The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. + The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. You can probably skip this part. From 38915783fc355a4eb49310182f353778982c70e1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 14:03:51 +0000 Subject: [PATCH 157/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 55b6a68948e54..01eefb052a8db 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo). * ✏ Fix broken link in `docs/tutorial/sql-databases.md` in several languages. PR [#10716](https://github.com/tiangolo/fastapi/pull/10716) by [@theoohoho](https://github.com/theoohoho). * ✏ Remove broken links from `external_links.yml`. PR [#10943](https://github.com/tiangolo/fastapi/pull/10943) by [@Torabek](https://github.com/Torabek). * 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin). From 58e2f8b1d9265a90aa0aecd7e7eb1ca8c19bf1de Mon Sep 17 00:00:00 2001 From: Delitel-WEB <57365921+Delitel-WEB@users.noreply.github.com> Date: Fri, 12 Jan 2024 17:10:31 +0300 Subject: [PATCH 158/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`docs/ru/docs/index.md`=20(#10672)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 97a3947bd3f25..6c99f623ddc9d 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -321,7 +321,7 @@ def update_item(item_id: int, item: Item): ТакОЌ ПбразПЌ, вы Пбъявляете **ПЎОМ раз** тОпы параЌетрПв, телП О т. ÐŽ. в качестве параЌетрПв фуМкцОО. -Вы Ўелаете этП Оспльзуя стаМЎартМую сПвреЌеММую тОпОзацОю Python. +Вы Ўелаете этП ОспПльзуя стаМЎартМую сПвреЌеММую тОпОзацОю Python. ВаЌ Ме МужМП Озучать МПвый сОМтаксОс, ЌетПЎы ОлО классы кПМкретМПй бОблОПтекО О т. ÐŽ. From ca33b6edac847e27a9543c0a8dad95c1fcfc65fc Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 14:10:54 +0000 Subject: [PATCH 159/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 01eefb052a8db..4e795b8cc33a6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Translations +* ✏ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB). * ✏ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). From c81ab17a594e140e66424addfe8374d72550728a Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Fri, 12 Jan 2024 15:15:29 +0100 Subject: [PATCH 160/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/background-tasks.md`=20(#1056?= =?UTF-8?q?6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/background-tasks.md | 126 ++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 docs/de/docs/tutorial/background-tasks.md diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md new file mode 100644 index 0000000000000..a7bfd55a7dae8 --- /dev/null +++ b/docs/de/docs/tutorial/background-tasks.md @@ -0,0 +1,126 @@ +# Hintergrundtasks + +Sie können Hintergrundtasks (Hintergrund-Aufgaben) definieren, die *nach* der RÃŒckgabe einer Response ausgefÃŒhrt werden sollen. + +Das ist nÃŒtzlich fÃŒr VorgÀnge, die nach einem Request ausgefÃŒhrt werden mÃŒssen, bei denen der Client jedoch nicht unbedingt auf den Abschluss des Vorgangs warten muss, bevor er die Response erhÀlt. + +Hierzu zÀhlen beispielsweise: + +* E-Mail-Benachrichtigungen, die nach dem AusfÃŒhren einer Aktion gesendet werden: + * Da die Verbindung zu einem E-Mail-Server und das Senden einer E-Mail in der Regel „langsam“ ist (einige Sekunden), können Sie die Response sofort zurÃŒcksenden und die E-Mail-Benachrichtigung im Hintergrund senden. +* Daten verarbeiten: + * Angenommen, Sie erhalten eine Datei, die einen langsamen Prozess durchlaufen muss. Sie können als Response „Accepted“ (HTTP 202) zurÃŒckgeben und die Datei im Hintergrund verarbeiten. + +## `BackgroundTasks` verwenden + +Importieren Sie zunÀchst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`: + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** erstellt fÃŒr Sie das Objekt vom Typ `BackgroundTasks` und ÃŒbergibt es als diesen Parameter. + +## Eine Taskfunktion erstellen + +Erstellen Sie eine Funktion, die als Hintergrundtask ausgefÃŒhrt werden soll. + +Es handelt sich schlicht um eine Standard-Funktion, die Parameter empfangen kann. + +Es kann sich um eine `async def`- oder normale `def`-Funktion handeln. **FastAPI** weiß, wie damit zu verfahren ist. + +In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail simulierend). + +Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`: + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## Den Hintergrundtask hinzufÃŒgen + +Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt: + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` erhÀlt als Argumente: + +* Eine Taskfunktion, die im Hintergrund ausgefÃŒhrt wird (`write_notification`). +* Eine beliebige Folge von Argumenten, die der Reihe nach an die Taskfunktion ÃŒbergeben werden sollen (`email`). +* Alle SchlÃŒsselwort-Argumente, die an die Taskfunktion ÃŒbergeben werden sollen (`message="some notification"`). + +## Dependency Injection + +Die Verwendung von `BackgroundTasks` funktioniert auch mit dem Dependency Injection System. Sie können einen Parameter vom Typ `BackgroundTasks` auf mehreren Ebenen deklarieren: in einer *Pfadoperation-Funktion*, in einer AbhÀngigkeit (Dependable), in einer UnterabhÀngigkeit usw. + +**FastAPI** weiß, was jeweils zu tun ist und wie dasselbe Objekt wiederverwendet werden kann, sodass alle Hintergrundtasks zusammengefÃŒhrt und anschließend im Hintergrund ausgefÃŒhrt werden: + +=== "Python 3.10+" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14 16 23 26" + {!> ../../../docs_src/background_tasks/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11 13 20 23" + {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002.py!} + ``` + +In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben. + +Wenn im Request ein Query-Parameter enthalten war, wird dieser in einem Hintergrundtask in das Log geschrieben. + +Und dann schreibt ein weiterer Hintergrundtask, der in der *Pfadoperation-Funktion* erstellt wird, eine Nachricht unter Verwendung des Pfad-Parameters `email`. + +## Technische Details + +Die Klasse `BackgroundTasks` stammt direkt von `starlette.background`. + +Sie wird direkt in FastAPI importiert/inkludiert, sodass Sie sie von `fastapi` importieren können und vermeiden, versehentlich das alternative `BackgroundTask` (ohne das `s` am Ende) von `starlette.background` zu importieren. + +Indem Sie nur `BackgroundTasks` (und nicht `BackgroundTask`) verwenden, ist es dann möglich, es als *Pfadoperation-Funktion*-Parameter zu verwenden und **FastAPI** den Rest fÃŒr Sie erledigen zu lassen, genau wie bei der direkten Verwendung des `Request`-Objekts. + +Es ist immer noch möglich, `BackgroundTask` allein in FastAPI zu verwenden, aber Sie mÃŒssen das Objekt in Ihrem Code erstellen und eine Starlette-`Response` zurÃŒckgeben, die es enthÀlt. + +Weitere Details finden Sie in der offiziellen Starlette-Dokumentation fÃŒr Hintergrundtasks. + +## Vorbehalt + +Wenn Sie umfangreiche Hintergrundberechnungen durchfÃŒhren mÃŒssen und diese nicht unbedingt vom selben Prozess ausgefÃŒhrt werden mÃŒssen (z. B. mÃŒssen Sie Speicher, Variablen, usw. nicht gemeinsam nutzen), könnte die Verwendung anderer größerer Tools wie z. B. Celery von Vorteil sein. + +Sie erfordern in der Regel komplexere Konfigurationen und einen Nachrichten-/Job-Queue-Manager wie RabbitMQ oder Redis, ermöglichen Ihnen jedoch die AusfÃŒhrung von Hintergrundtasks in mehreren Prozessen und insbesondere auf mehreren Servern. + +Um ein Beispiel zu sehen, sehen Sie sich die [Projektgeneratoren](../project-generation.md){.internal-link target=_blank} an. Sie alle enthalten Celery, bereits konfiguriert. + +Wenn Sie jedoch ÃŒber dieselbe **FastAPI**-Anwendung auf Variablen und Objekte zugreifen oder kleine Hintergrundtasks ausfÃŒhren mÃŒssen (z. B. das Senden einer E-Mail-Benachrichtigung), können Sie einfach `BackgroundTasks` verwenden. + +## Zusammenfassung + +Importieren und verwenden Sie `BackgroundTasks` mit Parametern in *Pfadoperation-Funktionen* und AbhÀngigkeiten, um Hintergrundtasks hinzuzufÃŒgen. From 4f9ad80f5d48377dae978130692dc4965fa19a2a Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 14:15:52 +0000 Subject: [PATCH 161/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4e795b8cc33a6..b69ad9e784a5c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB). * ✏ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). From 0aee526de9fa908027c100237a692407a5e49818 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 12 Jan 2024 15:38:17 +0100 Subject: [PATCH 162/217] =?UTF-8?q?=F0=9F=94=A7=20=20Add=20support=20for?= =?UTF-8?q?=20translations=20to=20languages=20with=20a=20longer=20code=20n?= =?UTF-8?q?ame,=20like=20`zh-hant`=20(#10950)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/language_names.yml | 1 + scripts/docs.py | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/language_names.yml b/docs/language_names.yml index fbbbde303e31a..7c37ff2b13271 100644 --- a/docs/language_names.yml +++ b/docs/language_names.yml @@ -179,4 +179,5 @@ yi: יי֎דיש yo: Yorùbá za: Saɯ cueŋƅ zh: 汉语 +zh-hant: 繁體䞭文 zu: isiZulu diff --git a/scripts/docs.py b/scripts/docs.py index a6710d7a50fac..37a7a34779d1a 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -53,9 +53,6 @@ def get_lang_paths() -> List[Path]: def lang_callback(lang: Optional[str]) -> Union[str, None]: if lang is None: return None - if not lang.isalpha() or len(lang) != 2: - typer.echo("Use a 2 letter language code, like: es") - raise typer.Abort() lang = lang.lower() return lang @@ -289,6 +286,12 @@ def update_config() -> None: for lang_dict in languages: code = list(lang_dict.keys())[0] url = lang_dict[code] + if code not in local_language_names: + print( + f"Missing language name for: {code}, " + "update it in docs/language_names.yml" + ) + raise typer.Abort() use_name = f"{code} - {local_language_names[code]}" new_alternate.append({"link": url, "name": use_name}) new_alternate.append({"link": "/em/", "name": "😉"}) From 44f3ebce6edc3926876ac0c0370fa8b69e2dea19 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 14:38:40 +0000 Subject: [PATCH 163/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b69ad9e784a5c..eb78fe8cf9065 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,10 @@ hide: * ✏ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). +### Internal + +* 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo). + ## 0.109.0 ### Features From be0bd344463c04ce095051a1fd6bf209165b3e94 Mon Sep 17 00:00:00 2001 From: ooknimm <68068775+ooknimm@users.noreply.github.com> Date: Fri, 12 Jan 2024 23:52:00 +0900 Subject: [PATCH 164/217] =?UTF-8?q?=E2=9C=85=20Re-enable=20test=20in=20`te?= =?UTF-8?q?sts/test=5Ftutorial/test=5Fheader=5Fparams/test=5Ftutorial003.p?= =?UTF-8?q?y`=20after=20fix=20in=20Starlette=20(#10904)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../test_tutorial/test_header_params/test_tutorial003.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/test_tutorial/test_header_params/test_tutorial003.py b/tests/test_tutorial/test_header_params/test_tutorial003.py index 268df7a3e9a80..6f7de8ed41acd 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial003.py +++ b/tests/test_tutorial/test_header_params/test_tutorial003.py @@ -12,8 +12,12 @@ [ ("/items", None, 200, {"X-Token values": None}), ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), + ( + "/items", + [("x-token", "foo"), ("x-token", "bar")], + 200, + {"X-Token values": ["foo", "bar"]}, + ), ], ) def test(path, headers, expected_status, expected_response): From 22e5d9e27fd3079e693cda8ae5c5a44c53b61ca2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 14:52:20 +0000 Subject: [PATCH 165/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index eb78fe8cf9065..2f82b70d685ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm). + ### Docs * 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo). From 91666b3556aedbaae2c84112ac272d23f312e5cb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 12 Jan 2024 10:00:18 -0500 Subject: [PATCH 166/217] =?UTF-8?q?=E2=AC=86=20Bump=20dawidd6/action-downl?= =?UTF-8?q?oad-artifact=20from=202.28.0=20to=203.0.0=20(#10777)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 2.28.0 to 3.0.0. - [Release notes](https://github.com/dawidd6/action-download-artifact/releases) - [Commits](https://github.com/dawidd6/action-download-artifact/compare/v2.28.0...v3.0.0) --- updated-dependencies: - dependency-name: dawidd6/action-download-artifact dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/deploy-docs.yml | 2 +- .github/workflows/smokeshow.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 155ebd0a8e86f..2bec6682c1513 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -21,7 +21,7 @@ jobs: mkdir ./site - name: Download Artifact Docs id: download - uses: dawidd6/action-download-artifact@v2.28.0 + uses: dawidd6/action-download-artifact@v3.0.0 with: if_no_artifact_found: ignore github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index 38b44c41300f1..229f56a9fe34b 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -24,7 +24,7 @@ jobs: - run: pip install smokeshow - - uses: dawidd6/action-download-artifact@v2.28.0 + - uses: dawidd6/action-download-artifact@v3.0.0 with: github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} workflow: test.yml From 0ce4f80ac9aea70af3425bd337c875a85b2d4625 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 15:00:39 +0000 Subject: [PATCH 167/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f82b70d685ad..156c48bbe20a3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -37,6 +37,7 @@ hide: ### Internal +* ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo). ## 0.109.0 From 25646a5070064053309259f1e69c98015c5ec633 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jiri=20Dan=C4=9Bk?= Date: Fri, 12 Jan 2024 16:01:06 +0100 Subject: [PATCH 168/217] =?UTF-8?q?=F0=9F=94=A7=20Fix=20Ruff=20configurati?= =?UTF-8?q?on=20unintentionally=20enabling=20and=20re-disabling=20mccabe?= =?UTF-8?q?=20complexity=20check=20(#10893)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix mistake in Ruff configuration unintentionally enabling mccabe complexity check Enabling "C" turns on complexity checks (C90, mccabe), which is unintended Instead, enable "C4" to get flake8-comprehensions checks See docs at https://docs.astral.sh/ruff/rules/#flake8-comprehensions-c4 Co-authored-by: Sebastián Ramírez --- pyproject.toml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 8e7f8bbbe5914..3e43f35e17cac 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -145,15 +145,14 @@ select = [ "W", # pycodestyle warnings "F", # pyflakes "I", # isort - "C", # flake8-comprehensions "B", # flake8-bugbear + "C4", # flake8-comprehensions "UP", # pyupgrade ] ignore = [ "E501", # line too long, handled by black "B008", # do not perform function calls in argument defaults - "C901", # too complex - "W191", # indentation contains tabs + "W191", # indentation contains tabs ] [tool.ruff.per-file-ignores] From a2937099982b7da564279619f0cb257df33521f6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 12 Jan 2024 10:01:52 -0500 Subject: [PATCH 169/217] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.8.10=20to=201.8.11=20(#10731)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.8.10 to 1.8.11. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.8.10...v1.8.11) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 8cbd01b92b098..d053be0a0601a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -32,7 +32,7 @@ jobs: - name: Build distribution run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.8.10 + uses: pypa/gh-action-pypi-publish@v1.8.11 with: password: ${{ secrets.PYPI_API_TOKEN }} - name: Dump GitHub context From c9e46ae12cfe5e32a25a78dca7499db1fae55059 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 15:02:38 +0000 Subject: [PATCH 170/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 156c48bbe20a3..558bd10b1f313 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek). * ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm). ### Docs From bc7d026b6ca487598a758b20c5935ccde1eace11 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 15:04:40 +0000 Subject: [PATCH 171/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 558bd10b1f313..65128b29a9375 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -38,6 +38,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo). From b0cd4f915bce79575e890e4ae0cccd5b15f2e38f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 12 Jan 2024 16:13:58 +0100 Subject: [PATCH 172/217] =?UTF-8?q?=E2=AC=86=20Bump=20actions/setup-python?= =?UTF-8?q?=20from=204=20to=205=20(#10764)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [actions/setup-python](https://github.com/actions/setup-python) from 4 to 5. - [Release notes](https://github.com/actions/setup-python/releases) - [Commits](https://github.com/actions/setup-python/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/setup-python dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build-docs.yml | 4 ++-- .github/workflows/publish.yml | 2 +- .github/workflows/smokeshow.yml | 2 +- .github/workflows/test.yml | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 51c069d9ebebb..abf2b90f688b2 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -39,7 +39,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" - uses: actions/cache@v3 @@ -80,7 +80,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" - uses: actions/cache@v3 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index d053be0a0601a..8ebb28a80fbcf 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -15,7 +15,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.10" # Issue ref: https://github.com/actions/setup-python/issues/436 diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index 229f56a9fe34b..10bff67aeeb62 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -18,7 +18,7 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.9' diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 032db9c9c85b4..b6b1736851e1f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -19,7 +19,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" # Issue ref: https://github.com/actions/setup-python/issues/436 @@ -57,7 +57,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} # Issue ref: https://github.com/actions/setup-python/issues/436 @@ -98,7 +98,7 @@ jobs: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.8' # Issue ref: https://github.com/actions/setup-python/issues/436 From 26e57903d134742ba0ee8e65ce7985cd398afdea Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 12 Jan 2024 15:14:18 +0000 Subject: [PATCH 173/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 65128b29a9375..19b4d8a35ad19 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -38,6 +38,7 @@ hide: ### Internal +* ⬆ Bump actions/setup-python from 4 to 5. PR [#10764](https://github.com/tiangolo/fastapi/pull/10764) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo). From fad1a464e73003feb8d5ae47f5d676faf353dd3e Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Sat, 13 Jan 2024 02:00:31 +0100 Subject: [PATCH 174/217] =?UTF-8?q?=F0=9F=94=A7=20=20Group=20dependencies?= =?UTF-8?q?=20on=20dependabot=20updates=20(#10952)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/dependabot.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index cd972a0ba4722..0a59adbd6b474 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,6 +11,10 @@ updates: - package-ecosystem: "pip" directory: "/" schedule: - interval: "daily" + interval: "monthly" + groups: + python-packages: + patterns: + - "*" commit-message: prefix: ⬆ From 1ce27fd743cf95901ca44fcf24805b596615581a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 01:00:55 +0000 Subject: [PATCH 175/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 19b4d8a35ad19..13efb84e96a36 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -38,6 +38,7 @@ hide: ### Internal +* 🔧 Group dependencies on dependabot updates. PR [#10952](https://github.com/tiangolo/fastapi/pull/10952) by [@Kludex](https://github.com/Kludex). * ⬆ Bump actions/setup-python from 4 to 5. PR [#10764](https://github.com/tiangolo/fastapi/pull/10764) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot). From 1caee0f105d64f475e369a82f9cac90472e54d61 Mon Sep 17 00:00:00 2001 From: Ahmed Ashraf <104530599+ahmedabdou14@users.noreply.github.com> Date: Sat, 13 Jan 2024 14:49:05 +0300 Subject: [PATCH 176/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20Pydantic=20m?= =?UTF-8?q?ethod=20name=20in=20`docs/en/docs/advanced/path-operation-advan?= =?UTF-8?q?ced-configuration.md`=20(#10826)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ahmed Ashraf --- docs/en/docs/advanced/path-operation-advanced-configuration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index 7ca88d43ed277..8b79bfe22a213 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -163,7 +163,7 @@ For example, in this application we don't use FastAPI's integrated functionality ``` !!! info - In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_schema_json()`. + In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML. From cc5711e6f105251f8e1952c0a10c660a258a0ed3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 11:49:51 +0000 Subject: [PATCH 177/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 13efb84e96a36..973073205b968 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +* ✏ Fix Pydantic method name in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#10826](https://github.com/tiangolo/fastapi/pull/10826) by [@ahmedabdou14](https://github.com/ahmedabdou14). + ### Refactors * 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek). From c3e2aa9dc2b1fbdb48009ed532410e1e75c2f231 Mon Sep 17 00:00:00 2001 From: fhabers21 <58401847+fhabers21@users.noreply.github.com> Date: Sat, 13 Jan 2024 12:50:36 +0100 Subject: [PATCH 178/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20German=20translati?= =?UTF-8?q?on=20for=20`docs/de/docs/tutorial/index.md`=20(#9502)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/de/docs/tutorial/index.md | 80 ++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 docs/de/docs/tutorial/index.md diff --git a/docs/de/docs/tutorial/index.md b/docs/de/docs/tutorial/index.md new file mode 100644 index 0000000000000..dd7ed43bdab62 --- /dev/null +++ b/docs/de/docs/tutorial/index.md @@ -0,0 +1,80 @@ +# Tutorial - Benutzerhandbuch - Intro + +Diese Anleitung zeigt Ihnen Schritt fÃŒr Schritt, wie Sie **FastAPI** mit den meisten Funktionen nutzen können. + +Jeder Abschnitt baut schrittweise auf den vorhergehenden auf. Diese Abschnitte sind aber nach einzelnen Themen gegliedert, sodass Sie direkt zu einem bestimmten Thema ÃŒbergehen können, um Ihre speziellen API-Anforderungen zu lösen. + +Außerdem dienen diese als zukÃŒnftige Referenz. + +Dadurch können Sie jederzeit zurÃŒckkommen und sehen genau das, was Sie benötigen. + +## Den Code ausfÃŒhren + +Alle Codeblöcke können kopiert und direkt verwendet werden (da es sich um getestete Python-Dateien handelt). + +Um eines der Beispiele auszufÃŒhren, kopieren Sie den Code in die Datei `main.py`, und starten Sie `uvicorn` mit: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +Es wird **ausdrÌcklich empfohlen**, dass Sie den Code schreiben oder kopieren, ihn bearbeiten und lokal ausfÌhren. + +Die Verwendung in Ihrem eigenen Editor zeigt Ihnen die Vorteile von FastAPI am besten, wenn Sie sehen, wie wenig Code Sie schreiben mÌssen, all die TypprÌfungen, die automatische VervollstÀndigung usw. + +--- + +## FastAPI installieren + +Der erste Schritt besteht aus der Installation von FastAPI. + +FÌr dieses Tutorial empfiehlt es sich, FastAPI mit allen optionalen AbhÀngigkeiten und Funktionen zu installieren: + +
+ +```console +$ pip install "fastapi[all]" + +---> 100% +``` + +
+ +...dies beinhaltet auch `uvicorn`, das Sie als Server verwenden können, auf dem Ihr Code lÀuft. + +!!! Hinweis + Sie können die Installation auch in einzelnen Schritten ausfÃŒhren. + + Dies werden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung produktiv einsetzen möchten: + + ``` + pip install fastapi + ``` + + Installieren Sie auch `uvicorn`, dies arbeitet als Server: + + ``` + pip install "uvicorn[standard]" + ``` + + Dasselbe gilt fÃŒr jede der optionalen AbhÀngigkeiten, die Sie verwenden möchten. + +## Erweitertes Benutzerhandbuch + +ZusÀtzlich gibt es ein **Erweitertes Benutzerhandbuch**, dies können Sie spÀter nach diesem **Tutorial - Benutzerhandbuch** lesen. + +Das **Erweiterte Benutzerhandbuch** baut auf dieses Tutorial auf, verwendet dieselben Konzepte und bringt Ihnen zusÀtzliche Funktionen bei. + +Allerdings sollten Sie zuerst das **Tutorial - Benutzerhandbuch** lesen (was Sie gerade lesen). + +Es ist so konzipiert, dass Sie nur mit dem **Tutorial - Benutzerhandbuch** eine vollstÀndige Anwendung erstellen können und diese dann je nach Bedarf mit einigen der zusÀtzlichen Ideen aus dem **Erweiterten Benutzerhandbuch** erweitern können. From 4299e712fb600b6460f85f551a2dd1d75ca7be05 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 11:51:55 +0000 Subject: [PATCH 179/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 973073205b968..66f14ef1e1a43 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,7 @@ hide: ### Translations +* 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21). * 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB). * ✏ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). From a37ac3819ee9b8d19d045d53d742779109d2f711 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Jos=C3=A9=20L=C3=B3pez=20Lira?= Date: Sat, 13 Jan 2024 06:57:27 -0500 Subject: [PATCH 180/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typos=20for?= =?UTF-8?q?=20Spanish=20documentation=20(#10957)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/advanced/additional-status-codes.md | 2 +- docs/es/docs/advanced/response-directly.md | 2 +- docs/es/docs/features.md | 14 +++++++------- docs/es/docs/index.md | 8 ++++---- docs/es/docs/python-types.md | 16 ++++++++-------- docs/es/docs/tutorial/first-steps.md | 2 +- docs/es/docs/tutorial/index.md | 2 +- docs/es/docs/tutorial/path-params.md | 6 +++--- 8 files changed, 26 insertions(+), 26 deletions(-) diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index 1f28ea85b738a..eaa3369ebe0b7 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -23,7 +23,7 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte No será serializado con el modelo, etc. - Asegurate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). + Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). !!! note "Detalles Técnicos" También podrías utilizar `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 54dadf5763a9b..dee44ac08a239 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -21,7 +21,7 @@ Y cuando devuelves una `Response`, **FastAPI** la pasará directamente. No hará ninguna conversión de datos con modelos Pydantic, no convertirá el contenido a ningún tipo, etc. -Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquer declaración de datos o validación, etc. +Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquier declaración de datos o validación, etc. ## Usando el `jsonable_encoder` en una `Response` diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index d05c4f73e4058..d68791d635f95 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -13,7 +13,7 @@ ### Documentación automática -Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluídas por defecto, porque el framework está basado en OpenAPI. +Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluidas por defecto, porque el framework está basado en OpenAPI. * Swagger UI, con exploración interactiva, llama y prueba tu API directamente desde tu navegador. @@ -25,7 +25,7 @@ Documentación interactiva de la API e interfaces web de exploración. Hay múlt ### Simplemente Python moderno -Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintáxis nueva, solo Python moderno. +Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintaxis nueva, solo Python moderno. Si necesitas un repaso de 2 minutos de cómo usar los tipos de Python (así no uses FastAPI) prueba el tutorial corto: [Python Types](python-types.md){.internal-link target=_blank}. @@ -72,9 +72,9 @@ my_second_user: User = User(**second_user_data) El framework fue diseñado en su totalidad para ser fácil e intuitivo de usar. Todas las decisiones fueron probadas en múltiples editores antes de comenzar el desarrollo para asegurar la mejor experiencia de desarrollo. -En la última encuesta a desarrolladores de Python fue claro que la característica más usada es el "autocompletado". +En la última encuesta a desarrolladores de Python fue claro que la característica más usada es el "auto-completado". -El framework **FastAPI** está creado para satisfacer eso. El autocompletado funciona en todas partes. +El framework **FastAPI** está creado para satisfacer eso. El auto-completado funciona en todas partes. No vas a tener que volver a la documentación seguido. @@ -140,13 +140,13 @@ FastAPI incluye un sistema de https://github.com/florimondmanca/asgi-lifespan#usage. + If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan. ## Other Asynchronous Function Calls From b24c4870d8f8f0547d956ac8c1d2c751f1f66b69 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 12:10:29 +0000 Subject: [PATCH 183/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c632cc0b06fd7..2234624f07b5e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Docs +* ✏ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typos for Spanish documentation. PR [#10957](https://github.com/tiangolo/fastapi/pull/10957) by [@jlopezlira](https://github.com/jlopezlira). * 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo). * ✏ Fix broken link in `docs/tutorial/sql-databases.md` in several languages. PR [#10716](https://github.com/tiangolo/fastapi/pull/10716) by [@theoohoho](https://github.com/theoohoho). From 83e386519d30d8c732249983ffdf7200e8af5a5d Mon Sep 17 00:00:00 2001 From: Nils Lindemann Date: Sat, 13 Jan 2024 13:16:22 +0100 Subject: [PATCH 184/217] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20A=20few=20tweaks?= =?UTF-8?q?=20in=20`docs/de/docs/tutorial/first-steps.md`=20(#10959)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/first-steps.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index 5997f138f0ac3..27ba3ec16795e 100644 --- a/docs/de/docs/tutorial/first-steps.md +++ b/docs/de/docs/tutorial/first-steps.md @@ -43,7 +43,7 @@ Diese Zeile zeigt die URL, unter der Ihre Anwendung auf Ihrem lokalen Computer b Öffnen Sie Ihren Browser unter http://127.0.0.1:8000. -Sie werden folgende JSON-Antwort sehen: +Sie werden folgende JSON-Response sehen: ```JSON {"message": "Hello World"} @@ -81,7 +81,7 @@ Diese Schemadefinition enthÀlt Ihre API-Pfade, die möglichen Parameter, welche #### Daten-„Schema“ -Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z.B. einen JSON-Inhalt. +Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z. B. einen JSON-Inhalt. In diesem Fall sind die JSON-Attribute und deren Datentypen, usw. gemeint. @@ -328,6 +328,6 @@ Es gibt viele andere Objekte und Modelle, die automatisch zu JSON konvertiert we * Importieren Sie `FastAPI`. * Erstellen Sie eine `app` Instanz. -* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z.B. `@app.get("/")`). -* Schreiben Sie eine **Pfadoperation-Funktion** (wie z.B. oben `def root(): ...`). -* Starten Sie den Entwicklungsserver (z.B. `uvicorn main:app --reload`). +* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z. B. `@app.get("/")`). +* Schreiben Sie eine **Pfadoperation-Funktion** (wie z. B. oben `def root(): ...`). +* Starten Sie den Entwicklungsserver (z. B. `uvicorn main:app --reload`). From cca6203c18552aa95c7ad0f7fd972fd6e86d0d77 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 12:19:28 +0000 Subject: [PATCH 185/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2234624f07b5e..510b842ba7f29 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Docs +* ✏ A few tweaks in `docs/de/docs/tutorial/first-steps.md`. PR [#10959](https://github.com/tiangolo/fastapi/pull/10959) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typos for Spanish documentation. PR [#10957](https://github.com/tiangolo/fastapi/pull/10957) by [@jlopezlira](https://github.com/jlopezlira). * 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo). From de0126d145c920c992c605538e63fe0e46b508d5 Mon Sep 17 00:00:00 2001 From: Evgenii Date: Sat, 13 Jan 2024 17:31:38 +0300 Subject: [PATCH 186/217] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Simplify=20string?= =?UTF-8?q?=20format=20with=20f-strings=20in=20`fastapi/utils.py`=20(#1057?= =?UTF-8?q?6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/utils.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fastapi/utils.py b/fastapi/utils.py index f8463dda24675..0019c21532b48 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -173,17 +173,17 @@ def generate_operation_id_for_path( DeprecationWarning, stacklevel=2, ) - operation_id = name + path + operation_id = f"{name}{path}" operation_id = re.sub(r"\W", "_", operation_id) - operation_id = operation_id + "_" + method.lower() + operation_id = f"{operation_id}_{method.lower()}" return operation_id def generate_unique_id(route: "APIRoute") -> str: - operation_id = route.name + route.path_format + operation_id = f"{route.name}{route.path_format}" operation_id = re.sub(r"\W", "_", operation_id) assert route.methods - operation_id = operation_id + "_" + list(route.methods)[0].lower() + operation_id = f"{operation_id}_{list(route.methods)[0].lower()}" return operation_id From 61a08d0c60cbe29784bb64cdbdea5d613a38b2e5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 14:31:58 +0000 Subject: [PATCH 187/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 510b842ba7f29..1fc1a16955515 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,7 @@ hide: ### Refactors +* ♻ Simplify string format with f-strings in `fastapi/utils.py`. PR [#10576](https://github.com/tiangolo/fastapi/pull/10576) by [@eukub](https://github.com/eukub). * 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek). * ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm). From f18eadb7de142d6bf37eff900731329a541758f5 Mon Sep 17 00:00:00 2001 From: Emmett Butler <723615+emmettbutler@users.noreply.github.com> Date: Sat, 13 Jan 2024 07:10:26 -0800 Subject: [PATCH 188/217] =?UTF-8?q?=E2=9C=85=20Refactor=20tests=20for=20du?= =?UTF-8?q?plicate=20operation=20ID=20generation=20for=20compatibility=20w?= =?UTF-8?q?ith=20other=20tools=20running=20the=20FastAPI=20test=20suite=20?= =?UTF-8?q?(#10876)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- tests/test_generate_unique_id_function.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/test_generate_unique_id_function.py b/tests/test_generate_unique_id_function.py index c5ef5182b73f7..5aeec66367a7c 100644 --- a/tests/test_generate_unique_id_function.py +++ b/tests/test_generate_unique_id_function.py @@ -1626,6 +1626,9 @@ def post_third(item1: Item): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") client.get("/openapi.json") - assert len(w) == 2 - assert issubclass(w[-1].category, UserWarning) - assert "Duplicate Operation ID" in str(w[-1].message) + assert len(w) >= 2 + duplicate_warnings = [ + warning for warning in w if issubclass(warning.category, UserWarning) + ] + assert len(duplicate_warnings) > 0 + assert "Duplicate Operation ID" in str(duplicate_warnings[0].message) From e90fc7bed4213fbf42195830a1a8f54288be4fb8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 13 Jan 2024 15:10:47 +0000 Subject: [PATCH 189/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1fc1a16955515..5e02e2352e7c4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,7 @@ hide: ### Refactors +* ✅ Refactor tests for duplicate operation ID generation for compatibility with other tools running the FastAPI test suite. PR [#10876](https://github.com/tiangolo/fastapi/pull/10876) by [@emmettbutler](https://github.com/emmettbutler). * ♻ Simplify string format with f-strings in `fastapi/utils.py`. PR [#10576](https://github.com/tiangolo/fastapi/pull/10576) by [@eukub](https://github.com/eukub). * 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek). * ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm). From dcc952d6990c507956669e6fc5cddba0530c79d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 15 Jan 2024 11:32:16 +0100 Subject: [PATCH 190/217] =?UTF-8?q?=E2=9C=A8=20=20Include=20HTTP=20205=20i?= =?UTF-8?q?n=20status=20codes=20with=20no=20body=20(#10969)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/utils.py b/fastapi/utils.py index 0019c21532b48..53b2fa0c36ba6 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -53,7 +53,7 @@ def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: }: return True current_status_code = int(status_code) - return not (current_status_code < 200 or current_status_code in {204, 304}) + return not (current_status_code < 200 or current_status_code in {204, 205, 304}) def get_path_param_names(path: str) -> Set[str]: From 69dc735fc2339f8b39a9f1b01ced7974df9c4a65 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 10:32:42 +0000 Subject: [PATCH 191/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 5e02e2352e7c4..7b09977e701a0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,10 @@ hide: * ✏ Fix Pydantic method name in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#10826](https://github.com/tiangolo/fastapi/pull/10826) by [@ahmedabdou14](https://github.com/ahmedabdou14). +### Features + +* ✹ Include HTTP 205 in status codes with no body. PR [#10969](https://github.com/tiangolo/fastapi/pull/10969) by [@tiangolo](https://github.com/tiangolo). + ### Refactors * ✅ Refactor tests for duplicate operation ID generation for compatibility with other tools running the FastAPI test suite. PR [#10876](https://github.com/tiangolo/fastapi/pull/10876) by [@emmettbutler](https://github.com/emmettbutler). From 63e5396a78a470c39558a37d1fefbbe1bcbf4db7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 15 Jan 2024 16:13:48 +0100 Subject: [PATCH 192/217] =?UTF-8?q?=F0=9F=91=B7=20Add=20changes-requested?= =?UTF-8?q?=20handling=20in=20GitHub=20Action=20issue=20manager=20(#10971)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/issue-manager.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index bb967fa118362..d1aad28fd3160 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -31,5 +31,9 @@ jobs: "answered": { "delay": 864000, "message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs." + }, + "changes-requested": { + "delay": 2628000, + "message": "As this PR had requested changes to be applied but has been inactive for a while, it's now going to be closed. But if there's anyone interested, feel free to create a new PR." } } From 2b6f12a5d00717f40b1fa0fa5e882fe021862559 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:14:34 +0000 Subject: [PATCH 193/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7b09977e701a0..c7ef17d65d21d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -50,6 +50,7 @@ hide: ### Internal +* 👷 Add changes-requested handling in GitHub Action issue manager. PR [#10971](https://github.com/tiangolo/fastapi/pull/10971) by [@tiangolo](https://github.com/tiangolo). * 🔧 Group dependencies on dependabot updates. PR [#10952](https://github.com/tiangolo/fastapi/pull/10952) by [@Kludex](https://github.com/Kludex). * ⬆ Bump actions/setup-python from 4 to 5. PR [#10764](https://github.com/tiangolo/fastapi/pull/10764) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot). From cf01195555ea0111a9540bccc1444b9d802587da Mon Sep 17 00:00:00 2001 From: Pedro Augusto de Paula Barbosa Date: Mon, 15 Jan 2024 12:17:34 -0300 Subject: [PATCH 194/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20`HTTPException`?= =?UTF-8?q?=20details=20in=20`docs/en/docs/tutorial/handling-errors.md`=20?= =?UTF-8?q?(#5418)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/handling-errors.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index a03029e811356..7d521696d88ef 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -234,9 +234,7 @@ You will receive a response telling you that the data is invalid containing the And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class. -The only difference, is that **FastAPI**'s `HTTPException` allows you to add headers to be included in the response. - -This is needed/used internally for OAuth 2.0 and some security utilities. +The only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it. So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code. From 32ae9497233a9dc859a17f642c6b9bca0260f9ca Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:17:54 +0000 Subject: [PATCH 195/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c7ef17d65d21d..771d286a11952 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Docs +* 📝 Update `HTTPException` details in `docs/en/docs/tutorial/handling-errors.md`. PR [#5418](https://github.com/tiangolo/fastapi/pull/5418) by [@papb](https://github.com/papb). * ✏ A few tweaks in `docs/de/docs/tutorial/first-steps.md`. PR [#10959](https://github.com/tiangolo/fastapi/pull/10959) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typos for Spanish documentation. PR [#10957](https://github.com/tiangolo/fastapi/pull/10957) by [@jlopezlira](https://github.com/jlopezlira). From 15429a9c395df0378aa58fdee00c9b63a7a40358 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:33:28 +0900 Subject: [PATCH 196/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/body-fields.md`=20(#1923)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/body-fields.md | 48 ++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 docs/ja/docs/tutorial/body-fields.md diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md new file mode 100644 index 0000000000000..8f01e821624d0 --- /dev/null +++ b/docs/ja/docs/tutorial/body-fields.md @@ -0,0 +1,48 @@ +# ボディ - フィヌルド + +`Query`や`Path`、`Body`を䜿っお *path operation関数* のパラメヌタに远加のバリデヌションやメタデヌタを宣蚀するのず同じように、Pydanticの`Field`を䜿っおPydanticモデルの内郚でバリデヌションやメタデヌタを宣蚀するこずができたす。 + +## `Field`のむンポヌト + +たず、以䞋のようにむンポヌトしたす: + +```Python hl_lines="4" +{!../../../docs_src/body_fields/tutorial001.py!} +``` + +!!! warning "泚意" + `Field`は他の党おのもの`Query`、`Path`、`Body`などずは違い、`fastapi`からではなく、`pydantic`から盎接むンポヌトされおいるこずに泚意しおください。 + +## モデルの属性の宣蚀 + +以䞋のように`Field`をモデルの属性ずしお䜿甚するこずができたす: + +```Python hl_lines="11 12 13 14" +{!../../../docs_src/body_fields/tutorial001.py!} +``` + +`Field`は`Query`や`Path`、`Body`ず同じように動䜜し、党く同様のパラメヌタなどを持ちたす。 + +!!! note "技術詳现" + 実際には次に芋る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブゞェクトを䜜成したすが、それ自䜓はPydanticの`FieldInfo`クラスのサブクラスです。 + + たた、Pydanticの`Field`は`FieldInfo`のむンスタンスも返したす。 + + `Body`は`FieldInfo`のサブクラスのオブゞェクトを盎接返すこずもできたす。そしお、他にも`Body`クラスのサブクラスであるものがありたす。 + + `fastapi`から`Query`や`Path`などをむンポヌトする堎合、これらは実際には特殊なクラスを返す関数であるこずに泚意しおください。 + +!!! tip "豆知識" + 型、デフォルト倀、`Field`を持぀各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持぀、*path operation 関数の*パラメヌタず同じ構造になっおいるこずに泚目しおください。 + +## 远加情報の远加 + +远加情報は`Field`や`Query`、`Body`などで宣蚀するこずができたす。そしおそれは生成されたJSONスキヌマに含たれたす。 + +埌に䟋を甚いお宣蚀を孊ぶ際に、远加情報を句悪方法を孊べたす。 + +## たずめ + +Pydanticの`Field`を䜿甚しお、モデルの属性に远加のバリデヌションやメタデヌタを宣蚀するこずができたす。 + +远加のキヌワヌド匕数を䜿甚しお、远加のJSONスキヌマのメタデヌタを枡すこずもできたす。 From 467ab2a5756245cc53a8c0ec4fd467ffbef7d347 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:33:51 +0000 Subject: [PATCH 197/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 771d286a11952..2d73401ef914d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21). * 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann). * ✏ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB). From 88f19be7c38b1c904d453dff3f0f1f97ebdcaec7 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:34:57 +0900 Subject: [PATCH 198/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/body-nested-models.md`=20(#?= =?UTF-8?q?1930)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/body-nested-models.md | 244 ++++++++++++++++++++ 1 file changed, 244 insertions(+) create mode 100644 docs/ja/docs/tutorial/body-nested-models.md diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md new file mode 100644 index 0000000000000..7f916c47a1079 --- /dev/null +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -0,0 +1,244 @@ +# ボディ - ネストされたモデル + +**FastAPI** を䜿甚するず、深くネストされた任意のモデルを定矩、怜蚌、文曞化、䜿甚するこずができたすPydanticのおかげです。 + +## リストのフィヌルド + +属性をサブタむプずしお定矩するこずができたす。䟋えば、Pythonの`list`は以䞋のように定矩できたす: + +```Python hl_lines="12" +{!../../../docs_src/body_nested_models/tutorial001.py!} +``` + +これにより、各項目の型は宣蚀されおいたせんが、`tags`はある項目のリストになりたす。 + +## タむプパラメヌタを持぀リストのフィヌルド + +しかし、Pythonには型や「タむプパラメヌタ」を䜿っおリストを宣蚀する方法がありたす: + +### typingの`List`をむンポヌト + +たず、Pythonの暙準の`typing`モゞュヌルから`List`をむンポヌトしたす: + +```Python hl_lines="1" +{!../../../docs_src/body_nested_models/tutorial002.py!} +``` + +### タむプパラメヌタを持぀`List`の宣蚀 + +`list`や`dict`、`tuple`のようなタむプパラメヌタ内郚の型を持぀型を宣蚀するには: + +* `typing`モゞュヌルからそれらをむンストヌルしたす。 +* 角括匧`[`ず`]`を䜿っお「タむプパラメヌタ」ずしお内郚の型を枡したす: + +```Python +from typing import List + +my_list: List[str] +``` + +型宣蚀の暙準的なPythonの構文はこれだけです。 + +内郚の型を持぀モデルの属性にも同じ暙準の構文を䜿甚しおください。 + +そのため、以䞋の䟋では`tags`を具䜓的な「文字列のリスト」にするこずができたす: + +```Python hl_lines="14" +{!../../../docs_src/body_nested_models/tutorial002.py!} +``` + +## セット型 + +しかし、よく考えおみるず、タグは繰り返すべきではなく、おそらくナニヌクな文字列になるのではないかず気付いたずしたす。 + +そしお、Pythonにはナニヌクな項目のセットのための特別なデヌタ型`set`がありたす。 + +そのため、以䞋のように、`Set`をむンポヌトしお`str`の`set`ずしお`tags`を宣蚀するこずができたす: + +```Python hl_lines="1 14" +{!../../../docs_src/body_nested_models/tutorial003.py!} +``` + +これを䜿えば、デヌタが重耇しおいるリク゚ストを受けた堎合でも、ナニヌクな項目のセットに倉換されたす。 + +そしお、そのデヌタを出力するず、たずえ゜ヌスに重耇があったずしおも、固有の項目のセットずしお出力されたす。 + +たた、それに応じお泚釈を぀けたり、文曞化したりしたす。 + +## ネストされたモデル + +Pydanticモデルの各属性には型がありたす。 + +しかし、その型はそれ自䜓が別のPydanticモデルである可胜性がありたす。 + +そのため、特定の属性名、型、バリデヌションを指定しお、深くネストしたJSON`object`を宣蚀するこずができたす。 + +すべおは、任意のネストにされおいたす。 + +### サブモデルの定矩 + +䟋えば、`Image`モデルを定矩するこずができたす: + +```Python hl_lines="9 10 11" +{!../../../docs_src/body_nested_models/tutorial004.py!} +``` + +### サブモデルを型ずしお䜿甚 + +そしお、それを属性の型ずしお䜿甚するこずができたす: + +```Python hl_lines="20" +{!../../../docs_src/body_nested_models/tutorial004.py!} +``` + +これは **FastAPI** が以䞋のようなボディを期埅するこずを意味したす: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +繰り返しになりたすが、**FastAPI** を䜿甚しお、その宣蚀を行うだけで以䞋のような恩恵を受けられたす: + +* ネストされたモデルでも察応可胜な゚ディタのサポヌト補完など +* デヌタ倉換 +* デヌタの怜蚌 +* 自動文曞化 + +## 特殊な型ずバリデヌション + +`str`や`int`、`float`のような通垞の単数型の他にも、`str`を継承したより耇雑な単数型を䜿うこずもできたす。 + +すべおのオプションをみるには、Pydanticの゚キゟチック な型のドキュメントを確認しおください。次の章でいく぀かの䟋をみるこずができたす。 + +䟋えば、`Image`モデルのように`url`フィヌルドがある堎合、`str`の代わりにPydanticの`HttpUrl`を指定するこずができたす: + +```Python hl_lines="4 10" +{!../../../docs_src/body_nested_models/tutorial005.py!} +``` + +文字列は有効なURLであるこずが確認され、そのようにJSONスキヌマ・OpenAPIで文曞化されたす。 + +## サブモデルのリストを持぀属性 + +Pydanticモデルを`list`や`set`などのサブタむプずしお䜿甚するこずもできたす: + +```Python hl_lines="20" +{!../../../docs_src/body_nested_models/tutorial006.py!} +``` + +これは、次のようなJSONボディを期埅したす倉換、怜蚌、ドキュメントなど: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +!!! info "情報" + `images`キヌが画像オブゞェクトのリストを持぀ようになったこずに泚目しおください。 + +## 深くネストされたモデル + +深くネストされた任意のモデルを定矩するこずができたす: + +```Python hl_lines="9 14 20 23 27" +{!../../../docs_src/body_nested_models/tutorial007.py!} +``` + +!!! info "情報" + `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っおいるこずに泚目しおください。 + +## 玔粋なリストのボディ + +期埅するJSONボディのトップレベルの倀がJSON`array`Pythonの`list`であれば、Pydanticモデルず同じように、関数のパラメヌタで型を宣蚀するこずができたす: + +```Python +images: List[Image] +``` + +以䞋のように: + +```Python hl_lines="15" +{!../../../docs_src/body_nested_models/tutorial008.py!} +``` + +## あらゆる堎所での゚ディタサポヌト + +゚ディタのサポヌトもどこでも受けるこずができたす。 + +以䞋のようにリストの䞭の項目でも: + + + +Pydanticモデルではなく、`dict`を盎接䜿甚しおいる堎合はこのような゚ディタのサポヌトは埗られたせん。 + +しかし、それらに぀いお心配する必芁はありたせん。入力された蟞曞は自動的に倉換され、出力も自動的にJSONに倉換されたす。 + +## 任意の`dict`のボディ + +たた、ある型のキヌず別の型の倀を持぀`dict`ずしおボディを宣蚀するこずもできたす。 + +有効なフィヌルド・属性名を事前に知る必芁がありたせんPydanticモデルの堎合のように。 + +これは、ただ知らないキヌを受け取りたいずきに䟿利だず思いたす。 + +--- + +他にも、`int`のように他の型のキヌを持ちたい堎合などに䟿利です。 + +それをここで芋おいきたしょう。 + +この堎合、`int`のキヌず`float`の倀を持぀ものであれば、どんな`dict`でも受け入れるこずができたす: + +```Python hl_lines="15" +{!../../../docs_src/body_nested_models/tutorial009.py!} +``` + +!!! tip "豆知識" + JSONはキヌずしお`str`しかサポヌトしおいないこずに泚意しおください。 + + しかしPydanticには自動デヌタ倉換機胜がありたす。 + + これは、APIクラむアントがキヌずしお文字列しか送信できなくおも、それらの文字列に玔粋な敎数が含たれおいる限り、Pydanticが倉換しお怜蚌するこずを意味したす。 + + そしお、`weights`ずしお受け取る`dict`は、実際には`int`のキヌず`float`の倀を持぀こずになりたす。 + +## たずめ + +**FastAPI** を䜿甚するず、Pydanticモデルが提䟛する最倧限の柔軟性を持ちながら、コヌドをシンプルに短く、゚レガントに保぀こずができたす。 + +以䞋のような利点がありたす: + +* ゚ディタのサポヌトどこでも補完 +* デヌタ倉換別名構文解析・シリアラむズ +* デヌタの怜蚌 +* スキヌマ文曞 +* 自動文曞化 From 2619bbd7cde8251e955512f560dc632a96f72fe8 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:35:25 +0900 Subject: [PATCH 199/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20tranlsa?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/schema-extra-example.md`=20?= =?UTF-8?q?(#1931)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/schema-extra-example.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/ja/docs/tutorial/schema-extra-example.md diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md new file mode 100644 index 0000000000000..3102a4936248e --- /dev/null +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -0,0 +1,58 @@ +# スキヌマの远加 - 䟋 + +JSON Schemaに远加する情報を定矩するこずができたす。 + +䞀般的なナヌスケヌスはこのドキュメントで瀺されおいるように`example`を远加するこずです。 + +JSON Schemaの远加情報を宣蚀する方法はいく぀かありたす。 + +## Pydanticの`schema_extra` + +Pydanticのドキュメント: スキヌマのカスタマむズで説明されおいるように、`Config`ず`schema_extra`を䜿っおPydanticモデルの䟋を宣蚀するこずができたす: + +```Python hl_lines="15 16 17 18 19 20 21 22 23" +{!../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +その远加情報はそのたた出力され、JSON Schemaに远加されたす。 + +## `Field`の远加匕数 + +埌述する`Field`、`Path`、`Query`、`Body`などでは、任意の匕数を関数に枡すこずでJSON Schemaの远加情報を宣蚀するこずもできたす: + +```Python hl_lines="4 10 11 12 13" +{!../../../docs_src/schema_extra_example/tutorial002.py!} +``` + +!!! warning "泚意" + これらの远加匕数が枡されおも、文曞化のためのバリデヌションは远加されず、泚釈だけが远加されるこずを芚えおおいおください。 + +## `Body`の远加匕数 + +远加情報を`Field`に枡すのず同じように、`Path`、`Query`、`Body`などでも同じこずができたす。 + +䟋えば、`Body`にボディリク゚ストの`example`を枡すこずができたす: + +```Python hl_lines="21 22 23 24 25 26" +{!../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +## ドキュメントのUIの䟋 + +䞊蚘のいずれの方法でも、`/docs`の䞭では以䞋のようになりたす: + + + +## 技術詳现 + +`example` ず `examples`に぀いお... + +JSON Schemaの最新バヌゞョンでは`examples`ずいうフィヌルドを定矩しおいたすが、OpenAPIは`examples`を持たない叀いバヌゞョンのJSON Schemaをベヌスにしおいたす。 + +そのため、OpenAPIでは同じ目的のために`example`を独自に定矩しおおり`examples`ではなく`example`ずしお、それがdocs UISwagger UIを䜿甚で䜿甚されおいたす。 + +぀たり、`example`はJSON Schemaの䞀郚ではありたせんが、OpenAPIの䞀郚であり、それがdocs UIで䜿甚されるこずになりたす。 + +## その他の情報 + +同じように、フロント゚ンドのナヌザヌむンタヌフェヌスなどをカスタマむズするために、各モデルのJSON Schemaに远加される独自の远加情報を远加するこずができたす。 From 79dbb11867f5217e090d3b498d91d9566be2fd95 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:35:41 +0000 Subject: [PATCH 200/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2d73401ef914d..0b820dce19ade 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21). * 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann). From c238292b44340f55df15ea48eb324288b922e85a Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:36:32 +0900 Subject: [PATCH 201/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/extra-models.md`=20(#1941)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/extra-models.md | 195 ++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 docs/ja/docs/tutorial/extra-models.md diff --git a/docs/ja/docs/tutorial/extra-models.md b/docs/ja/docs/tutorial/extra-models.md new file mode 100644 index 0000000000000..aa2e5ffdcbe61 --- /dev/null +++ b/docs/ja/docs/tutorial/extra-models.md @@ -0,0 +1,195 @@ +# モデル - より詳しく + +先ほどの䟋に続き、耇数の関連モデルを持぀こずが䞀般的です。 + +これはナヌザヌモデルの堎合は特にそうです。なぜなら: + +* **入力モデル** にはパスワヌドが必芁です。 +* **出力モデル**はパスワヌドをも぀べきではありたせん。 +* **デヌタベヌスモデル**はおそらくハッシュ化されたパスワヌドが必芁になるでしょう。 + +!!! danger "危険" + ナヌザヌの平文のパスワヌドは絶察に保存しないでください。垞に認蚌に利甚可胜な「安党なハッシュ」を保存しおください。 + + 知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワヌドハッシュ」ずは䜕かを孊ぶこずができたす。 + +## 耇数のモデル + +ここでは、パスワヌドフィヌルドをも぀モデルがどのように芋えるのか、たた、どこで䜿われるのか、倧たかなむメヌゞを玹介したす: + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!../../../docs_src/extra_models/tutorial001.py!} +``` + +### `**user_in.dict()`に぀いお + +#### Pydanticの`.dict()` + +`user_in`は`UserIn`クラスのPydanticモデルです。 + +Pydanticモデルには、モデルのデヌタを含む`dict`を返す`.dict()`メ゜ッドがありたす。 + +そこで、以䞋のようなPydanticオブゞェクト`user_in`を䜜成するず: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +そしお呌び出すず: + +```Python +user_dict = user_in.dict() +``` + +これで倉数`user_dict`のデヌタを持぀`dict`ができたした。これはPydanticモデルのオブゞェクトの代わりに`dict`です。 + +そしお呌び出すず: + +```Python +print(user_dict) +``` + +以䞋のようなPythonの`dict`を埗るこずができたす: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### `dict`の展開 + +`user_dict`のような`dict`を受け取り、それを`**user_dict`を持぀関数たたはクラスに枡すず、Pythonはそれを「展開」したす。これは`user_dict`のキヌず倀を盎接キヌ・バリュヌの匕数ずしお枡したす。 + +そこで䞊述の`user_dict`の続きを以䞋のように曞くず: + +```Python +UserInDB(**user_dict) +``` + +以䞋ず同等の結果になりたす: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +もっず正確に蚀えば、`user_dict`を将来的にどんな内容であっおも盎接䜿甚するこずになりたす: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### 別のモデルから぀くるPydanticモデル + +䞊述の䟋では`user_in.dict()`から`user_dict`をこのコヌドのように取埗しおいたすが: + +```Python +user_dict = user_in.dict() +UserInDB(**user_dict) +``` + +これは以䞋ず同等です: + +```Python +UserInDB(**user_in.dict()) +``` + +...なぜなら`user_in.dict()`は`dict`であり、`**`を付䞎しお`UserInDB`を枡しおPythonに「展開」させおいるからです。 + +そこで、別のPydanticモデルのデヌタからPydanticモデルを取埗したす。 + +#### `dict`の展開ず远加匕数 + +そしお、远加のキヌワヌド匕数`hashed_password=hashed_password`を以䞋のように远加するず: + +```Python +UserInDB(**user_in.dict(), hashed_password=hashed_password) +``` + +...以䞋のようになりたす: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +!!! warning "泚意" + サポヌトしおいる远加機胜は、デヌタの可胜な流れをデモするだけであり、もちろん本圓のセキュリティを提䟛しおいるわけではありたせん。 + +## 重耇の削枛 + +コヌドの重耇を枛らすこずは、**FastAPI**の䞭栞的なアむデアの぀です。 + +コヌドの重耇が増えるず、バグやセキュリティの問題、コヌドの非同期化問題ある堎所では曎新しおも他の堎所では曎新されない堎合などが発生する可胜性が高くなりたす。 + +そしお、これらのモデルは党おのデヌタを共有し、属性名や型を重耇させおいたす。 + +もっず良い方法がありたす。 + +他のモデルのベヌスずなる`UserBase`モデルを宣蚀するこずができたす。そしお、そのモデルの属性型宣蚀、怜蚌などを継承するサブクラスを䜜るこずができたす。 + +デヌタの倉換、怜蚌、文曞化などはすべお通垞通りに動䜜したす。 + +このようにしお、モデル間の違いだけを宣蚀するこずができたす: + +```Python hl_lines="9 15 16 19 20 23 24" +{!../../../docs_src/extra_models/tutorial002.py!} +``` + +## `Union`たたは`anyOf` + +レスポンスを぀の型の`Union`ずしお宣蚀するこずができたす。 + +OpenAPIでは`anyOf`で定矩されたす。 + +そのためには、暙準的なPythonの型ヒント`typing.Union`を䜿甚したす: + +```Python hl_lines="1 14 15 18 19 20 33" +{!../../../docs_src/extra_models/tutorial003.py!} +``` + +## モデルのリスト + +同じように、オブゞェクトのリストのレスポンスを宣蚀するこずができたす。 + +そのためには、暙準のPythonの`typing.List`を䜿甚する: + +```Python hl_lines="1 20" +{!../../../docs_src/extra_models/tutorial004.py!} +``` + +## 任意の`dict`を持぀レスポンス + +たた、Pydanticモデルを䜿甚せずに、キヌず倀の型だけを定矩した任意の`dict`を䜿っおレスポンスを宣蚀するこずもできたす。 + +これは、有効なフィヌルド・属性名Pydanticモデルに必芁なものを事前に知らない堎合に䟿利です。 + +この堎合、`typing.Dict`を䜿甚するこずができたす: + +```Python hl_lines="1 8" +{!../../../docs_src/extra_models/tutorial005.py!} +``` + +## たずめ + +耇数のPydanticモデルを䜿甚し、ケヌスごずに自由に継承したす。 + +゚ンティティが異なる「状態」を持たなければならない堎合は、゚ンティティごずに単䞀のデヌタモデルを持぀必芁はありたせん。`password` や `password_hash` やパスワヌドなしなどのいく぀かの「状態」をも぀ナヌザヌ「゚ンティティ」の堎合の様にすれば良いです。 From f386011d64e68c63f397834eda1c937b660f0d75 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:38:18 +0000 Subject: [PATCH 202/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0b820dce19ade..bca167cd1ff29 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21). From 17511f776891d6bbdaac2a6ba7157b24259210a4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:38:58 +0000 Subject: [PATCH 203/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bca167cd1ff29..33caa2ac7ecca 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc). From 88225ae231731ff266f964f3bf5818a4397db223 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:42:08 +0900 Subject: [PATCH 204/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/response-status-code.md`=20?= =?UTF-8?q?(#1942)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/response-status-code.md | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 docs/ja/docs/tutorial/response-status-code.md diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md new file mode 100644 index 0000000000000..ead2adddaa60b --- /dev/null +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -0,0 +1,89 @@ +# レスポンスステヌタスコヌド + +レスポンスモデルを指定するのず同じ方法で、レスポンスに䜿甚されるHTTPステヌタスコヌドを以䞋の*path operations*のいずれかの`status_code`パラメヌタで宣蚀するこずもできたす。 + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* など。 + +```Python hl_lines="6" +{!../../../docs_src/response_status_code/tutorial001.py!} +``` + +!!! note "備考" + `status_code`は「デコレヌタ」メ゜ッド`get`、`post`などのパラメヌタであるこずに泚意しおください。すべおのパラメヌタやボディのように、*path operation関数*のものではありたせん。 + +`status_code`パラメヌタはHTTPステヌタスコヌドを含む数倀を受け取りたす。 + +!!! info "情報" + `status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取るこずもできたす。 + +これは: + +* レスポンスでステヌタスコヌドを返したす。 +* OpenAPIスキヌマおよびナヌザヌむンタヌフェヌスに以䞋のように文曞化したす: + + + +!!! note "備考" + いく぀かのレスポンスコヌド次のセクションを参照は、レスポンスにボディがないこずを瀺しおいたす。 + + FastAPIはこれを知っおいお、レスポンスボディがないずいうOpenAPIドキュメントを生成したす。 + +## HTTPステヌタスコヌドに぀いお + +!!! note "備考" + すでにHTTPステヌタスコヌドが䜕であるかを知っおいる堎合は、次のセクションにスキップしおください。 + +HTTPでは、レスポンスの䞀郚ずしお桁の数字のステヌタスコヌドを送信したす。 + +これらのステヌタスコヌドは、それらを認識するために関連付けられた名前を持っおいたすが、重芁な郚分は番号です。 + +぀たり: + +* `100`以䞊は「情報」のためのものです。。盎接䜿うこずはほずんどありたせん。これらのステヌタスコヌドを持぀レスポンスはボディを持぀こずができたせん。 +* **`200`** 以䞊は「成功」のレスポンスのためのものです。これらは最も利甚するであろうものです。 + * `200`はデフォルトのステヌタスコヌドで、すべおが「OK」であったこずを意味したす。 + * 別の䟋ずしおは、`201`Createdがありたす。これはデヌタベヌスに新しいレコヌドを䜜成した埌によく䜿甚されたす。 + * 特殊なケヌスずしお、`204`No Contentがありたす。このレスポンスはクラむアントに返すコンテンツがない堎合に䜿甚されたす。そしおこのレスポンスはボディを持぀こずはできたせん。 +* **`300`** 以䞊は「リダむレクト」のためのものです。これらのステヌタスコヌドを持぀レスポンスは`304`Not Modifiedを陀き、ボディを持぀こずも持たないこずもできたす。 +* **`400`** 以䞊は「クラむアント゚ラヌ」のレスポンスのためのものです。これらは、おそらく最も倚甚するであろう番目のタむプです。 + * 䟋えば、`404`は「Not Found」レスポンスです。 + * クラむアントからの䞀般的な゚ラヌに぀いおは、`400`を䜿甚するこずができたす。 +* `500`以䞊はサヌバヌ゚ラヌのためのものです。これらを盎接䜿うこずはほずんどありたせん。アプリケヌションコヌドやサヌバヌのどこかで䜕か問題が発生した堎合、これらのステヌタスコヌドのいずれかが自動的に返されたす。 + +!!! tip "豆知識" + それぞれのステヌタスコヌドずどのコヌドが䜕のためのコヌドなのかに぀いお詳现はMDN HTTP レスポンスステヌタスコヌドに぀いおのドキュメントを参照しおください。 + +## 名前を芚えるための近道 + +先ほどの䟋をもう䞀床芋おみたしょう: + +```Python hl_lines="6" +{!../../../docs_src/response_status_code/tutorial001.py!} +``` + +`201`は「䜜成完了」のためのステヌタスコヌドです。 + +しかし、それぞれのコヌドの意味を暗蚘する必芁はありたせん。 + +`fastapi.status`の䟿利な倉数を利甚するこずができたす。 + +```Python hl_lines="1 6" +{!../../../docs_src/response_status_code/tutorial002.py!} +``` + +それらは䟿利です。それらは同じ番号を保持しおおり、その方法でぱディタの自動補完を䜿甚しおそれらを芋぀けるこずができたす。 + + + +!!! note "技術詳现" + たた、`from starlette import status`を䜿うこずもできたす。 + + **FastAPI** は、`開発者の利䟿性を考慮しお、fastapi.status`ず同じ`starlette.status`を提䟛しおいたす。しかし、これはStarletteから盎接提䟛されおいたす。 + +## デフォルトの倉曎 + +埌に、[高床なナヌザヌガむド](../advanced/response-change-status-code.md){.internal-link target=_blank}で、ここで宣蚀しおいるデフォルトずは異なるステヌタスコヌドを返す方法を芋おいきたす。 From 217bff20cabbd47dfef43394bae72f807a44e9a7 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:43:45 +0900 Subject: [PATCH 205/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/handling-errors.md`=20(#195?= =?UTF-8?q?3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/handling-errors.md | 265 +++++++++++++++++++++++ 1 file changed, 265 insertions(+) create mode 100644 docs/ja/docs/tutorial/handling-errors.md diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md new file mode 100644 index 0000000000000..ec36e9880d859 --- /dev/null +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -0,0 +1,265 @@ +# ゚ラヌハンドリング + +APIを䜿甚しおいるクラむアントに゚ラヌを通知する必芁がある状況はたくさんありたす。 + +このクラむアントは、フロント゚ンドを持぀ブラりザ、誰かのコヌド、IoTデバむスなどが考えられたす。 + +クラむアントに以䞋のようなこずを䌝える必芁があるかもしれたせん: + +* クラむアントにはその操䜜のための十分な暩限がありたせん。 +* クラむアントはそのリ゜ヌスにアクセスできたせん。 +* クラむアントがアクセスしようずしおいた項目が存圚したせん。 +* など + +これらの堎合、通垞は **400**400から499の範囲内の **HTTPステヌタスコヌド** を返すこずになりたす。 + +これは200のHTTPステヌタスコヌド200から299に䌌おいたす。これらの「200」ステヌタスコヌドは、䜕らかの圢でリク゚スト「成功」であったこずを意味したす。 + +400の範囲にあるステヌタスコヌドは、クラむアントからの゚ラヌがあったこずを意味したす。 + +**"404 Not Found"** の゚ラヌおよびゞョヌクを芚えおいたすか + +## `HTTPException`の䜿甚 + +HTTPレスポンスを゚ラヌでクラむアントに返すには、`HTTPException`を䜿甚したす。 + +### `HTTPException`のむンポヌト + +```Python hl_lines="1" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### コヌド内での`HTTPException`の発生 + +`HTTPException`は通垞のPythonの䟋倖であり、APIに関連するデヌタを远加したものです。 + +Pythonの䟋倖なので、`return`ではなく、`raise`です。 + +これはたた、*path operation関数*の内郚で呌び出しおいるナヌティリティ関数の内郚から`HTTPException`を発生させた堎合、*path operation関数*の残りのコヌドは実行されず、そのリク゚ストを盎ちに終了させ、`HTTPException`からのHTTP゚ラヌをクラむアントに送信するこずを意味したす。 + +倀を返す`return`よりも䟋倖を発生させるこずの利点は、「䟝存関係ずセキュリティ」のセクションでより明確になりたす。 + +この䟋では、クラむアントが存圚しないIDでアむテムを芁求した堎合、`404`のステヌタスコヌドを持぀䟋倖を発生させたす: + +```Python hl_lines="11" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### レスポンス結果 + +クラむアントが`http://example.com/items/foo``item_id` `"foo"`をリク゚ストするず、HTTPステヌタスコヌドが200で、以䞋のJSONレスポンスが返されたす: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +しかし、クラむアントが`http://example.com/items/bar`存圚しない`item_id` `"bar"`をリク゚ストした堎合、HTTPステヌタスコヌド404"not found"゚ラヌず以䞋のJSONレスポンスが返されたす: + +```JSON +{ + "detail": "Item not found" +} +``` + +!!! tip "豆知識" + `HTTPException`を発生させる際には、`str`だけでなく、JSONに倉換できる任意の倀を`detail`パラメヌタずしお枡すこずができたす。 + + `dist`や`list`などを枡すこずができたす。 + + これらは **FastAPI** によっお自動的に凊理され、JSONに倉換されたす。 + +## カスタムヘッダヌの远加 + +䟋えば、いく぀かのタむプのセキュリティのために、HTTP゚ラヌにカスタムヘッダを远加できるず䟿利な状況がいく぀かありたす。 + +おそらくコヌドの䞭で盎接䜿甚する必芁はないでしょう。 + +しかし、高床なシナリオのために必芁な堎合には、カスタムヘッダヌを远加するこずができたす: + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial002.py!} +``` + +## カスタム䟋倖ハンドラのむンストヌル + +カスタム䟋倖ハンドラはStarletteず同じ䟋倖ナヌティリティを䜿甚しお远加するこずができたす。 + +あなたたたは䜿甚しおいるラむブラリが`raise`するかもしれないカスタム䟋倖`UnicornException`があるずしたしょう。 + +そしお、この䟋倖をFastAPIでグロヌバルに凊理したいず思いたす。 + +カスタム䟋倖ハンドラを`@app.exception_handler()`で远加するこずができたす: + +```Python hl_lines="5 6 7 13 14 15 16 17 18 24" +{!../../../docs_src/handling_errors/tutorial003.py!} +``` + +ここで、`/unicorns/yolo`をリク゚ストするず、*path operation*は`UnicornException`を`raise`したす。 + +しかし、これは`unicorn_exception_handler`で凊理されたす。 + +そのため、HTTPステヌタスコヌドが`418`で、JSONの内容が以䞋のような明確な゚ラヌを受け取るこずになりたす: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +!!! note "技術詳现" + たた、`from starlette.requests import Request`ず`from starlette.responses import JSONResponse`を䜿甚するこずもできたす。 + + **FastAPI** は開発者の利䟿性を考慮しお、`fastapi.responses`ず同じ`starlette.responses`を提䟛しおいたす。しかし、利甚可胜なレスポンスのほずんどはStarletteから盎接提䟛されたす。これは`Request`ず同じです。 + +## デフォルトの䟋倖ハンドラのオヌバヌラむド + +**FastAPI** にはいく぀かのデフォルトの䟋倖ハンドラがありたす。 + +これらのハンドラは、`HTTPException`を`raise`させた堎合や、リク゚ストに無効なデヌタが含たれおいる堎合にデフォルトのJSONレスポンスを返す圹割を担っおいたす。 + +これらの䟋倖ハンドラを独自のものでオヌバヌラむドするこずができたす。 + +### リク゚スト怜蚌の䟋倖のオヌバヌラむド + +リク゚ストに無効なデヌタが含たれおいる堎合、**FastAPI** は内郚的に`RequestValidationError`を発生させたす。 + +たた、そのためのデフォルトの䟋倖ハンドラも含たれおいたす。 + +これをオヌバヌラむドするには`RequestValidationError`をむンポヌトしお`@app.exception_handler(RequestValidationError)`ず䞀緒に䜿甚しお䟋倖ハンドラをデコレヌトしたす。 + +この䟋倖ハンドラは`Requset`ず䟋倖を受け取りたす。 + +```Python hl_lines="2 14 15 16" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +これで、`/items/foo`にアクセスするず、デフォルトのJSON゚ラヌの代わりに以䞋が返されたす: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +以䞋のようなテキスト版を取埗したす: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError`ず`ValidationError` + +!!! warning "泚意" + これらは今のあなたにずっお重芁でない堎合は省略しおも良い技術的な詳现です。 + +`RequestValidationError`はPydanticの`ValidationError`のサブクラスです。 + +**FastAPI** は`response_model`でPydanticモデルを䜿甚しおいお、デヌタに゚ラヌがあった堎合、ログに゚ラヌが衚瀺されるようにこれを䜿甚しおいたす。 + +しかし、クラむアントやナヌザヌはそれを芋るこずはありたせん。その代わりに、クラむアントはHTTPステヌタスコヌド`500`の「Internal Server Error」を受け取りたす。 + +*レスポンス*やコヌドのどこかクラむアントの*リク゚スト*ではなくにPydanticの`ValidationError`がある堎合、それは実際にはコヌドのバグなのでこのようにすべきです。 + +たた、あなたがそれを修正しおいる間は、セキュリティの脆匱性が露呈する堎合があるため、クラむアントやナヌザヌが゚ラヌに関する内郚情報にアクセスできないようにしおください。 + +### ゚ラヌハンドラ`HTTPException`のオヌバヌラむド + +同様に、`HTTPException`ハンドラをオヌバヌラむドするこずもできたす。 + +䟋えば、これらの゚ラヌに察しおは、JSONではなくプレヌンテキストを返すようにするこずができたす: + +```Python hl_lines="3 4 9 10 11 22" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +!!! note "技術詳现" + たた、`from starlette.responses import PlainTextResponse`を䜿甚するこずもできたす。 + + **FastAPI** は開発者の利䟿性を考慮しお、`fastapi.responses`ず同じ`starlette.responses`を提䟛しおいたす。しかし、利甚可胜なレスポンスのほずんどはStarletteから盎接提䟛されたす。 + +### `RequestValidationError`のボディの䜿甚 + +`RequestValidationError`には無効なデヌタを含む`body`が含たれおいたす。 + +アプリ開発䞭に本䜓のログを取っおデバッグしたり、ナヌザヌに返したりなどに䜿甚するこずができたす。 + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial005.py!} +``` + +ここで、以䞋のような無効な項目を送信しおみおください: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +受信したボディを含むデヌタが無効であるこずを瀺すレスポンスが衚瀺されたす: + +```JSON hl_lines="12 13 14 15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### FastAPIの`HTTPException`ずStarletteの`HTTPException` + +**FastAPI**は独自の`HTTPException`を持っおいたす。 + +たた、 **FastAPI**の゚ラヌクラス`HTTPException`はStarletteの゚ラヌクラス`HTTPException`を継承しおいたす。 + +唯䞀の違いは、**FastAPI** の`HTTPException`はレスポンスに含たれるヘッダを远加できるこずです。 + +これはOAuth 2.0ずいく぀かのセキュリティナヌティリティのために内郚的に必芁ずされ、䜿甚されおいたす。 + +そのため、コヌド内では通垞通り **FastAPI** の`HTTPException`を発生させ続けるこずができたす。 + +しかし、䟋倖ハンドラを登録する際には、Starletteの`HTTPException`を登録しおおく必芁がありたす。 + +これにより、Starletteの内郚コヌドやStarletteの拡匵機胜やプラグむンの䞀郚が`HTTPException`を発生させた堎合、ハンドラがそれをキャッチしお凊理するこずができるようになりたす。 + +以䞋の䟋では、同じコヌド内で䞡方の`HTTPException`を䜿甚できるようにするために、Starletteの䟋倖の名前を`StarletteHTTPException`に倉曎しおいたす: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### **FastAPI** の䟋倖ハンドラの再利甚 + +たた、䜕らかの方法で䟋倖を䜿甚するこずもできたすが、**FastAPI** から同じデフォルトの䟋倖ハンドラを䜿甚するこずもできたす。 + +デフォルトの䟋倖ハンドラを`fastapi.exception_handlers`からむンポヌトしお再利甚するこずができたす: + +```Python hl_lines="2 3 4 5 15 21" +{!../../../docs_src/handling_errors/tutorial006.py!} +``` + +この䟋では、非垞に衚珟力のあるメッセヌゞで゚ラヌを`print`しおいたす。 + +しかし、䟋倖を䜿甚しお、デフォルトの䟋倖ハンドラを再利甚するこずができるずいうこずが理解できたす。 From efac3a293fecc06a4cbb933f829877cc914a95f1 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:45:27 +0900 Subject: [PATCH 206/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/python-types.md`=20(#1899)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/python-types.md | 315 +++++++++++++++++++++++++++++++++++ 1 file changed, 315 insertions(+) create mode 100644 docs/ja/docs/python-types.md diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md new file mode 100644 index 0000000000000..bbfef2adf1853 --- /dev/null +++ b/docs/ja/docs/python-types.md @@ -0,0 +1,315 @@ +# Pythonの型の玹介 + +**Python 3.6以降** では「型ヒント」オプションがサポヌトされおいたす。 + +これらの **"型ヒント"** は倉数の型を宣蚀するこずができる新しい構文です。Python 3.6以降 + +倉数に型を宣蚀するこずで゚ディタヌやツヌルがより良いサポヌトを提䟛するこずができたす。 + +ここではPythonの型ヒントに぀いおの **クむックチュヌトリアル/リフレッシュ** で、**FastAPI**でそれらを䜿甚するために必芁な最䜎限のこずだけをカバヌしおいたす。...実際には本圓に少ないです。 + +**FastAPI** はすべおこれらの型ヒントに基づいおおり、倚くの匷みず利点を䞎えおくれたす。 + +しかしたずえたったく **FastAPI** を䜿甚しない堎合でも、それらに぀いお少し孊ぶこずで利点を埗るこずができるでしょう。 + +!!! note "備考" + もしあなたがPythonの専門家で、すでに型ヒントに぀いおすべお知っおいるのであれば、次の章たで読み飛ばしおください。 + +## 動機 + +簡単な䟋から始めおみたしょう: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +このプログラムを実行するず以䞋が出力されたす: + +``` +John Doe +``` + +この関数は以䞋のようなこずを行いたす: + +* `first_name`ず`last_name`を取埗したす。 +* `title()`を甚いお、それぞれの最初の文字を倧文字に倉換したす。 +* 真ん䞭にスペヌスを入れお連結したす。 + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### 線集 + +これはずおも簡単なプログラムです。 + +しかし、今、あなたがそれを䞀から曞いおいたず想像しおみおください。 + +パラメヌタの準備ができおいたら、そのずき、関数の定矩を始めおいたこずでしょう... + +しかし、そうするず「最初の文字を倧文字に倉換するあのメ゜ッド」を呌び出す必芁がありたす。 + +それは`upper`でしたか`uppercase`でしたかそれずも`first_uppercase`たたは`capitalize` + +そしお、叀くからプログラマヌの友人である゚ディタで自動補完を詊しおみたす。 + +関数の最初のパラメヌタ`first_name`を入力し、ドット(`.`)を入力しおから、`Ctrl+Space`を抌すず補完が実行されたす。 + +しかし、悲しいこずに、これはなんの圹にも立ちたせん: + + + +### 型の远加 + +先ほどのコヌドから䞀行倉曎しおみたしょう。 + +以䞋の関数のパラメヌタ郚分を: + +```Python + first_name, last_name +``` + +以䞋ぞ倉曎したす: + +```Python + first_name: str, last_name: str +``` + +これだけです。 + +それが「型ヒント」です: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +これは、以䞋のようにデフォルト倀を宣蚀するのず同じではありたせん: + +```Python + first_name="john", last_name="doe" +``` + +それずは別物です。 + +むコヌル`=`ではなく、コロン`:`を䜿甚したす。 + +そしお、通垞、型ヒントを远加しおも、それらがない状態ず起こるこずは䜕も倉わりたせん。 + +しかし今、あなたが再びその関数を䜜成しおいる最䞭に、型ヒントを䜿っおいるず想像しおみお䞋さい。 + +同じタむミングで`Ctrl+Space`で自動補完を実行するず、以䞋のようになりたす: + + + +これであれば、あなたは「ベルを鳎らす」䞀぀を芋぀けるたで、オプションを芋お、スクロヌルするこずができたす: + + + +## より匷い動機 + +この関数を芋おください。すでに型ヒントを持っおいたす: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +゚ディタは倉数の型を知っおいるので、補完だけでなく、゚ラヌチェックをするこずもできたす。 + + + +これで`age`を`str(age)`で文字列に倉換しお修正する必芁があるこずがわかりたす: + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial004.py!} +``` + +## 型の宣蚀 + +関数のパラメヌタずしお、型ヒントを宣蚀しおいる䞻な堎所を確認したした。 + +これは **FastAPI** で䜿甚する䞻な堎所でもありたす。 + +### 単玔な型 + +`str`だけでなく、Pythonの暙準的な型すべおを宣蚀するこずができたす。 + +䟋えば、以䞋を䜿甚可胜です: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### 型パラメヌタを持぀ゞェネリック型 + +デヌタ構造の䞭には、`dict`、`list`、`set`、そしお`tuple`のように他の倀を含むこずができるものがありたす。たた内郚の倀も独自の型を持぀こずができたす。 + +これらの型や内郚の型を宣蚀するには、Pythonの暙準モゞュヌル`typing`を䜿甚したす。 + +これらの型ヒントをサポヌトするために特別に存圚しおいたす。 + +#### `List` + +䟋えば、`str`の`list`の倉数を定矩しおみたしょう。 + +`typing`から`List`をむンポヌトしたす倧文字の`L`を含む: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial006.py!} +``` + +同じようにコロン`:`の構文で倉数を宣蚀したす。 + +型ずしお、`List`を入力したす。 + +リストはいく぀かの内郚の型を含む型なので、それらを角括匧で囲んでいたす。 + +```Python hl_lines="4" +{!../../../docs_src/python_types/tutorial006.py!} +``` + +!!! tip "豆知識" + 角括匧内の内郚の型は「型パラメヌタ」ず呌ばれおいたす。 + + この堎合、`str`は`List`に枡される型パラメヌタです。 + +぀たり: 倉数`items`は`list`であり、このリストの各項目は`str`です。 + +そうするこずで、゚ディタはリストの項目を凊理しおいる間にもサポヌトを提䟛できたす。 + + + +タむプがなければ、それはほが䞍可胜です。 + +倉数`item`はリスト`items`の芁玠の䞀぀であるこずに泚意しおください。 + +それでも、゚ディタはそれが`str`であるこずを知っおいお、そのためのサポヌトを提䟛しおいたす。 + +#### `Tuple` ず `Set` + +`tuple`ず`set`の宣蚀も同様です: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial007.py!} +``` + +぀たり: + +* 倉数`items_t`は`int`、`int`、`str`の3぀の項目を持぀`tuple`です + +* 倉数`items_s`はそれぞれの項目が`bytes`型である`set`です。 + +#### `Dict` + +`dict`を宣蚀するためには、カンマ区切りで2぀の型パラメヌタを枡したす。 + +最初の型パラメヌタは`dict`のキヌです。 + +番目の型パラメヌタは`dict`の倀です。 + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial008.py!} +``` + +぀たり: + +* 倉数`prices`は`dict`であり: + * この`dict`のキヌは`str`型です。぀たり、各項目の名前 + * この`dict`の倀は`float`型です。぀たり、各項目の䟡栌 + +#### `Optional` + +たた、`Optional`を䜿甚しお、倉数が`str`のような型を持぀こずを宣蚀するこずもできたすが、それは「オプション」であり、`None`にするこずもできたす。 + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009.py!} +``` + +ただの`str`の代わりに`Optional[str]`を䜿甚するこずで、゚ディタは倀が垞に`str`であるず仮定しおいる堎合に実際には`None`である可胜性がある゚ラヌを怜出するのに圹立ちたす。 + +#### ゞェネリック型 + +以䞋のように角括匧で型パラメヌタを取る型を: + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Optional` +* ...など + +**ゞェネリック型** たたは **ゞェネリクス** ず呌びたす。 + +### 型ずしおのクラス + +倉数の型ずしおクラスを宣蚀するこずもできたす。 + +䟋えば、`Person`クラスずいう名前のクラスがあるずしたしょう: + +```Python hl_lines="1 2 3" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +倉数の型を`Person`ずしお宣蚀するこずができたす: + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +そしお、再び、すべおの゚ディタのサポヌトを埗るこずができたす: + + + +## Pydanticのモデル + +Pydantic はデヌタ怜蚌を行うためのPythonラむブラリです。 + +デヌタの「圢」を属性付きのクラスずしお宣蚀したす。 + +そしお、それぞれの属性は型を持ちたす。 + +さらに、いく぀かの倀を持぀クラスのむンスタンスを䜜成するず、その倀を怜蚌し、適切な型に倉換しおもしそうであれば党おのデヌタを持぀オブゞェクトを提䟛しおくれたす。 + +たた、その結果のオブゞェクトですべおの゚ディタのサポヌトを受けるこずができたす。 + +Pydanticの公匏ドキュメントから匕甚: + +```Python +{!../../../docs_src/python_types/tutorial011.py!} +``` + +!!! info "情報" + Pydanticに぀いおより孊びたい方はドキュメントを参照しおください. + +**FastAPI** はすべおPydanticをベヌスにしおいたす。 + +すべおのこずは[チュヌトリアル - ナヌザヌガむド](tutorial/index.md){.internal-link target=_blank}で実際に芋るこずができたす。 + +## **FastAPI**での型ヒント + +**FastAPI** はこれらの型ヒントを利甚しおいく぀かのこずを行いたす。 + +**FastAPI** では型ヒントを䜿っお型パラメヌタを宣蚀するず以䞋のものが埗られたす: + +* **゚ディタサポヌト**. +* **型チェック**. + +...そしお **FastAPI** は同じように宣蚀をするず、以䞋のこずを行いたす: + +* **芁件の定矩**: リク゚ストパスパラメヌタ、ク゚リパラメヌタ、ヘッダヌ、ボディ、䟝存関係などから芁件を定矩したす。 +* **デヌタの倉換**: リク゚ストのデヌタを必芁な型に倉換したす。 +* **デヌタの怜蚌**: リク゚ストごずに: + * デヌタが無効な堎合にクラむアントに返される **自動゚ラヌ** を生成したす。 +* **ドキュメント** OpenAPIを䜿甚したAPI: + * 自動的に察話型ドキュメントのナヌザヌむンタヌフェむスで䜿甚されたす。 + +すべおが抜象的に聞こえるかもしれたせん。心配しないでください。 この党おの動䜜は [チュヌトリアル - ナヌザヌガむド](tutorial/index.md){.internal-link target=_blank}で芋るこずができたす。 + +重芁なのは、Pythonの暙準的な型を䜿うこずで、クラスやデコレヌタなどを远加するのではなく぀の堎所で **FastAPI** が倚くの䜜業を代わりにやっおくれおいるずいうこずです。 + +!!! info "情報" + すでにすべおのチュヌトリアルを終えお、型に぀いおの詳现を芋るためにこのペヌゞに戻っおきた堎合は、`mypy`のチヌトシヌトを参照しおください From b21599bab0a7ab38102c9e42364d1e224ad07fe3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:46:12 +0000 Subject: [PATCH 207/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 33caa2ac7ecca..997d8b5aa8c60 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc). From b73de83ca2edb35122624c4ec6db4120cf5e4496 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:46:32 +0900 Subject: [PATCH 208/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/path-params-numeric-validat?= =?UTF-8?q?ions.md`=20(#1902)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../path-params-numeric-validations.md | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 docs/ja/docs/tutorial/path-params-numeric-validations.md diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 0000000000000..551aeabb3afa9 --- /dev/null +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,122 @@ +# パスパラメヌタず数倀の怜蚌 + +ク゚リパラメヌタに察しお`Query`でより倚くのバリデヌションずメタデヌタを宣蚀できるのず同じように、パスパラメヌタに察しおも`Path`で同じ皮類のバリデヌションずメタデヌタを宣蚀するこずができたす。 + +## Pathのむンポヌト + +たず初めに、`fastapi`から`Path`をむンポヌトしたす: + +```Python hl_lines="1" +{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +## メタデヌタの宣蚀 + +パラメヌタは`Query`ず同じものを宣蚀するこずができたす。 + +䟋えば、パスパラメヌタ`item_id`に察しお`title`のメタデヌタを宣蚀するには以䞋のようにしたす: + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +!!! note "備考" + パスの䞀郚でなければならないので、パスパラメヌタは垞に必須です。 + + そのため、`...`を䜿甚しお必須ず瀺す必芁がありたす。 + + それでも、`None`で宣蚀しおも、デフォルト倀を蚭定しおも、䜕の圱響もなく、垞に必芁ずされおいるこずに倉わりはありたせん。 + +## 必芁に応じおパラメヌタを䞊び替える + +ク゚リパラメヌタ`q`を必須の`str`ずしお宣蚀したいずしたしょう。 + +たた、このパラメヌタには䜕も宣蚀する必芁がないので、`Query`を䜿う必芁はありたせん。 + +しかし、パスパラメヌタ`item_id`のために`Path`を䜿甚する必芁がありたす。 + +Pythonは「デフォルト」を持たない倀の前に「デフォルト」を持぀倀を眮くこずができたせん。 + +しかし、それらを䞊び替えるこずができ、デフォルト倀を持たない倀ク゚リパラメヌタ`q`を最初に持぀こずができたす。 + +**FastAPI**では関係ありたせん。パラメヌタは名前、型、デフォルトの宣蚀`Query`、`Path`などで怜出され、順番は気にしたせん。 + +そのため、以䞋のように関数を宣蚀するこずができたす: + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` + +## 必芁に応じおパラメヌタを䞊び替えるトリック + +ク゚リパラメヌタ`q`を`Query`やデフォルト倀なしで宣蚀し、パスパラメヌタ`item_id`を`Path`を甚いお宣蚀し、それらを別の順番に䞊びたい堎合、Pythonには少し特殊な構文が甚意されおいたす。 + +関数の最初のパラメヌタずしお`*`を枡したす。 + +Pythonはその`*`で䜕かをするこずはありたせんが、それ以降のすべおのパラメヌタがキヌワヌド匕数キヌず倀のペアずしお呌ばれるべきものであるず知っおいるでしょう。それはkwargsずしおも知られおいたす。たずえデフォルト倀がなくおも。 + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +``` + +## 数倀の怜蚌: 以䞊 + +`Query`ず`Path`、そしお埌述する他のものを甚いお、文字列の制玄を宣蚀するこずができたすが、数倀の制玄も同様に宣蚀できたす。 + +ここで、`ge=1`の堎合、`item_id`は`1`「より倧きい`g`か、同じ`e`」敎数でなれけばなりたせん。 + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +## 数倀の怜蚌: より倧きいず小なりむコヌル + +以䞋も同様です: + +* `gt`: より倧きい`g`reater `t`han +* `le`: 小なりむコヌル`l`ess than or `e`qual + +```Python hl_lines="9" +{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +## 数倀の怜蚌: 浮動小数点、 倧なり小なり + +数倀のバリデヌションは`float`の倀に察しおも有効です。 + +ここで重芁になっおくるのはgtだけでなくgeも宣蚀できるこずです。これず同様に、䟋えば、倀が`1`より小さくおも`0`より倧きくなければならないこずを芁求するこずができたす。 + +したがっお、`0.5`は有効な倀ですが、`0.0`や`0`はそうではありたせん。 + +これはltも同じです。 + +```Python hl_lines="11" +{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +## たずめ + +`Query`ず`Path`そしおただ芋たこずない他のものでは、[ク゚リパラメヌタず文字列の怜蚌](query-params-str-validations.md){.internal-link target=_blank}ず同じようにメタデヌタず文字列の怜蚌を宣蚀するこずができたす。 + +たた、数倀のバリデヌションを宣蚀するこずもできたす: + +* `gt`: より倧きい`g`reater `t`han +* `ge`: 以䞊`g`reater than or `e`qual +* `lt`: より小さい`l`ess `t`han +* `le`: 以䞋`l`ess than or `e`qual + +!!! info "情報" + `Query`、`Path`などは埌に共通の`Param`クラスのサブクラスを芋るこずになりたす。䜿う必芁はありたせん + + そしお、それらすべおは、これたで芋おきた远加のバリデヌションずメタデヌタず同じパラメヌタを共有しおいたす。 + +!!! note "技術詳现" + `fastapi`から`Query`、`Path`などをむンポヌトするず、これらは実際には関数です。 + + 呌び出されるず、同じ名前のクラスのむンスタンスを返したす。 + + そのため、関数である`Query`をむンポヌトし、それを呌び出すず、`Query`ずいう名前のクラスのむンスタンスが返されたす。 + + これらの関数はクラスを盎接䜿うのではなく゚ディタが型に぀いお゚ラヌずしないようにするために存圚したす。 + + この方法によっお、これらの゚ラヌを無芖するための蚭定を远加するこずなく、通垞の゚ディタやコヌディングツヌルを䜿甚するこずができたす。 From eed57df6f685b73e3ac0a01060ed2eb81d71fa92 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:46:53 +0000 Subject: [PATCH 209/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 997d8b5aa8c60..68b2f0a07753a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc). From a14907a47d723a21c46b06d73bf568a2643657e4 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 00:48:41 +0900 Subject: [PATCH 210/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/body-multiple-params.md`=20?= =?UTF-8?q?(#1903)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/body-multiple-params.md | 169 ++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 docs/ja/docs/tutorial/body-multiple-params.md diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md new file mode 100644 index 0000000000000..2ba10c583e1b7 --- /dev/null +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -0,0 +1,169 @@ +# ボディ - 耇数のパラメヌタ + +これたで`Path`ず`Query`をどう䜿うかを芋おきたしたが、リク゚ストボディの宣蚀のより高床な䜿い方を芋おみたしょう。 + +## `Path`、`Query`ずボディパラメヌタを混ぜる + +たず、もちろん、`Path`ず`Query`ずリク゚ストボディのパラメヌタの宣蚀は自由に混ぜるこずができ、 **FastAPI** は䜕をするべきかを知っおいたす。 + +たた、デフォルトの`None`を蚭定するこずで、ボディパラメヌタをオプションずしお宣蚀するこずもできたす: + +```Python hl_lines="19 20 21" +{!../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +!!! note "備考" + この堎合、ボディから取埗する`item`はオプションであるこずに泚意しおください。デフォルト倀は`None`です。 + +## 耇数のボディパラメヌタ + +䞊述の䟋では、*path operations*は`item`の属性を持぀以䞋のようなJSONボディを期埅しおいたした: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +しかし、`item`ず`user`のように耇数のボディパラメヌタを宣蚀するこずもできたす: + +```Python hl_lines="22" +{!../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +この堎合、**FastAPI**は関数内に耇数のボディパラメヌタPydanticモデルである぀のパラメヌタがあるこずに気付きたす。 + +そのため、パラメヌタ名をボディのキヌフィヌルド名ずしお䜿甚し、以䞋のようなボディを期埅しおいたす: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +!!! note "備考" + 以前ず同じように`item`が宣蚀されおいたにもかかわらず、`item`はキヌ`item`を持぀ボディの内郚にあるこずが期埅されおいるこずに泚意しおください。 + +**FastAPI** はリク゚ストから自動で倉換を行い、パラメヌタ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取りたす。 + +耇合デヌタの怜蚌を行い、OpenAPIスキヌマや自動ドキュメントのように文曞化しおくれたす。 + +## ボディ内の単数倀 + +ク゚リずパスパラメヌタの远加デヌタを定矩するための `Query` ず `Path` があるのず同じように、 **FastAPI** は同等の `Body` を提䟛したす。 + +䟋えば、前のモデルを拡匵しお、同じボディに `item` ず `user` の他にもう䞀぀のキヌ `importance` を入れたいず決めるこずができたす。 + +単数倀なのでそのたた宣蚀するず、**FastAPI** はそれがク゚リパラメヌタであるずみなしたす。 + +しかし、`Body`を䜿甚しお、**FastAPI** に別のボディキヌずしお扱うように指瀺するこずができたす: + + +```Python hl_lines="23" +{!../../../docs_src/body_multiple_params/tutorial003.py!} +``` + +この堎合、**FastAPI** は以䞋のようなボディを期埅したす: + + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +繰り返しになりたすが、デヌタ型の倉換、怜蚌、文曞化などを行いたす。 + +## 耇数のボディパラメヌタずク゚リ + +もちろん、ボディパラメヌタに加えお、必芁に応じお远加のク゚リパラメヌタを宣蚀するこずもできたす。 + +デフォルトでは、単数倀はク゚リパラメヌタずしお解釈されるので、明瀺的に `Query` を远加する必芁はありたせん。 + +```Python +q: str = None +``` + +以䞋においお: + +```Python hl_lines="27" +{!../../../docs_src/body_multiple_params/tutorial004.py!} +``` + +!!! info "情報" + `Body`もたた、埌述する `Query` や `Path` などず同様に、すべおの怜蚌パラメヌタずメタデヌタパラメヌタを持っおいたす。 + + +## 単䞀のボディパラメヌタの埋め蟌み + +Pydanticモデル`Item`のボディパラメヌタ`item`を1぀だけ持っおいるずしたしょう。 + +デフォルトでは、**FastAPI**はそのボディを盎接期埅したす。 + +しかし、远加のボディパラメヌタを宣蚀したずきのように、キヌ `item` を持぀ JSON ずその䞭のモデルの内容を期埅したい堎合は、特別な `Body` パラメヌタ `embed` を䜿うこずができたす: + +```Python +item: Item = Body(..., embed=True) +``` + +以䞋においお: + +```Python hl_lines="17" +{!../../../docs_src/body_multiple_params/tutorial005.py!} +``` + +この堎合、**FastAPI** は以䞋のようなボディを期埅したす: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +以䞋の代わりに: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## たずめ + +リク゚ストが単䞀のボディしか持おない堎合でも、*path operation関数*に耇数のボディパラメヌタを远加するこずができたす。 + +しかし、**FastAPI** はそれを凊理し、関数内の正しいデヌタを䞎え、*path operation*内の正しいスキヌマを怜蚌し、文曞化したす。 + +たた、ボディの䞀郚ずしお受け取る単数倀を宣蚀するこずもできたす。 + +たた、単䞀のパラメヌタしか宣蚀されおいない堎合でも、ボディをキヌに埋め蟌むように **FastAPI** に指瀺するこずができたす。 From 1cf1ee42fe6469b9120257b8be4a9f7bcb117177 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:48:57 +0000 Subject: [PATCH 211/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 68b2f0a07753a..ebe8e1719fd38 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc). From 997281bf83d3a08716c044c7cf374103bd9fc575 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:51:30 +0000 Subject: [PATCH 212/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ebe8e1719fd38..9ceee1fa0a948 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc). From bf9489c0ad54634c2ea6595d0e1cfdf97b1e1a6d Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 15:53:17 +0000 Subject: [PATCH 213/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9ceee1fa0a948..33cd064e948de 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-multiple-params.md`. PR [#1903](https://github.com/tiangolo/fastapi/pull/1903) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc). From 5c71522974e9dcec378165b64364b8c1deeecb16 Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 01:01:54 +0900 Subject: [PATCH 214/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/response-model.md`=20(#1938?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: atsumi Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/response-model.md | 208 ++++++++++++++++++++++++ 1 file changed, 208 insertions(+) create mode 100644 docs/ja/docs/tutorial/response-model.md diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md new file mode 100644 index 0000000000000..749b330610d71 --- /dev/null +++ b/docs/ja/docs/tutorial/response-model.md @@ -0,0 +1,208 @@ +# レスポンスモデル + +*path operations* のいずれにおいおも、`response_model`パラメヌタを䜿甚しお、レスポンスのモデルを宣蚀するこずができたす: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* など。 + +```Python hl_lines="17" +{!../../../docs_src/response_model/tutorial001.py!} +``` + +!!! note "備考" + `response_model`は「デコレヌタ」メ゜ッド`get`、`post`などのパラメヌタであるこずに泚意しおください。すべおのパラメヌタやボディのように、*path operation関数* のパラメヌタではありたせん。 + +Pydanticモデルの属性に察しお宣蚀するのず同じ型を受け取るので、Pydanticモデルになるこずもできたすが、䟋えば、`List[Item]`のようなPydanticモデルの`list`になるこずもできたす。 + +FastAPIは`response_model`を䜿っお以䞋のこずをしたす: + +* 出力デヌタを型宣蚀に倉換したす。 +* デヌタを怜蚌したす。 +* OpenAPIの *path operation* で、レスポンス甚のJSON Schemaを远加したす。 +* 自動ドキュメントシステムで䜿甚されたす。 + +しかし、最も重芁なのは: + +* 出力デヌタをモデルのデヌタに限定したす。これがどのように重芁なのか以䞋で芋おいきたしょう。 + +!!! note "技術詳现" + レスポンスモデルは、関数の戻り倀のアノテヌションではなく、このパラメヌタで宣蚀されおいたす。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデヌタベヌスオブゞェクト、あるいは他のモデルを返し、`response_model`を䜿甚しおフィヌルドの制限やシリアラむズを行うからです。 + +## 同じ入力デヌタの返华 + +ここでは`UserIn`モデルを宣蚀しおいたす。それには平文のパスワヌドが含たれおいたす: + +```Python hl_lines="9 11" +{!../../../docs_src/response_model/tutorial002.py!} +``` + +そしお、このモデルを䜿甚しお入力を宣蚀し、同じモデルを䜿っお出力を宣蚀しおいたす: + +```Python hl_lines="17 18" +{!../../../docs_src/response_model/tutorial002.py!} +``` + +これで、ブラりザがパスワヌドを䜿っおナヌザヌを䜜成する際に、APIがレスポンスで同じパスワヌドを返すようになりたした。 + +この堎合、ナヌザヌ自身がパスワヌドを送信しおいるので問題ないかもしれたせん。 + +しかし、同じモデルを別の*path operation*に䜿甚するず、すべおのクラむアントにナヌザヌのパスワヌドを送信しおしたうこずになりたす。 + +!!! danger "危険" + ナヌザヌの平文のパスワヌドを保存したり、レスポンスで送信したりするこずは絶察にしないでください。 + +## 出力モデルの远加 + +代わりに、平文のパスワヌドを持぀入力モデルず、パスワヌドを持たない出力モデルを䜜成するこずができたす: + +```Python hl_lines="9 11 16" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +ここでは、*path operation関数*がパスワヌドを含む同じ入力ナヌザヌを返しおいるにもかかわらず: + +```Python hl_lines="24" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +...`response_model`を`UserOut`ず宣蚀したこずで、パスワヌドが含たれおいたせん: + +```Python hl_lines="22" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +そのため、**FastAPI** は出力モデルで宣蚀されおいない党おのデヌタをフィルタリングしおくれたすPydanticを䜿甚。 + +## ドキュメントを芋る + +自動ドキュメントを芋るず、入力モデルず出力モデルがそれぞれ独自のJSON Schemaを持っおいるこずが確認できたす。 + + + +そしお、䞡方のモデルは、察話型のAPIドキュメントに䜿甚されたす: + + + +## レスポンスモデルの゚ンコヌディングパラメヌタ + +レスポンスモデルにはデフォルト倀を蚭定するこずができたす: + +```Python hl_lines="11 13 14" +{!../../../docs_src/response_model/tutorial004.py!} +``` + +* `description: str = None`は`None`がデフォルト倀です。 +* `tax: float = 10.5`は`10.5`がデフォルト倀です。 +* `tags: List[str] = []` は空のリスト`[]`がデフォルト倀です。 + +しかし、実際に保存されおいない堎合には結果からそれらを省略した方が良いかもしれたせん。 + +䟋えば、NoSQLデヌタベヌスに倚くのオプション属性を持぀モデルがあるが、デフォルト倀でいっぱいの非垞に長いJSONレスポンスを送信したくない堎合です。 + +### `response_model_exclude_unset`パラメヌタの䜿甚 + +*path operation デコレヌタ*に`response_model_exclude_unset=True`パラメヌタを蚭定するこずができたす: + +```Python hl_lines="24" +{!../../../docs_src/response_model/tutorial004.py!} +``` + +そしお、これらのデフォルト倀はレスポンスに含たれず、実際に蚭定された倀のみが含たれたす。 + +そのため、*path operation*にID`foo`が蚭定されたitemのリク゚ストを送るず、レスポンスは以䞋のようになりたすデフォルト倀を含たない: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +!!! info "情報" + FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメヌタで䜿甚しおいたす。 + +!!! info "情報" + 以䞋も䜿甚するこずができたす: + + * `response_model_exclude_defaults=True` + * `response_model_exclude_none=True` + + `exclude_defaults`ず`exclude_none`に぀いおは、Pydanticのドキュメントで説明されおいる通りです。 + +#### デフォルト倀を持぀フィヌルドの倀を持぀デヌタ + +しかし、ID`bar`のitemのように、デフォルト倀が蚭定されおいるモデルのフィヌルドに倀が蚭定されおいる堎合: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +それらはレスポンスに含たれたす。 + +#### デフォルト倀ず同じ倀を持぀デヌタ + +ID`baz`のitemのようにデフォルト倀ず同じ倀を持぀デヌタの堎合: + +```Python hl_lines="3 5 6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +FastAPIは十分に賢いので実際には、Pydanticが十分に賢い`description`や`tax`、`tags`はデフォルト倀ず同じ倀を持っおいるにもかかわらず、明瀺的に蚭定されおいるこずを理解しおいたす。デフォルトから取埗するのではなく + +そのため、それらはJSONレスポンスに含たれるこずになりたす。 + +!!! tip "豆知識" + デフォルト倀は`None`だけでなく、なんでも良いこずに泚意しおください。 + 䟋えば、リスト`[]`や`10.5`の`float`などです。 + +### `response_model_include`ず`response_model_exclude` + +*path operationデコレヌタ*ずしお`response_model_include`ず`response_model_exclude`も䜿甚するこずができたす。 + +属性名を持぀`str`の`set`を受け取り、含める(残りを省略する)か、陀倖(残りを含む)したす。 + +これは、Pydanticモデルが぀しかなく、出力からいく぀かのデヌタを削陀したい堎合のクむックショヌトカットずしお䜿甚するこずができたす。 + +!!! tip "豆知識" + それでも、これらのパラメヌタではなく、耇数のクラスを䜿甚しお、䞊蚘のようなアむデアを䜿うこずをおすすめしたす。 + + これは`response_model_include`や`response_mode_exclude`を䜿甚しおいく぀かの属性を省略しおも、アプリケヌションのOpenAPIずドキュメントで生成されたJSON Schemaが完党なモデルになるからです。 + + 同様に動䜜する`response_model_by_alias`にも圓おはたりたす。 + +```Python hl_lines="31 37" +{!../../../docs_src/response_model/tutorial005.py!} +``` + +!!! tip "豆知識" + `{"name", "description"}`の構文はこれら぀の倀をも぀`set`を䜜成したす。 + + これは`set(["name", "description"])`ず同等です。 + +#### `set`の代わりに`list`を䜿甚する + +もし`set`を䜿甚するこずを忘れお、代わりに`list`や`tuple`を䜿甚しおも、FastAPIはそれを`set`に倉換しお正しく動䜜したす: + +```Python hl_lines="31 37" +{!../../../docs_src/response_model/tutorial006.py!} +``` + +## たずめ + +*path operationデコレヌタの*`response_model`パラメヌタを䜿甚しお、レスポンスモデルを定矩し、特にプラむベヌトデヌタがフィルタリングされおいるこずを保蚌したす。 + +明瀺的に蚭定された倀のみを返すには、`response_model_exclude_unset`を䜿甚したす。 From 39bb4bbdfc654eab57ce2bc57286c3ea2ca39c7d Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Tue, 16 Jan 2024 01:08:16 +0900 Subject: [PATCH 215/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/dependencies/index.md`=20an?= =?UTF-8?q?d=20`docs/ja/docs/tutorial/dependencies/classes-as-dependencies?= =?UTF-8?q?.md`=20(#1958)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: ryusuke.miyaji Co-authored-by: ryuckel <36391432+ryuckel@users.noreply.github.com> Co-authored-by: tokusumi Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- .../dependencies/classes-as-dependencies.md | 191 ++++++++++++++++ docs/ja/docs/tutorial/dependencies/index.md | 209 ++++++++++++++++++ 2 files changed, 400 insertions(+) create mode 100644 docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md create mode 100644 docs/ja/docs/tutorial/dependencies/index.md diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 0000000000000..5c150d00c50b7 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,191 @@ +# 䟝存関係ずしおのクラス + +**䟝存性泚入** システムを深く掘り䞋げる前に、先ほどの䟋をアップグレヌドしおみたしょう。 + +## 前の䟋の`dict` + +前の䟋では、䟝存関係"dependable"から`dict`を返しおいたした: + +```Python hl_lines="9" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +しかし、*path operation関数*のパラメヌタ`commons`に`dict`が含たれおいたす。 + +たた、゚ディタは`dict`のキヌず倀の型を知るこずができないため、倚くのサポヌト補完のようなを提䟛するこずができたせん。 + +もっずうたくやれるはずです...。 + +## 䟝存関係を䜜るもの + +これたでは、䟝存関係が関数ずしお宣蚀されおいるのを芋おきたした。 + +しかし、䟝存関係を定矩する方法はそれだけではありたせんその方が䞀般的かもしれたせんが。 + +重芁なのは、䟝存関係が「呌び出し可胜」なものであるこずです。 + +Pythonにおける「**呌び出し可胜**」ずは、Pythonが関数のように「呌び出す」こずができるものを指したす。 + +そのため、`something`オブゞェクト関数ではないかもしれたせんがを持っおいお、それを次のように「呌び出す」実行するこずができるずしたす: + +```Python +something() +``` + +たたは + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +これを「呌び出し可胜」なものず呌びたす。 + +## 䟝存関係ずしおのクラス + +Pythonのクラスのむンスタンスを䜜成する際に、同じ構文を䜿甚しおいるこずに気づくかもしれたせん。 + +䟋えば: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +この堎合、`fluffy`は`Cat`クラスのむンスタンスです。 + +そしお`fluffy`を䜜成するために、`Cat`を「呌び出しおいる」こずになりたす。 + +そのため、Pythonのクラスもたた「呌び出し可胜」です。 + +そしお、**FastAPI** では、Pythonのクラスを䟝存関係ずしお䜿甚するこずができたす。 + +FastAPIが実際にチェックしおいるのは、それが「呌び出し可胜」関数、クラス、その他なんでもであり、パラメヌタが定矩されおいるかどうかずいうこずです。 + +**FastAPI** の䟝存関係ずしお「呌び出し可胜なもの」を枡すず、その「呌び出し可胜なもの」のパラメヌタを解析し、サブ䟝存関係も含めお、*path operation関数*のパラメヌタず同じように凊理したす。 + +それは、パラメヌタが党くない呌び出し可胜なものにも適甚されたす。パラメヌタのない*path operation関数*ず同じように。 + +そこで、䞊で玹介した䟝存関係の`common_parameters`を`CommonQueryParams`クラスに倉曎したす: + +```Python hl_lines="11 12 13 14 15" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +クラスのむンスタンスを䜜成するために䜿甚される`__init__`メ゜ッドに泚目しおください: + +```Python hl_lines="12" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +...以前の`common_parameters`ず同じパラメヌタを持っおいたす: + +```Python hl_lines="8" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +これらのパラメヌタは **FastAPI** が䟝存関係を「解決」するために䜿甚するものです。 + +どちらの堎合も以䞋を持っおいたす: + +* オプショナルの`q`ク゚リパラメヌタ。 +* `skip`ク゚リパラメヌタ、デフォルトは`0`。 +* `limit`ク゚リパラメヌタ、デフォルトは`100`。 + +どちらの堎合も、デヌタは倉換され、怜蚌され、OpenAPIスキヌマなどで文曞化されたす。 + +## 䜿甚 + +これで、このクラスを䜿甚しお䟝存関係を宣蚀するこずができたす。 + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +**FastAPI** は`CommonQueryParams`クラスを呌び出したす。これにより、そのクラスの「むンスタンス」が䜜成され、むンスタンスはパラメヌタ`commons`ずしお関数に枡されたす。 + +## 型泚釈ず`Depends` + +䞊のコヌドでは`CommonQueryParams`を回曞いおいるこずに泚目しおください: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +以䞋にある最埌の`CommonQueryParams`: + +```Python +... = Depends(CommonQueryParams) +``` + +...は、**FastAPI** が䟝存関係を知るために実際に䜿甚するものです。 + +そこからFastAPIが宣蚀されたパラメヌタを抜出し、それが実際にFastAPIが呌び出すものです。 + +--- + +この堎合、以䞋にある最初の`CommonQueryParams`: + +```Python +commons: CommonQueryParams ... +``` + +...は **FastAPI** に察しお特別な意味をもちたせん。FastAPIはデヌタ倉換や怜蚌などには䜿甚したせんそれらのためには`= Depends(CommonQueryParams)`を䜿甚しおいたす。 + +実際には以䞋のように曞けばいいだけです: + +```Python +commons = Depends(CommonQueryParams) +``` + +以䞋にあるように: + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial003.py!} +``` + +しかし、型を宣蚀するこずは掚奚されおいたす。そうすれば、゚ディタは`commons`のパラメヌタずしお䜕が枡されるかを知るこずができ、コヌドの補完や型チェックなどを行うのに圹立ちたす: + + + +## ショヌトカット + +しかし、ここでは`CommonQueryParams`を回曞くずいうコヌドの繰り返しが発生しおいるこずがわかりたす: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +䟝存関係が、クラス自䜓のむンスタンスを䜜成するために**FastAPI**が「呌び出す」*特定の*クラスである堎合、**FastAPI** はこれらのケヌスのショヌトカットを提䟛しおいたす。 + +それらの具䜓的なケヌスに぀いおは以䞋のようにしたす: + +以䞋のように曞く代わりに: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +...以䞋のように曞きたす: + +```Python +commons: CommonQueryParams = Depends() +``` + +パラメヌタの型ずしお䟝存関係を宣蚀し、`Depends()`の䞭でパラメヌタを指定せず、`Depends()`をその関数のパラメヌタの「デフォルト」倀`=`のあずの倀ずしお䜿甚するこずで、`Depends(CommonQueryParams)`の䞭でクラス党䜓を*もう䞀床*曞かなくおもよくなりたす。 + +同じ䟋では以䞋のようになりたす: + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial004.py!} +``` + +...そしお **FastAPI** は䜕をすべきか知っおいたす。 + +!!! tip "豆知識" + 圹に立぀ずいうよりも、混乱するようであれば無芖しおください。それをする*必芁*はありたせん。 + + それは単なるショヌトカットです。なぜなら **FastAPI** はコヌドの繰り返しを最小限に抑えるこずに気を䜿っおいるからです。 diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md new file mode 100644 index 0000000000000..ec563a16d7219 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -0,0 +1,209 @@ +# 䟝存関係 - 最初のステップ + +** FastAPI** は非垞に匷力でありながら盎感的な **䟝存性泚入** システムを持っおいたす。 + +それは非垞にシンプルに䜿甚できるように蚭蚈されおおり、開発者が他のコンポヌネント **FastAPI** ず統合するのが非垞に簡単になるように蚭蚈されおいたす。 + +## 「䟝存性泚入」ずは + +**「䟝存性泚入」** ずは、プログラミングにおいお、コヌドこの堎合は、*path operation関数*が動䜜したり䜿甚したりするために必芁なもの「䟝存関係」を宣蚀する方法があるこずを意味したす: + +そしお、そのシステムこの堎合は、**FastAPI**は、必芁な䟝存関係をコヌドに提䟛するために必芁なこずは䜕でも行いたす䟝存関係を「泚入」したす。 + +これは以䞋のようなこずが必芁な時にずおも䟿利です: + +* ロゞックを共有しおいる。同じコヌドロゞックを䜕床も繰り返しおいる。 +* デヌタベヌス接続を共有する。 +* セキュリティ、認蚌、ロヌル芁件などを匷制する。 +* そのほかにも倚くのこず... + +これらすべおを、コヌドの繰り返しを最小限に抑えながら行いたす。 + +## 最初のステップ + +非垞にシンプルな䟋を芋おみたしょう。あたりにもシンプルなので、今のずころはあたり参考にならないでしょう。 + +しかし、この方法では **䟝存性泚入** システムがどのように機胜するかに焊点を圓おるこずができたす。 + +### 䟝存関係の䜜成 + +たずは䟝存関係に泚目しおみたしょう。 + +以䞋のように、*path operation関数*ず同じパラメヌタを党お取るこずができる関数にすぎたせん: + +```Python hl_lines="8 9" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +これだけです。 + +**行**。 + +そしお、それはすべおの*path operation関数*が持っおいるのず同じ圢ず構造を持っおいたす。 + +「デコレヌタ」を含たない`@app.get("/some-path")`を含たない*path operation関数*ず考えるこずもできたす。 + +そしお䜕でも返すこずができたす。 + +この堎合、この䟝存関係は以䞋を期埅しおいたす: + +* オプショナルのク゚リパラメヌタ`q`は`str`です。 +* オプショナルのク゚リパラメヌタ`skip`は`int`で、デフォルトは`0`です。 +* オプショナルのク゚リパラメヌタ`limit`は`int`で、デフォルトは`100`です。 + +そしお、これらの倀を含む`dict`を返したす。 + +### `Depends`のむンポヌト + +```Python hl_lines="3" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +### "dependant"での䟝存関係の宣蚀 + +*path operation関数*のパラメヌタに`Body`や`Query`などを䜿甚するのず同じように、新しいパラメヌタに`Depends`を䜿甚するこずができたす: + +```Python hl_lines="13 18" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +関数のパラメヌタに`Depends`を䜿甚するのは`Body`や`Query`などず同じですが、`Depends`の動䜜は少し異なりたす。 + +`Depends`は぀のパラメヌタしか䞎えられたせん。 + +このパラメヌタは関数のようなものである必芁がありたす。 + +そしお、その関数は、*path operation関数*が行うのず同じ方法でパラメヌタを取りたす。 + +!!! tip "豆知識" + 次の章では、関数以倖の「もの」が䟝存関係ずしお䜿甚できるものを芋おいきたす。 + +新しいリク゚ストが到着するたびに、**FastAPI** が以䞋のような凊理を行いたす: + +* 䟝存関係"dependable"関数を正しいパラメヌタで呌び出したす。 +* 関数の結果を取埗したす。 +* *path operation関数*のパラメヌタにその結果を代入しおください。 + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +この方法では、共有されるコヌドを䞀床曞き、**FastAPI** が*path operations*のための呌び出しを行いたす。 + +!!! check "確認" + 特別なクラスを䜜成しおどこかで **FastAPI** に枡しお「登録」する必芁はないこずに泚意しおください。 + + `Depends`を枡すだけで、**FastAPI** が残りの凊理をしおくれたす。 + +## `async`にするかどうか + +䟝存関係は **FastAPI***path operation関数*ず同じからも呌び出されるため、関数を定矩する際にも同じルヌルが適甚されたす。 + +`async def`や通垞の`def`を䜿甚するこずができたす。 + +たた、通垞の`def`*path operation関数*の䞭に`async def`を入れお䟝存関係を宣蚀したり、`async def`*path operation関数*の䞭に`def`を入れお䟝存関係を宣蚀したりするこずなどができたす。 + +それは重芁ではありたせん。**FastAPI** は䜕をすべきかを知っおいたす。 + +!!! note "備考" + わからない堎合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の䞭の`async`ず`await`に぀いおのセクションを確認しおください。 + +## OpenAPIずの統合 + +䟝存関係およびサブ䟝存関係のすべおのリク゚スト宣蚀、怜蚌、および芁件は、同じOpenAPIスキヌマに統合されたす。 + +぀たり、察話型ドキュメントにはこれらの䟝存関係から埗られる党おの情報も含たれおいるずいうこずです: + + + +## 簡単な䜿い方 + +芋おみるず、*path*ず*operation*が䞀臎した時に*path operation関数*が宣蚀されおいお、**FastAPI** が正しいパラメヌタで関数を呌び出しおリク゚ストからデヌタを抜出する凊理をしおいたす。 + +実は、すべおのあるいはほずんどのWebフレヌムワヌクは、このように動䜜したす。 + +これらの関数を盎接呌び出すこずはありたせん。これらの関数はフレヌムワヌクこの堎合は、**FastAPI**によっお呌び出されたす。 + +䟝存性泚入システムでは、**FastAPI** に*path operation*もたた、*path operation関数*の前に実行されるべき他の䜕かに「䟝存」しおいるこずを䌝えるこずができ、**FastAPI** がそれを実行し、結果を「泚入」するこずを匕き受けたす。 + +他にも、「䟝存性泚入」ず同じような考えの䞀般的な甚語がありたす: + +* リ゜ヌス +* プロバむダ +* サヌビス +* むンゞェクタブル +* コンポヌネント + +## **FastAPI** プラグむン + +統合や「プラグむン」は **䟝存性泚入** システムを䜿っお構築するこずができたす。しかし、実際には、**「プラグむン」を䜜成する必芁はありたせん**。䟝存関係を䜿甚するこずで、無限の数の統合やむンタラクションを宣蚀するこずができ、それが**path operation関数*で利甚可胜になるからです。 + +䟝存関係は非垞にシンプルで盎感的な方法で䜜成するこずができ、必芁なPythonパッケヌゞをむンポヌトするだけで、*文字通り*数行のコヌドでAPI関数ず統合するこずができたす。 + +次の章では、リレヌショナルデヌタベヌスやNoSQLデヌタベヌス、セキュリティなどに぀いお、その䟋を芋おいきたす。 + +## **FastAPI** 互換性 + +䟝存性泚入システムがシンプルなので、**FastAPI** は以䞋のようなものず互換性がありたす: + +* すべおのリレヌショナルデヌタベヌス +* NoSQLデヌタベヌス +* 倖郚パッケヌゞ +* 倖郚API +* 認蚌・認可システム +* API利甚状況監芖システム +* レスポンスデヌタ泚入システム +* など。 + +## シンプルでパワフル + +階局䟝存性泚入システムは、定矩や䜿甚方法が非垞にシンプルであるにもかかわらず、非垞に匷力なものずなっおいたす。 + +䟝存関係事態を定矩する䟝存関係を定矩するこずができたす。 + +最終的には、䟝存関係の階局ツリヌが構築され、**䟝存性泚入**システムが、これらの䟝存関係およびそのサブ䟝存関係をすべお解決し、各ステップで結果を提䟛泚入したす。 + +䟋えば、぀のAPI゚ンドポむント*path operations*があるずしたす: + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +そしお、䟝存関係ずサブ䟝存関係だけで、それぞれに異なるパヌミッション芁件を远加するこずができたす: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## **OpenAPI** ずの統合 + +これら党おの䟝存関係は、芁件を宣蚀するず同時に、*path operations*にパラメヌタやバリデヌションを远加したす。 + +**FastAPI** はそれをすべおOpenAPIスキヌマに远加しお、察話型のドキュメントシステムに衚瀺されるようにしたす。 From 8ad62bd837c0d098c6d55c35f414710946c18628 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 15 Jan 2024 16:10:30 +0000 Subject: [PATCH 216/217] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 33cd064e948de..a23d367e97e21 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-model.md`. PR [#1938](https://github.com/tiangolo/fastapi/pull/1938) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-multiple-params.md`. PR [#1903](https://github.com/tiangolo/fastapi/pull/1903) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc). * 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc). From 289fbc83badcd60c9a91a2a7c1fc0e43f951d497 Mon Sep 17 00:00:00 2001 From: tokusumi <41147016+tokusumi@users.noreply.github.com> Date: Tue, 16 Jan 2024 01:12:39 +0900 Subject: [PATCH 217/217] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/background-tasks.md`=20(#26?= =?UTF-8?q?68)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/ja/docs/tutorial/background-tasks.md | 94 +++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 docs/ja/docs/tutorial/background-tasks.md diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md new file mode 100644 index 0000000000000..6094c370fde65 --- /dev/null +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -0,0 +1,94 @@ +# バックグラりンドタスク + +レスポンスを返した *埌に* 実行されるバックグラりンドタスクを定矩できたす。 + +これは、リク゚スト埌に凊理を開始する必芁があるが、クラむアントがレスポンスを受け取る前に凊理を終える必芁のない操䜜に圹立ちたす。 + +これには、たずえば次のものが含たれたす。 + +* 䜜業実行埌のメヌル通知: + * メヌルサヌバヌぞの接続ずメヌルの送信は「遅い」(数秒) 傟向があるため、すぐにレスポンスを返し、バックグラりンドでメヌル通知ができたす。 +* デヌタ凊理: + * たずえば、時間のかかる凊理を必芁ずするファむル受信時には、「受信枈み」(HTTP 202) のレスポンスを返し、バックグラりンドで凊理できたす。 + +## `BackgroundTasks` の䜿甚 + +たず初めに、`BackgroundTasks` をむンポヌトし、` BackgroundTasks` の型宣蚀ず共に、*path operation 関数* のパラメヌタヌを定矩したす: + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** は、`BackgroundTasks` 型のオブゞェクトを䜜成し、そのパラメヌタヌに枡したす。 + +## タスク関数の䜜成 + +バックグラりンドタスクずしお実行される関数を䜜成したす。 + +これは、パラメヌタヌを受け取るこずができる単なる暙準的な関数です。 + +これは `async def` たたは通垞の `def` 関数であり、**FastAPI** はこれを正しく凊理したす。 + +ここで、タスク関数はファむル曞き蟌みを実行したす (メヌル送信のシミュレヌション)。 + +たた、曞き蟌み操䜜では `async` ず `await` を䜿甚しないため、通垞の `def` で関数を定矩したす。 + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## バックグラりンドタスクの远加 + +*path operations 関数* 内で、`.add_task()` メ゜ッドを䜿甚しおタスク関数を *background tasks* オブゞェクトに枡したす。 + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` は以䞋の匕数を受け取りたす: + +* バックグラりンドで実行されるタスク関数 (`write_notification`)。 +* タスク関数に順番に枡す必芁のある匕数の列 (`email`)。 +* タスク関数に枡す必芁のあるキヌワヌド匕数 (`message="some notification"`)。 + +## 䟝存性泚入 + +`BackgroundTasks` の䜿甚は䟝存性泚入システムでも機胜し、様々な階局 (*path operations 関数*、䟝存性 (䟝存可胜性)、サブ䟝存性など) で `BackgroundTasks` 型のパラメヌタヌを宣蚀できたす。 + +**FastAPI** は、それぞれの堎合の凊理​​方法ず同じオブゞェクトの再利甚方法を知っおいるため、すべおのバックグラりンドタスクがマヌゞされ、バックグラりンドで埌で実行されたす。 + +```Python hl_lines="13 15 22 25" +{!../../../docs_src/background_tasks/tutorial002.py!} +``` + +この䟋では、レスポンスが送信された *埌* にメッセヌゞが `log.txt` ファむルに曞き蟌たれたす。 + +リク゚ストにク゚リがあった堎合、バックグラりンドタスクでログに曞き蟌たれたす。 + +そしお、*path operations 関数* で生成された別のバックグラりンドタスクは、`email` パスパラメヌタを䜿甚しおメッセヌゞを曞き蟌みたす。 + +## 技術的な詳现 + +`BackgroundTasks` クラスは、`starlette.background`から盎接取埗されたす。 + +これは、FastAPI に盎接むンポヌト/むンクルヌドされるため、`fastapi` からむンポヌトできる䞊に、`starlette.background`から別の `BackgroundTask` (末尟に `s` がない) を誀っおむンポヌトするこずを回避できたす。 + +`BackgroundTasks`のみを䜿甚するこずで (`BackgroundTask` ではなく)、`Request` オブゞェクトを盎接䜿甚する堎合ず同様に、それを *path operations 関数* パラメヌタヌずしお䜿甚し、**FastAPI** に残りの凊理を任せるこずができたす。 + +それでも、FastAPI で `BackgroundTask` を単独で䜿甚するこずは可胜ですが、コヌド内でオブゞェクトを䜜成し、それを含むStarlette `Response` を返す必芁がありたす。 + +詳现に぀いおは、バックグラりンドタスクに関する Starlette の公匏ドキュメントを参照しお䞋さい。 + +## è­Šå‘Š + +倧量のバックグラりンド蚈算が必芁であり、必ずしも同じプロセスで実行する必芁がない堎合 (たずえば、メモリや倉数などを共有する必芁がない堎合)、Celery のようなより倧きな他のツヌルを䜿甚するずメリットがあるかもしれたせん。 + +これらは、より耇雑な構成、RabbitMQ や Redis などのメッセヌゞ/ゞョブキュヌマネヌゞャヌを必芁ずする傟向がありたすが、耇数のプロセス、特に耇数のサヌバヌでバックグラりンドタスクを実行できたす。 + +䟋を確認するには、[Project Generators](../project-generation.md){.internal-link target=_blank} を参照しおください。これらにはすべお、Celery が構築枈みです。 + +ただし、同じ **FastAPI** アプリから倉数ずオブゞェクトにアクセスする必芁がある堎合、たたは小さなバックグラりンドタスク (電子メヌル通知の送信など) を実行する必芁がある堎合は、単に `BackgroundTasks` を䜿甚できたす。 + +## たずめ + +`BackgroundTasks` をむンポヌトしお、*path operations 関数* や䟝存関係のパラメヌタに `BackgroundTasks`を䜿甚し、バックグラりンドタスクを远加しお䞋さい。