Compare commits
79 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5614b94ccc | ||
|
|
e170c86412 | ||
|
|
180bdf31ac | ||
|
|
1e58a3e44c | ||
|
|
dfe3f614ed | ||
|
|
97c747fe54 | ||
|
|
fdb6c9ccc5 | ||
|
|
4fdcdf341c | ||
|
|
e2a6341c60 | ||
|
|
7046d80a23 | ||
|
|
9f89399f5e | ||
|
|
ed0fe9f369 | ||
|
|
6e9b771abf | ||
|
|
4a93562a3d | ||
|
|
3f478b7733 | ||
|
|
c660d96dce | ||
|
|
6de9f5890d | ||
|
|
a16ecf2f91 | ||
|
|
7a2c5526d4 | ||
|
|
d6b5bc9401 | ||
|
|
e6f8aa8756 | ||
|
|
f0a14a9ab6 | ||
|
|
c3dbf4ef7c | ||
|
|
52dd5924d7 | ||
|
|
a960c42178 | ||
|
|
436b023fe4 | ||
|
|
f1759297c7 | ||
|
|
f1ca8da6e1 | ||
|
|
478f157013 | ||
|
|
5c8b41abf2 | ||
|
|
4236c99b7f | ||
|
|
1a816fd6a0 | ||
|
|
02b7d988ae | ||
|
|
1b70a1cbf6 | ||
|
|
259c55f7cd | ||
|
|
6a05f1774e | ||
|
|
6189aacd0f | ||
|
|
9e6b069c09 | ||
|
|
6ffc8a547f | ||
|
|
51e920e2fc | ||
|
|
c27b9dcf9d | ||
|
|
c7e137c6e0 | ||
|
|
7e4d7fe895 | ||
|
|
2c57ea57bf | ||
|
|
be7d15ce3a | ||
|
|
afc2bb0801 | ||
|
|
313bbe802f | ||
|
|
d550738fa2 | ||
|
|
cc99e23e82 | ||
|
|
dbdcf86a11 | ||
|
|
2434980968 | ||
|
|
ee27f7790f | ||
|
|
d2cc2627ba | ||
|
|
f6a285c13c | ||
|
|
8af0b136b1 | ||
|
|
159a61d2b0 | ||
|
|
94fe5495fa | ||
|
|
8cc3ac1329 | ||
|
|
6b49f67d11 | ||
|
|
9972b76efa | ||
|
|
410da16a14 | ||
|
|
8997f96540 | ||
|
|
b8331b13d7 | ||
|
|
7a3c244c07 | ||
|
|
7a692d2c7b | ||
|
|
b53c443a06 | ||
|
|
7d7289aeb8 | ||
|
|
24b638faf6 | ||
|
|
2561a17225 | ||
|
|
d8cfa8ac87 | ||
|
|
76083559f0 | ||
|
|
df56655361 | ||
|
|
2e67f2fa6d | ||
|
|
ac073b2f5f | ||
|
|
4bcdbc5673 | ||
|
|
97adeca0a4 | ||
|
|
ac99792762 | ||
|
|
d01e0a10d8 | ||
|
|
de0f466ef8 |
1
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
3
.github/workflows/build-docs.yml
vendored
@@ -20,6 +20,9 @@ jobs:
|
||||
run: python3.7 -m pip install flit
|
||||
- name: Install docs extras
|
||||
run: python3.7 -m flit install --extras doc
|
||||
- name: Install Material for MkDocs Insiders
|
||||
if: github.event.pull_request.head.repo.fork == false
|
||||
run: pip install git+https://${{ secrets.ACTIONS_TOKEN }}@github.com/squidfunk/mkdocs-material-insiders.git
|
||||
- name: Build Docs
|
||||
run: python3.7 ./scripts/docs.py build-all
|
||||
- name: Zip docs
|
||||
|
||||
@@ -14,9 +14,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -48,6 +45,7 @@ The key features are:
|
||||
<!-- sponsors -->
|
||||
|
||||
<a href="https://www.deta.sh/?ref=fastapi" target="_blank" title="The launchpad for all your (team's) ideas"><img src="https://fastapi.tiangolo.com/img/sponsors/deta.svg"></a>
|
||||
<a href="https://www.investsuite.com/" target="_blank" title="Wealthtech as a service"><img src="https://fastapi.tiangolo.com/img/sponsors/investsuite.svg"></a>
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
@@ -127,7 +125,7 @@ You will also need an ASGI server, for production such as <a href="https://www.u
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -144,6 +144,10 @@ articles:
|
||||
title: HTTP server to display desktop notifications
|
||||
author_link: https://julienharbulot.com/
|
||||
author: Julien Harbulot
|
||||
- link: https://guitton.co/posts/fastapi-monitoring/
|
||||
title: How to monitor your FastAPI service
|
||||
author_link: https://twitter.com/louis_guitton
|
||||
author: Louis Guitton
|
||||
japanese:
|
||||
- link: https://qiita.com/mtitg/items/47770e9a562dd150631d
|
||||
title: FastAPI|DB接続してCRUDするPython製APIサーバーを構築
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
maintainers:
|
||||
- login: tiangolo
|
||||
answers: 979
|
||||
prs: 189
|
||||
answers: 998
|
||||
prs: 200
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/1326112?u=05f95ca7fdead36edd9c86be46b4ef6c3c71f876&v=4
|
||||
url: https://github.com/tiangolo
|
||||
experts:
|
||||
@@ -18,37 +18,45 @@ experts:
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/331403?v=4
|
||||
url: https://github.com/phy25
|
||||
- login: Kludex
|
||||
count: 104
|
||||
count: 123
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/7353520?u=cf8455cb899806b774a3a71073f88583adec99f6&v=4
|
||||
url: https://github.com/Kludex
|
||||
- login: Mause
|
||||
count: 99
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/1405026?v=4
|
||||
url: https://github.com/Mause
|
||||
- login: ycd
|
||||
count: 61
|
||||
count: 92
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/62724709?u=496a800351ea1009678e40b26288a2a6c0dfa8bd&v=4
|
||||
url: https://github.com/ycd
|
||||
- login: ArcLightSlavik
|
||||
count: 44
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/31127044?u=b81d0c33b056152513fb14749a9fe00f39887a8e&v=4
|
||||
url: https://github.com/ArcLightSlavik
|
||||
- login: sm-Fifteen
|
||||
count: 39
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4
|
||||
url: https://github.com/sm-Fifteen
|
||||
- login: ArcLightSlavik
|
||||
count: 35
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/31127044?u=b81d0c33b056152513fb14749a9fe00f39887a8e&v=4
|
||||
url: https://github.com/ArcLightSlavik
|
||||
- login: prostomarkeloff
|
||||
count: 33
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4
|
||||
url: https://github.com/prostomarkeloff
|
||||
- login: Mause
|
||||
count: 32
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/1405026?v=4
|
||||
url: https://github.com/Mause
|
||||
- login: wshayes
|
||||
count: 29
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4
|
||||
url: https://github.com/wshayes
|
||||
- login: includeamin
|
||||
count: 29
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4
|
||||
url: https://github.com/includeamin
|
||||
- login: dbanty
|
||||
count: 25
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/43723790?u=0cf33e4f40efc2ea206a1189fd63a11344eb88ed&v=4
|
||||
url: https://github.com/dbanty
|
||||
- login: raphaelauv
|
||||
count: 24
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
|
||||
url: https://github.com/raphaelauv
|
||||
- login: SirTelemak
|
||||
count: 23
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4
|
||||
@@ -73,18 +81,10 @@ experts:
|
||||
count: 19
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/24581770?v=4
|
||||
url: https://github.com/retnikt
|
||||
- login: raphaelauv
|
||||
count: 18
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
|
||||
url: https://github.com/raphaelauv
|
||||
- login: jorgerpo
|
||||
count: 17
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/12537771?u=7444d20019198e34911082780cc7ad73f2b97cb3&v=4
|
||||
url: https://github.com/jorgerpo
|
||||
- login: includeamin
|
||||
count: 17
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4
|
||||
url: https://github.com/includeamin
|
||||
- login: Slyfoxy
|
||||
count: 17
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/28262306?u=66ee21316275ef356081c2efc4ed7a4572e690dc&v=4
|
||||
@@ -102,47 +102,39 @@ experts:
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/20441825?u=ee1e59446b98f8ec2363caeda4c17164d0d9cc7d&v=4
|
||||
url: https://github.com/stefanondisponibile
|
||||
last_month_active:
|
||||
- login: ycd
|
||||
count: 19
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/62724709?u=496a800351ea1009678e40b26288a2a6c0dfa8bd&v=4
|
||||
url: https://github.com/ycd
|
||||
- login: Mause
|
||||
count: 18
|
||||
count: 51
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/1405026?v=4
|
||||
url: https://github.com/Mause
|
||||
- login: ycd
|
||||
count: 22
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/62724709?u=496a800351ea1009678e40b26288a2a6c0dfa8bd&v=4
|
||||
url: https://github.com/ycd
|
||||
- login: Kludex
|
||||
count: 11
|
||||
count: 14
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/7353520?u=cf8455cb899806b774a3a71073f88583adec99f6&v=4
|
||||
url: https://github.com/Kludex
|
||||
- login: includeamin
|
||||
count: 11
|
||||
count: 12
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4
|
||||
url: https://github.com/includeamin
|
||||
- login: eseglem
|
||||
count: 7
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/5920492?u=208d419cf667b8ac594c82a8db01932c7e50d057&v=4
|
||||
url: https://github.com/eseglem
|
||||
- login: ArcLightSlavik
|
||||
count: 5
|
||||
count: 9
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/31127044?u=b81d0c33b056152513fb14749a9fe00f39887a8e&v=4
|
||||
url: https://github.com/ArcLightSlavik
|
||||
- login: SirTelemak
|
||||
count: 4
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4
|
||||
url: https://github.com/SirTelemak
|
||||
- login: clmno
|
||||
count: 3
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/17064666?v=4
|
||||
url: https://github.com/clmno
|
||||
- login: raphaelauv
|
||||
count: 6
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
|
||||
url: https://github.com/raphaelauv
|
||||
top_contributors:
|
||||
- login: waynerv
|
||||
count: 17
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4
|
||||
url: https://github.com/waynerv
|
||||
- login: dmontagu
|
||||
count: 16
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/35119617?u=58ed2a45798a4339700e2f62b2e12e6e54bf0396&v=4
|
||||
url: https://github.com/dmontagu
|
||||
- login: waynerv
|
||||
count: 16
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4
|
||||
url: https://github.com/waynerv
|
||||
- login: euri10
|
||||
count: 13
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/1104190?u=ffd411da5d3b7ad3aa18261317f7ddc76f763c33&v=4
|
||||
@@ -152,9 +144,13 @@ top_contributors:
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4
|
||||
url: https://github.com/tokusumi
|
||||
- login: mariacamilagl
|
||||
count: 8
|
||||
count: 9
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4
|
||||
url: https://github.com/mariacamilagl
|
||||
- login: RunningIkkyu
|
||||
count: 7
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/31848542?u=706e1ee3f248245f2d68b976d149d06fd5a2010d&v=4
|
||||
url: https://github.com/RunningIkkyu
|
||||
- login: Serrones
|
||||
count: 6
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4
|
||||
@@ -167,27 +163,43 @@ top_contributors:
|
||||
count: 4
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/2546697?v=4
|
||||
url: https://github.com/jekirl
|
||||
- login: komtaki
|
||||
count: 4
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/39375566?v=4
|
||||
url: https://github.com/komtaki
|
||||
top_reviewers:
|
||||
- login: Kludex
|
||||
count: 53
|
||||
count: 62
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/7353520?u=cf8455cb899806b774a3a71073f88583adec99f6&v=4
|
||||
url: https://github.com/Kludex
|
||||
- login: tokusumi
|
||||
count: 40
|
||||
count: 41
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4
|
||||
url: https://github.com/tokusumi
|
||||
- login: ycd
|
||||
count: 24
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/62724709?u=496a800351ea1009678e40b26288a2a6c0dfa8bd&v=4
|
||||
url: https://github.com/ycd
|
||||
- login: dmontagu
|
||||
count: 23
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/35119617?u=58ed2a45798a4339700e2f62b2e12e6e54bf0396&v=4
|
||||
url: https://github.com/dmontagu
|
||||
- login: ycd
|
||||
count: 17
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/62724709?u=496a800351ea1009678e40b26288a2a6c0dfa8bd&v=4
|
||||
url: https://github.com/ycd
|
||||
- login: Laineyzhang55
|
||||
count: 21
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/59285379?v=4
|
||||
url: https://github.com/Laineyzhang55
|
||||
- login: AdrianDeAnda
|
||||
count: 16
|
||||
count: 20
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/1024932?u=bb7f8a0d6c9de4e9d0320a9f271210206e202250&v=4
|
||||
url: https://github.com/AdrianDeAnda
|
||||
- login: komtaki
|
||||
count: 19
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/39375566?v=4
|
||||
url: https://github.com/komtaki
|
||||
- login: waynerv
|
||||
count: 18
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4
|
||||
url: https://github.com/waynerv
|
||||
- login: SwftAlpc
|
||||
count: 16
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4
|
||||
@@ -196,18 +208,14 @@ top_reviewers:
|
||||
count: 14
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/3127847?u=b0a652331da17efeb85cd6e3a4969182e5004804&v=4
|
||||
url: https://github.com/cassiobotaro
|
||||
- login: Laineyzhang55
|
||||
count: 12
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/59285379?v=4
|
||||
url: https://github.com/Laineyzhang55
|
||||
- login: yanever
|
||||
count: 11
|
||||
count: 14
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/21978760?v=4
|
||||
url: https://github.com/yanever
|
||||
- login: waynerv
|
||||
count: 10
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4
|
||||
url: https://github.com/waynerv
|
||||
- login: RunningIkkyu
|
||||
count: 11
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/31848542?u=706e1ee3f248245f2d68b976d149d06fd5a2010d&v=4
|
||||
url: https://github.com/RunningIkkyu
|
||||
- login: mariacamilagl
|
||||
count: 10
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4
|
||||
@@ -216,14 +224,10 @@ top_reviewers:
|
||||
count: 10
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/1175560?v=4
|
||||
url: https://github.com/Attsun1031
|
||||
- login: RunningIkkyu
|
||||
count: 9
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/31848542?u=706e1ee3f248245f2d68b976d149d06fd5a2010d&v=4
|
||||
url: https://github.com/RunningIkkyu
|
||||
- login: komtaki
|
||||
count: 9
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/39375566?v=4
|
||||
url: https://github.com/komtaki
|
||||
- login: maoyibo
|
||||
count: 10
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/7887703?v=4
|
||||
url: https://github.com/maoyibo
|
||||
- login: Serrones
|
||||
count: 7
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4
|
||||
@@ -232,10 +236,18 @@ top_reviewers:
|
||||
count: 7
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/36391432?u=094eec0cfddd5013f76f31e55e56147d78b19553&v=4
|
||||
url: https://github.com/ryuckel
|
||||
- login: ArcLightSlavik
|
||||
count: 6
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/31127044?u=b81d0c33b056152513fb14749a9fe00f39887a8e&v=4
|
||||
url: https://github.com/ArcLightSlavik
|
||||
- login: MashhadiNima
|
||||
count: 5
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/49960770?u=e39b11d47188744ee07b2a1c7ce1a1bdf3c80760&v=4
|
||||
url: https://github.com/MashhadiNima
|
||||
- login: raphaelauv
|
||||
count: 5
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
|
||||
url: https://github.com/raphaelauv
|
||||
- login: euri10
|
||||
count: 4
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/1104190?u=ffd411da5d3b7ad3aa18261317f7ddc76f763c33&v=4
|
||||
@@ -244,10 +256,6 @@ top_reviewers:
|
||||
count: 4
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/23391143?u=56ab6bff50be950fa8cae5cf736f2ae66e319ff3&v=4
|
||||
url: https://github.com/rkbeatss
|
||||
- login: raphaelauv
|
||||
count: 4
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4
|
||||
url: https://github.com/raphaelauv
|
||||
sponsors:
|
||||
- login: samuelcolvin
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/4039449?u=807390ba9cfe23906c3bf8a0d56aaca3cf2bfa0d&v=4
|
||||
@@ -258,6 +266,9 @@ sponsors:
|
||||
- login: wshayes
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4
|
||||
url: https://github.com/wshayes
|
||||
- login: lukin0110
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/992275?u=d20b7e18b213ae7004585b382eccb542db5ffe48&v=4
|
||||
url: https://github.com/lukin0110
|
||||
- login: ltieman
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/1084689?u=c9bf77f5e57f98b49694870219b9bd9d1cc862e7&v=4
|
||||
url: https://github.com/ltieman
|
||||
@@ -267,9 +278,6 @@ sponsors:
|
||||
- login: timdrijvers
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/1694939?v=4
|
||||
url: https://github.com/timdrijvers
|
||||
- login: abdelhai
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/1752577?u=8f8f2bce75f3ab68188cea2b5da37c784197acd8&v=4
|
||||
url: https://github.com/abdelhai
|
||||
- login: ddahan
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/1933516?u=4068dc3c5db5d3605116c4f5df6deb9fee324c33&v=4
|
||||
url: https://github.com/ddahan
|
||||
@@ -292,10 +300,13 @@ sponsors:
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4
|
||||
url: https://github.com/pawamoy
|
||||
- login: p141592
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/5256328?u=7f9fdf3329bf90017cff00c8a78781bd7a2b48aa&v=4
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/5256328?u=07bc6374282ab3d08511afebaa5d511987d034f1&v=4
|
||||
url: https://github.com/p141592
|
||||
- login: ginomempin
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/6091865?v=4
|
||||
url: https://github.com/ginomempin
|
||||
- login: fabboe
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/7251331?v=4
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/7251331?u=43098dddeee6514a552ee5e98bc198ecfd18fdb7&v=4
|
||||
url: https://github.com/fabboe
|
||||
- login: Shackelford-Arden
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/7362263?v=4
|
||||
@@ -303,9 +314,9 @@ sponsors:
|
||||
- login: macleodmac
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/8996312?u=e39c68c3e0b1d264dcba4850134a291680f46355&v=4
|
||||
url: https://github.com/macleodmac
|
||||
- login: cristeaadrian
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/9112724?u=76099d546d6ee44b3ad7269773ecb916590c6a36&v=4
|
||||
url: https://github.com/cristeaadrian
|
||||
- login: hard-coders
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/9651103?u=f2d3d2038c55d86d7f9348f4e6c5e30191e4ee8b&v=4
|
||||
url: https://github.com/hard-coders
|
||||
- login: otivvormes
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/11317418?u=6de1edefb6afd0108c0ad2816bd6efc4464a9c44&v=4
|
||||
url: https://github.com/otivvormes
|
||||
@@ -321,9 +332,6 @@ sponsors:
|
||||
- login: robintully
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/17059673?u=862b9bb01513f5acd30df97433cb97a24dbfb772&v=4
|
||||
url: https://github.com/robintully
|
||||
- login: Duval23
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/17622958?v=4
|
||||
url: https://github.com/Duval23
|
||||
- login: wedwardbeck
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/19333237?u=1de4ae2bf8d59eb4c013f21d863cbe0f2010575f&v=4
|
||||
url: https://github.com/wedwardbeck
|
||||
@@ -349,8 +357,11 @@ sponsors:
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/34250156?u=c50c9df0e34f411f7e5f050a72e8d89696284eba&v=4
|
||||
url: https://github.com/d3vzer0
|
||||
- login: AjitZK
|
||||
avatarUrl: https://avatars0.githubusercontent.com/u/40203625?u=70c479337ab95d76ab59ae17ba0a988f1b43c0c6&v=4
|
||||
avatarUrl: https://avatars3.githubusercontent.com/u/40203625?u=9638bfeacfa5940358188f8205ce662bba022b53&v=4
|
||||
url: https://github.com/AjitZK
|
||||
- login: ilias-ant
|
||||
avatarUrl: https://avatars1.githubusercontent.com/u/42189572?u=064bf3a60fcb3c445ab038386321098920b3f4e4&v=4
|
||||
url: https://github.com/ilias-ant
|
||||
- login: dbanty
|
||||
avatarUrl: https://avatars2.githubusercontent.com/u/43723790?u=0cf33e4f40efc2ea206a1189fd63a11344eb88ed&v=4
|
||||
url: https://github.com/dbanty
|
||||
|
||||
@@ -2,7 +2,13 @@ gold:
|
||||
- url: https://www.deta.sh/?ref=fastapi
|
||||
title: The launchpad for all your (team's) ideas
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/deta.svg
|
||||
- url: https://www.investsuite.com/
|
||||
title: Wealthtech as a service
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/investsuite.svg
|
||||
silver:
|
||||
- url: https://testdriven.io/
|
||||
- url: https://testdriven.io/courses/tdd-fastapi/
|
||||
title: Learn to build high-quality web apps with best practices
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg
|
||||
- url: https://jobs.bywetransfer.com/
|
||||
title: WeTransfer - We deal in big ideas. You in?
|
||||
img: https://fastapi.tiangolo.com/img/sponsors/wetransfer.svg
|
||||
|
||||
@@ -83,15 +83,6 @@ So we are going to use that same knowledge to document how the *external API* sh
|
||||
|
||||
First create a new `APIRouter` that will contain one or more callbacks.
|
||||
|
||||
This router will never be added to an actual `FastAPI` app (i.e. it will never be passed to `app.include_router(...)`).
|
||||
|
||||
Because of that, you need to declare what will be the `default_response_class`, and set it to `JSONResponse`.
|
||||
|
||||
!!! Note "Technical Details"
|
||||
The `response_class` is normally set by the `FastAPI` app during the call to `app.include_router(some_router)`.
|
||||
|
||||
But as we are never calling `app.include_router(some_router)`, we need to set the `default_response_class` during creation of the `APIRouter`.
|
||||
|
||||
```Python hl_lines="5 26"
|
||||
{!../../../docs_src/openapi_callbacks/tutorial001.py!}
|
||||
```
|
||||
|
||||
@@ -55,3 +55,11 @@ a.internal-link::after {
|
||||
font-size: 80%;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
a.announce:link, a.announce:visited {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
a.announce:hover {
|
||||
color: var(--md-accent-fg-color);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Deploy on Deta
|
||||
# Deploy FastAPI on Deta
|
||||
|
||||
In this section you will learn see how to easily deploy a **FastAPI** application on <a href="https://www.deta.sh/?ref=fastapi" class="external-link" target="_blank">Deta</a> using the free plan. 🎁
|
||||
In this section you will learn how to easily deploy a **FastAPI** application on <a href="https://www.deta.sh/?ref=fastapi" class="external-link" target="_blank">Deta</a> using the free plan. 🎁
|
||||
|
||||
It will take you about **10 minutes**.
|
||||
|
||||
|
||||
@@ -11,13 +11,18 @@ You just need to install an ASGI compatible server like:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
!!! tip
|
||||
By adding the `standard`, Uvicorn will install and use some recommended extra dependencies.
|
||||
|
||||
That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost.
|
||||
|
||||
=== "Hypercorn"
|
||||
|
||||
* <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>, an ASGI server also compatible with HTTP/2.
|
||||
|
||||
@@ -10,6 +10,16 @@ There are very simple ways to help (several involve just one or two clicks).
|
||||
|
||||
And there are several ways to get help too.
|
||||
|
||||
## Subscribe to the newsletter
|
||||
|
||||
You can subscribe to the (infrequent) [**FastAPI and friends** newsletter](/newsletter/){.internal-link target=_blank} to stay updated about:
|
||||
|
||||
* News about FastAPI and friends 🚀
|
||||
* Guides 📝
|
||||
* Features ✨
|
||||
* Breaking changes 🚨
|
||||
* Tips and tricks ✅
|
||||
|
||||
## Star **FastAPI** in GitHub
|
||||
|
||||
You can "star" FastAPI in GitHub (clicking the star button at the top right): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. ⭐️
|
||||
@@ -52,12 +62,13 @@ I love to hear about how **FastAPI** is being used, what have you liked in it, i
|
||||
|
||||
* <a href="https://www.slant.co/options/34241/~fastapi-review" class="external-link" target="_blank">Vote for **FastAPI** in Slant</a>.
|
||||
* <a href="https://alternativeto.net/software/fastapi/" class="external-link" target="_blank">Vote for **FastAPI** in AlternativeTo</a>.
|
||||
* <a href="https://github.com/marmelab/awesome-rest/pull/93" class="external-link" target="_blank">Vote for **FastAPI** on awesome-rest</a>.
|
||||
|
||||
## Help others with issues in GitHub
|
||||
|
||||
You can see <a href="https://github.com/tiangolo/fastapi/issues" class="external-link" target="_blank">existing issues</a> and try and help others, most of the times they are questions that you might already know the answer for. 🤓
|
||||
|
||||
If you are helping a lot of people on issues you might become an official [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}. 🎉
|
||||
|
||||
## Watch the GitHub repository
|
||||
|
||||
You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">https://github.com/tiangolo/fastapi</a>. 👀
|
||||
@@ -70,43 +81,52 @@ Then you can try and help them solving those issues.
|
||||
|
||||
You can <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">create a new issue</a> in the GitHub repository, for example to:
|
||||
|
||||
* Ask a question or ask about a problem.
|
||||
* Suggest a new feature.
|
||||
* Ask a **question** or ask about a **problem**.
|
||||
* Suggest a new **feature**.
|
||||
|
||||
**Note**: if you create an issue then I'm going to ask you to also help others. 😉
|
||||
|
||||
## Create a Pull Request
|
||||
|
||||
You can <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">create a Pull Request</a>, for example:
|
||||
You can [contribute](contributing.md){.internal-link target=_blank} to the source code with Pull Requests, for example:
|
||||
|
||||
* To fix a typo you found on the documentation.
|
||||
* To share an article, video, or podcast you created or found about FastAPI by <a href="https://github.com/tiangolo/fastapi/edit/master/docs/en/data/external_links.yml" class="external-link" target="_blank">editing this file</a>.
|
||||
* Make sure you add your link to the end of the corresponding section.
|
||||
* To help [translate the documentation](contributing.md#translations){.internal-link target=_blank} to your language.
|
||||
* You can also help reviewing the translations created by others.
|
||||
* To propose new documentation sections.
|
||||
* To fix an existing issue/bug.
|
||||
* To add a new feature.
|
||||
|
||||
## Join the chat
|
||||
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
Join the 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">Discord chat server</a> 👥 and hang out with others in the FastAPI community.
|
||||
|
||||
Join the chat on Gitter: <a href="https://gitter.im/tiangolo/fastapi" class="external-link" target="_blank">https://gitter.im/tiangolo/fastapi</a>.
|
||||
!!! tip
|
||||
For questions, ask them in <a href="https://github.com/tiangolo/fastapi/issues/new/choose" class="external-link" target="_blank">GitHub issues</a>, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#experts){.internal-link target=_blank}.
|
||||
|
||||
There you can have quick conversations with others, help others, share ideas, etc.
|
||||
Use the chat only for other general conversations.
|
||||
|
||||
But have in mind that as it allows more "free conversation", it's easy to ask questions that are too general and more difficult to answer, so, you might not receive answers.
|
||||
There is also the previous <a href="https://gitter.im/tiangolo/fastapi" class="external-link" target="_blank">Gitter chat</a>, but as it doesn't have channels and advanced features, conversations are more difficult, so Discord is now the recommended system.
|
||||
|
||||
In GitHub issues the template will guide to to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the Gitter chat. 😅
|
||||
### Don't use the chat for questions
|
||||
|
||||
Conversations in Gitter are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation.
|
||||
Have in mind that as chats allow more "free conversation", it's easy to ask questions that are too general and more difficult to answer, so, you might not receive answers.
|
||||
|
||||
On the other side, there's more than 1000 people in the chat, so there's a high chance you'll find someone to talk to there, almost all the time. 😄
|
||||
In GitHub issues the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the chat systems. 😅
|
||||
|
||||
Conversations in the chat systems are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation. And only the ones in GitHub issues count to become a [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}, so you will most probably receive more attention in GitHub isssues.
|
||||
|
||||
On the other side, there are thousands of users in the chat systems, so there's a high chance you'll find someone to talk to there, almost all the time. 😄
|
||||
|
||||
## Sponsor the author
|
||||
|
||||
You can also financially support the author (me) through <a href="https://github.com/sponsors/tiangolo" class="external-link" target="_blank">GitHub sponsors</a>.
|
||||
|
||||
There you could buy me a coffee ☕️ to say thanks 😄.
|
||||
There you could buy me a coffee ☕️ to say thanks. 😄
|
||||
|
||||
And you can also become a Silver or Gold sponsor for FastAPI. 🏅🎉
|
||||
|
||||
## Sponsor the tools that power FastAPI
|
||||
|
||||
|
||||
114
docs/en/docs/img/sponsors/investsuite.svg
Normal file
@@ -0,0 +1,114 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="240"
|
||||
height="100"
|
||||
viewBox="0 0 63.5 26.458334"
|
||||
version="1.1"
|
||||
id="svg975">
|
||||
<defs
|
||||
id="defs969">
|
||||
<clipPath
|
||||
id="clip0">
|
||||
<rect
|
||||
width="770"
|
||||
height="222.03999"
|
||||
fill="#ffffff"
|
||||
id="rect14"
|
||||
x="0"
|
||||
y="0" />
|
||||
</clipPath>
|
||||
<clipPath
|
||||
id="clip0-7">
|
||||
<rect
|
||||
width="770"
|
||||
height="222.03999"
|
||||
fill="#ffffff"
|
||||
id="rect14-5"
|
||||
x="0"
|
||||
y="0" />
|
||||
</clipPath>
|
||||
<clipPath
|
||||
id="clip0-2">
|
||||
<rect
|
||||
width="770"
|
||||
height="222.03999"
|
||||
fill="#ffffff"
|
||||
id="rect14-0"
|
||||
x="0"
|
||||
y="0" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
<metadata
|
||||
id="metadata972">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<rect
|
||||
style="fill:#ffffff;fill-opacity:1;stroke-width:0.342717;stop-color:#000000"
|
||||
id="rect945"
|
||||
width="63.5"
|
||||
height="26.458334"
|
||||
x="4e-07"
|
||||
y="-1.5122477e-07" />
|
||||
<g
|
||||
id="g967"
|
||||
transform="translate(0.17210258,1.0583333)">
|
||||
<g
|
||||
id="g955"
|
||||
transform="matrix(0.65843845,0,0,0.65843845,0.27576501,1.1223943)">
|
||||
<path
|
||||
d="m 8.9812622,1.4378695 1.2474488,0.00173 7.302287,7.3022874 0.0018,1.3131081 -7.022162,7.02216 -1.7676605,-0.0025 -6.8470822,-6.847084 -0.00242,-1.7019627 7.0877822,-7.087706 z"
|
||||
fill="#d10622"
|
||||
fill-rule="evenodd"
|
||||
id="path884"
|
||||
style="fill:#b3b3b3;stroke-width:0.0383523" />
|
||||
<path
|
||||
d="m 12.889758,1.4378695 1.24741,0.00173 7.302287,7.3022874 0.0018,1.3131081 -7.022161,7.022161 -1.76766,-0.0025 -6.8470835,-6.847084 -0.00242,-1.7019627 7.0878215,-7.0877058 z"
|
||||
fill="#f7c0bd"
|
||||
fill-rule="evenodd"
|
||||
id="path895"
|
||||
style="stroke-width:0.0383523" />
|
||||
<path
|
||||
d="m 16.798207,1.4378695 1.24741,0.00173 7.302287,7.3022874 0.0018,1.3131081 -7.022162,7.022161 -1.767659,-0.0025 -6.8470836,-6.847084 -0.0024,-1.7019626 7.0877436,-7.0877059 z"
|
||||
fill="#0000ff"
|
||||
fill-rule="evenodd"
|
||||
opacity="0.8"
|
||||
id="path906"
|
||||
style="stroke-width:0.0383523" />
|
||||
<path
|
||||
d="m 20.706643,1.4378692 1.247449,0.00173 7.302287,7.3022875 0.0018,1.3131083 -7.022161,7.022161 -1.76766,-0.0025 -6.847122,-6.847084 -0.0024,-1.7019627 7.087783,-7.0877061 z"
|
||||
fill="#ffffff"
|
||||
fill-rule="evenodd"
|
||||
id="path917"
|
||||
style="fill:#e7285d;fill-opacity:1;stroke-width:0.0383523" />
|
||||
</g>
|
||||
<path
|
||||
d="m 58.713926,8.3808577 h 2.793359 l 0.084,-0.04316 c 0.04201,-0.09527 0.04201,-0.173052 0.04201,-0.216608 0,-1.168599 -0.713215,-2.120589 -1.761649,-2.120589 -1.21643,0 -2.013255,0.95199 -2.013255,2.129144 0,1.2036 0.964434,2.1991443 2.180866,2.1991443 0.629215,0 1.216431,-0.30333 1.594038,-0.5627163 v -0.909211 l -0.04201,-0.04277 c -0.419605,0.432439 -1.006435,0.692215 -1.55165,0.692215 -0.713214,0 -1.216431,-0.475995 -1.325708,-1.125434 z m -0.04667,-0.757546 c 0.124051,-0.446441 0.565828,-0.811214 1.184543,-0.811214 0.486495,0 0.928657,0.364773 0.972601,0.811214 z M 56.35728,10.328782 c 0.279997,0 0.726048,-0.118994 0.962101,-0.255108 V 9.2671277 l -0.04394,-0.04277 a 1.5905386,1.5905386 0 0 1 -0.917766,0.297497 c -0.349996,0 -0.656048,-0.254721 -0.656048,-0.934492 v -1.529096 h 1.573817 l 0.04395,-0.04277 v -0.764547 l -0.04395,-0.04239 h -1.57382 v -0.968322 l -0.04395,-0.05094 h -0.787101 l -0.04355,0.04239 v 0.976879 h -0.6996 l -0.04355,0.04277 v 0.764158 l 0.04355,0.04239 h 0.699603 v 1.571483 c 0,1.104433 0.56855,1.6994263 1.530262,1.6994263 z m -3.580069,-4.8696143 0.497773,-0.499328 v -0.08322 l -0.497773,-0.49933 h -0.08284 l -0.497769,0.499329 v 0.08322 l 0.497772,0.499328 z m -1.431873,4.7443943 0.04201,-0.04201 V 6.3127617 l -0.04201,-0.04201 h -0.754437 l -0.04238,0.04201 v 2.802693 c -0.20961,0.25122 -0.629216,0.418441 -1.048434,0.418441 -0.713214,0 -1.048434,-0.418441 -1.048434,-1.087712 v -2.133422 l -0.04201,-0.04201 h -0.755214 l -0.04161,0.04201 v 2.175421 c 0,1.128934 0.628827,1.8405923 1.887258,1.8405923 0.377218,0 0.754825,-0.125609 1.048433,-0.292829 v 0.125608 l 0.04201,0.04161 h 0.754826 z M 44.157191,5.6403867 c 0,-0.373329 0.24772,-0.62377 0.581384,-0.636603 v -0.0016 c 0.510994,0.0062 0.811992,0.302941 1.069433,0.851657 h 0.08711 l 0.6506,-0.511772 c -0.303326,-0.766816 -0.953931,-1.235422 -1.82231,-1.235422 v 0.0023 c -0.88238,0.02061 -1.564093,0.692603 -1.564093,1.532206 0,1.661704 2.646748,1.576538 2.646748,2.769636 0,0.59655 -0.390828,1.022768 -0.954711,1.022768 -0.520717,0 -0.824437,-0.298274 -1.08499,-0.852047 h -0.08672 l -0.650608,0.511383 c 0.30333,0.76727 0.954712,1.2358763 1.822315,1.2358763 1.084987,0 1.9522,-0.8524353 1.9522,-1.9179803 0,-1.959979 -2.646361,-1.917589 -2.646361,-2.770025 z m -2.629248,4.6883953 c 0.279218,0 0.725268,-0.118994 0.961323,-0.255108 V 9.2671277 l -0.04355,-0.04277 c -0.34105,0.237998 -0.673548,0.297497 -0.917766,0.297497 -0.349997,0 -0.656438,-0.254721 -0.656438,-0.934492 v -1.529096 h 1.574204 l 0.04355,-0.04277 v -0.764547 l -0.04355,-0.04239 h -1.574212 v -0.968322 l -0.04355,-0.05094 H 40.04085 l -0.04355,0.04239 v 0.976879 h -0.699992 l -0.04355,0.04277 v 0.764158 l 0.04395,0.04239 h 0.699603 v 1.571483 c 0,1.104433 0.568162,1.6994263 1.530263,1.6994263 z M 38.984247,9.0299077 c 0,-1.68776 -2.341086,-1.081878 -2.341086,-1.817648 0,-0.21622 0.21272,-0.389662 0.595772,-0.389662 0.425439,0 0.851268,0.129886 1.277097,0.432828 l 0.04277,-0.04317 v -0.865656 c -0.340654,-0.216609 -0.808872,-0.346108 -1.319865,-0.346108 -0.894436,0 -1.490206,0.51916 -1.490206,1.211764 0,1.601427 2.341085,0.995546 2.341085,1.818037 0,0.302942 -0.169943,0.475995 -0.766103,0.475995 -0.467828,0 -1.0216,-0.173053 -1.489428,-0.475995 l -0.04277,0.04317 v 0.865658 c 0.383051,0.2597753 1.0216,0.3896613 1.532206,0.3896613 1.021989,0 1.660538,-0.5627163 1.660538,-1.2988743 z m -5.63805,1.2988743 c 0.629603,0 1.216431,-0.30333 1.594038,-0.5627163 v -0.909212 l -0.04199,-0.04277 c -0.419218,0.432439 -1.006434,0.692214 -1.551651,0.692214 -0.713213,0 -1.216431,-0.475995 -1.325319,-1.125433 h 2.79297 l 0.084,-0.04316 c 0.04199,-0.09527 0.04199,-0.173053 0.04199,-0.216609 0,-1.168599 -0.712826,-2.120589 -1.761649,-2.120589 -1.21643,0 -2.013257,0.95199 -2.013257,2.129145 0,1.203599 0.964825,2.1991443 2.180868,2.1991443 z M 31.974211,7.6233117 c 0.124051,-0.446441 0.565828,-0.811214 1.184543,-0.811214 0.486106,0 0.928268,0.364773 0.972601,0.811214 z m -2.409531,2.6623043 1.600649,-3.9716793 -0.04201,-0.04277 h -0.842714 l -0.04201,0.04277 -1.095488,2.849359 -1.0951,-2.849359 -0.04238,-0.04277 h -0.842324 l -0.04238,0.04277 1.601039,3.9720693 0.04201,0.04316 h 0.758316 l 0.04238,-0.04277 z m -2.755247,-0.227498 0.04201,-0.04161 V 7.8410877 c 0,-1.129711 -0.629216,-1.840592 -1.887258,-1.840592 -0.377608,0 -0.755215,0.125227 -1.048824,0.29283 v -0.125609 l -0.04161,-0.04201 h -0.755599 l -0.04201,0.04201 v 3.8487913 l 0.04201,0.04161 h 0.755214 l 0.04161,-0.04161 V 7.2134267 c 0.209997,-0.250831 0.629215,-0.418051 1.048821,-0.418051 0.712825,0 1.048433,0.418051 1.048433,1.087322 v 2.1338103 l 0.04201,0.04161 h 0.754824 z M 21.996206,5.9604407 h 0.0019 v -1.583151 h -0.115497 l -0.693381,0.730715 v 5.1780013 l 0.04044,0.04277 h 0.725659 l 0.04045,-0.04277 V 5.9608287 Z m 30.510342,0.310329 -0.04045,0.04317 v 3.9720693 l 0.04045,0.04316 h 0.727992 l 0.04045,-0.04277 V 6.3135577 l -0.04045,-0.04277 h -0.728382 z"
|
||||
fill="#f7c0bd"
|
||||
fill-rule="evenodd"
|
||||
id="path934"
|
||||
style="fill:#e7285d;fill-opacity:1;stroke-width:0.388885" />
|
||||
</g>
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:4.65251px;line-height:1.25;font-family:Roboto, sans-serif;-inkscape-font-specification:'Roboto, sans-serif';text-align:center;letter-spacing:0px;word-spacing:0px;text-anchor:middle;stroke-width:0.116313"
|
||||
x="31.727283"
|
||||
y="21.847746"
|
||||
id="text959"><tspan
|
||||
id="tspan957"
|
||||
x="31.727282"
|
||||
y="21.847746"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Roboto, sans-serif;-inkscape-font-specification:'Roboto, sans-serif';text-align:center;text-anchor:middle;stroke-width:0.116313">Wealthtech as a service</tspan></text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 8.6 KiB |
|
Before Width: | Height: | Size: 9.9 KiB After Width: | Height: | Size: 26 KiB |
118
docs/en/docs/img/sponsors/wetransfer.svg
Normal file
@@ -0,0 +1,118 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="240"
|
||||
height="100"
|
||||
viewBox="0 0 63.5 26.458334"
|
||||
version="1.1"
|
||||
id="svg975">
|
||||
<defs
|
||||
id="defs969">
|
||||
<clipPath
|
||||
id="clip0">
|
||||
<rect
|
||||
width="770"
|
||||
height="222.03999"
|
||||
fill="#ffffff"
|
||||
id="rect14"
|
||||
x="0"
|
||||
y="0" />
|
||||
</clipPath>
|
||||
<clipPath
|
||||
id="clip0-7">
|
||||
<rect
|
||||
width="770"
|
||||
height="222.03999"
|
||||
fill="#ffffff"
|
||||
id="rect14-5"
|
||||
x="0"
|
||||
y="0" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
<metadata
|
||||
id="metadata972">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
id="layer1"
|
||||
transform="translate(-75.455132,-135.96141)">
|
||||
<rect
|
||||
style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.364576;stop-color:#000000"
|
||||
id="rect901"
|
||||
width="63.5"
|
||||
height="26.458334"
|
||||
x="75.455132"
|
||||
y="135.96141" />
|
||||
<rect
|
||||
style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.404023;stop-color:#000000"
|
||||
id="rect1758"
|
||||
width="60.854168"
|
||||
height="23.8125"
|
||||
x="76.778053"
|
||||
y="137.28433" />
|
||||
<text
|
||||
xml:space="preserve"
|
||||
style="font-size:4.23333px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;stroke-width:0.133861"
|
||||
x="107.22684"
|
||||
y="154.45795"
|
||||
id="text1712"><tspan
|
||||
x="107.22684"
|
||||
y="154.45795"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:4.23333px;font-family:Roboto;-inkscape-font-specification:Roboto;text-align:center;text-anchor:middle;fill:#000000;stroke-width:0.133861"
|
||||
id="tspan2004">We deal in big ideas. You in?</tspan><tspan
|
||||
x="107.22684"
|
||||
y="159.79095"
|
||||
style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:4.23333px;font-family:Roboto;-inkscape-font-specification:Roboto;text-align:center;text-anchor:middle;fill:#000000;stroke-width:0.133861"
|
||||
id="tspan874" /></text>
|
||||
<g
|
||||
id="g1003"
|
||||
transform="matrix(0.02061785,0,0,0.02061785,70.802235,134.33866)">
|
||||
<g
|
||||
id="g1015"
|
||||
transform="translate(4.0510205)">
|
||||
<path
|
||||
d="m 900.5,226.1 c -21.9,23 -28.6,35.3 -44.3,70.1 L 710.9,630 608.2,396.1 506.6,630 360.2,296.2 c -15.2,-34.8 -21.9,-46 -44.3,-70.1 h 185.7 c -14,11.8 -21.3,26.9 -21.3,46 0,13.4 2.3,23 9.5,40.4 l 55.5,132.4 41,-98.7 -23,-53.3 c -13.5,-30.8 -23,-49.9 -36.5,-66.7 h 185.7 c -18,11.8 -26.9,26.9 -26.9,46 0,13.4 2.3,23 9.5,40.4 L 751.8,445 807.9,312.6 c 7.3,-17.4 10.1,-26.9 10.1,-39.8 0,-16.8 -11.8,-37 -25.3,-46.5 z"
|
||||
id="path966" />
|
||||
<path
|
||||
d="m 1093.5,523.4 c -18,78 -61.2,103.8 -124,103.8 -71.8,0 -139.2,-52.2 -139.2,-150.3 0,-94.2 59.5,-161 137.5,-161 51.1,0 122.9,26.4 122.9,137.4 H 921.3 c 11.8,59.4 50.5,90.3 104.4,90.3 27.4,0 46.5,-5 67.8,-20.2 z M 917.9,414.6 v 7.3 H 992 c 0,-56.1 -12.4,-73.5 -35.9,-73.5 -24.2,0 -38.2,24.1 -38.2,66.2 z"
|
||||
id="path968" />
|
||||
<path
|
||||
d="M 1433.6,327.6 C 1387,283.3 1341,260.3 1305.7,260.3 v 247.4 c 0,49.9 12.9,80.2 47.1,111.1 h -212.1 c 34.2,-30.8 47.1,-61.1 47.1,-111.1 V 260.3 c -35.4,0 -83.6,23 -127.9,67.3 l 22.5,-118.4 c 15.2,11.8 43.2,16.8 74.6,16.8 h 179.6 c 31.4,0 59.5,-5.1 74.6,-16.8 z"
|
||||
id="path970" />
|
||||
<path
|
||||
d="m 1562.6,618.8 h -178.4 c 21.9,-25.8 31.4,-42.6 31.4,-83.6 v -90.9 c 0,-32 -4.5,-47.1 -25.8,-66.7 l -12.3,-11.2 134.7,-50.5 V 386 c 12.9,-40.4 33.1,-70.1 66.2,-70.1 26.9,0 44.3,19.1 44.3,47.1 0,29.7 -18.5,50.5 -44.3,50.5 -5.6,-12.9 -19.1,-19.1 -31.4,-19.1 -10.1,0 -19.6,2.8 -24.7,7.9 v 129.6 c -0.1,43.1 7.2,54.9 40.3,86.9 z"
|
||||
id="path972" />
|
||||
<path
|
||||
d="m 1931.3,567.2 c -6.7,35.3 -35.9,60 -75.8,60 -33.7,0 -59.5,-20.2 -67.3,-43.2 -16.8,30.3 -48.3,43.2 -81.9,43.2 -46.6,0 -78,-30.8 -78,-72.9 0,-49.4 35.4,-83.6 116.7,-103.2 l 37.6,-9 v -50.5 c 0,-31.4 -10.7,-44.3 -29.7,-44.3 -17.9,0 -29.7,11.8 -29.7,28 0,14 6.7,23 18.5,34.2 0,17.9 -28.1,36.4 -57.2,36.4 -28.6,0 -48.8,-21.9 -48.8,-48.8 0,-47.7 52.7,-81.3 130.2,-81.3 80.8,0 123.4,34.2 123.4,110.5 v 120.6 c 0,15.1 9,25.2 23,25.2 8.3,0.1 14.5,-1.6 19,-4.9 z m -148.7,-8.4 v -90.3 l -7.3,2.2 c -24.1,7.3 -40.4,23 -40.4,54.4 0,26.9 10.7,43.2 28.1,43.2 8.9,0 16.2,-2.8 19.6,-9.5 z"
|
||||
id="path974" />
|
||||
<path
|
||||
d="m 2083.3,618.8 h -150.9 c 15.7,-15.1 25.8,-37.6 25.8,-83.6 v -90.9 c 0,-30.8 -3.9,-46.5 -22.4,-63.9 l -12.9,-11.8 139.2,-52.7 v 43.7 c 16.3,-26.9 50.5,-43.7 84.7,-43.7 53.9,0 83.6,29.2 83.6,81.3 v 157.1 c 0,32 8.4,51.6 21.9,64.5 h -147 c 14.6,-14 18.5,-33.1 18.5,-48.2 V 410.1 c 0,-23.5 -7.8,-35.3 -29.7,-35.3 -12.3,0 -22.5,4.5 -29.2,11.2 v 184.5 c -0.1,15.2 3.8,33.7 18.4,48.3 z"
|
||||
id="path976" />
|
||||
<path
|
||||
d="m 2279.7,602.5 v -95.9 c 40.4,52.7 82.5,81.9 121.8,81.9 19.1,0 28.1,-10.1 28.1,-24.1 0,-13.5 -7.3,-21.3 -20.2,-26.4 l -65.1,-24.1 c -49.9,-18.5 -72.4,-49.4 -72.4,-95.3 0,-59.4 48.8,-102.6 118.4,-102.6 37.6,0 79.1,10.6 99.9,25.8 v 81.9 c -25.8,-45.4 -67.9,-70.7 -108.9,-70.7 -20.8,0 -31.4,6.7 -31.4,19.6 0,12.9 7.9,17.9 25.2,25.2 l 76.9,31.4 c 38.7,15.7 56.1,48.8 56.1,88.6 0,65.6 -47.7,109.4 -119.5,109.4 -36,0 -73,-7.9 -108.9,-24.7 z"
|
||||
id="path978" />
|
||||
<path
|
||||
d="m 2519.3,352.3 32.5,-49.9 c 41.5,-62.8 74.7,-93.1 130.8,-93.1 43.8,0 71.8,19.1 71.8,47.7 0,24.7 -20.2,42.6 -62.9,42.6 0,-34.8 -19.6,-47.7 -39.3,-47.7 -19.6,0 -34.8,14 -34.8,37 0,15.7 8.4,31.4 34.2,35.3 h 62.3 l -22.5,28 h -38.2 v 166.6 c 0,31.4 5.1,59.4 37.6,88.1 l 13.5,11.8 h -193.6 c 22.5,-22.4 35.9,-49.9 35.9,-90.3 V 352.3 Z"
|
||||
id="path980" />
|
||||
<path
|
||||
d="m 2959.2,523.4 c -18,78 -61.2,103.8 -124,103.8 -71.8,0 -139.2,-52.2 -139.2,-150.3 0,-94.2 59.5,-161 137.5,-161 51.1,0 122.9,26.4 122.9,137.4 H 2787 c 11.8,59.4 50.5,90.3 104.4,90.3 27.4,0 46.5,-5 67.8,-20.2 z M 2783.6,414.6 v 7.3 h 74.1 c 0,-56.1 -12.4,-73.5 -35.9,-73.5 -24.2,0 -38.2,24.1 -38.2,66.2 z"
|
||||
id="path982" />
|
||||
<path
|
||||
d="m 3147.2,618.8 h -178.4 c 21.9,-25.8 31.4,-42.6 31.4,-83.6 v -90.9 c 0,-32 -4.5,-47.1 -25.8,-66.7 L 2962,366.4 3096.7,315.9 V 386 c 12.9,-40.4 33.1,-70.1 66.2,-70.1 26.9,0 44.3,19.1 44.3,47.1 0,29.7 -18.5,50.5 -44.3,50.5 -5.6,-12.9 -19.1,-19.1 -31.4,-19.1 -10.1,0 -19.6,2.8 -24.7,7.9 v 129.6 c 0,43.1 7.3,54.9 40.4,86.9 z"
|
||||
id="path984" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 76 KiB After Width: | Height: | Size: 73 KiB |
43
docs/en/docs/img/tutorial/bigger-applications/package.drawio
Normal file
@@ -0,0 +1,43 @@
|
||||
<mxfile host="65bd71144e" modified="2020-11-28T18:13:19.199Z" agent="5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Code/1.51.1 Chrome/83.0.4103.122 Electron/9.3.3 Safari/537.36" etag="KPHuXUeExV3PdWouu_3U" version="13.6.5">
|
||||
<diagram id="zB4-QXJZ7ScUzHSLnJ1i" name="Page-1">
|
||||
<mxGraphModel dx="1154" dy="780" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1920" pageHeight="1200" math="0" shadow="0" extFonts="Roboto^https://fonts.googleapis.com/css?family=Roboto|Roboto Mono, mono^https://fonts.googleapis.com/css?family=Roboto+Mono%2C+mono">
|
||||
<root>
|
||||
<mxCell id="0"/>
|
||||
<mxCell id="1" parent="0"/>
|
||||
<mxCell id="2" value="" style="rounded=0;whiteSpace=wrap;html=1;fontStyle=1;strokeWidth=4;" parent="1" vertex="1">
|
||||
<mxGeometry x="110" y="280" width="1350" height="620" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="3" value="<font style="font-size: 24px" face="Roboto">Package app<br>app/__init__.py</font>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;strokeWidth=3;fontFamily=Roboto Mono, mono;FType=g;" parent="1" vertex="1">
|
||||
<mxGeometry x="635" y="310" width="300" height="80" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="15" value="<span style="font-family: &#34;roboto&#34; ; font-size: 24px">Module app.main</span><br style="font-family: &#34;roboto&#34; ; font-size: 24px"><span style="font-family: &#34;roboto&#34; ; font-size: 24px">app/main.py</span>" style="shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;strokeWidth=3;" parent="1" vertex="1">
|
||||
<mxGeometry x="140" y="430" width="360" height="100" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="16" value="<span style="font-family: &#34;roboto&#34; ; font-size: 24px">Module app.dependencies</span><br style="font-family: &#34;roboto&#34; ; font-size: 24px"><span style="font-family: &#34;roboto&#34; ; font-size: 24px">app/dependencies.py</span>" style="shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;strokeWidth=3;" parent="1" vertex="1">
|
||||
<mxGeometry x="130" y="565" width="370" height="100" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="5" value="" style="rounded=0;whiteSpace=wrap;html=1;fontStyle=1;strokeWidth=4;" parent="1" vertex="1">
|
||||
<mxGeometry x="1030" y="430" width="400" height="260" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="8" value="<font style="font-size: 24px" face="Roboto">Subpackage app.internal<br></font><span style="font-family: &#34;roboto&#34; ; font-size: 24px">app/internal/__init__.py</span><font style="font-size: 24px" face="Roboto"><br></font>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;strokeWidth=3;fontFamily=Roboto Mono, mono;FType=g;" parent="1" vertex="1">
|
||||
<mxGeometry x="1083.8438461538462" y="460" width="292.3076923076923" height="80" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="19" value="<span style="font-family: &#34;roboto&#34; ; font-size: 24px">Module app.internal.admin</span><br style="font-family: &#34;roboto&#34; ; font-size: 24px"><span style="font-family: &#34;roboto&#34; ; font-size: 24px">app/internal/admin.py</span>" style="shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;strokeWidth=3;" parent="1" vertex="1">
|
||||
<mxGeometry x="1050" y="570" width="360" height="100" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="4" value="" style="rounded=0;whiteSpace=wrap;html=1;fontStyle=1;strokeWidth=4;" parent="1" vertex="1">
|
||||
<mxGeometry x="540" y="430" width="440" height="410" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="7" value="<font style="font-size: 24px" face="Roboto">Subpackage app.routers<br>app/routers/__init__.py<br></font>" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;strokeWidth=3;fontFamily=Roboto Mono, mono;FType=g;" parent="1" vertex="1">
|
||||
<mxGeometry x="599.2307692307693" y="460" width="321.53846153846155" height="80" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="17" value="<span style="font-family: &#34;roboto&#34; ; font-size: 24px">Module app.routers.items</span><br style="font-family: &#34;roboto&#34; ; font-size: 24px"><span style="font-family: &#34;roboto&#34; ; font-size: 24px">app/routers/items.py</span>" style="shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;strokeWidth=3;" parent="1" vertex="1">
|
||||
<mxGeometry x="580" y="570" width="360" height="100" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="18" value="<span style="font-family: &#34;roboto&#34; ; font-size: 24px">Module app.routers.users</span><br style="font-family: &#34;roboto&#34; ; font-size: 24px"><span style="font-family: &#34;roboto&#34; ; font-size: 24px">app/routers/users.py</span>" style="shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;strokeWidth=3;" parent="1" vertex="1">
|
||||
<mxGeometry x="580" y="700" width="360" height="100" as="geometry"/>
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
</mxfile>
|
||||
|
After Width: | Height: | Size: 14 KiB |
@@ -14,9 +14,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -131,7 +128,7 @@ You will also need an ASGI server, for production such as <a href="https://www.u
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
5
docs/en/docs/newsletter.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# FastAPI and friends newsletter
|
||||
|
||||
<iframe class="mj-w-res-iframe" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://app.mailjet.com/widget/iframe/6gQ4/GDo" width="100%"></iframe>
|
||||
|
||||
<script type="text/javascript" src="https://app.mailjet.com/statics/js/iframeResizer.min.js"></script>
|
||||
@@ -2,8 +2,161 @@
|
||||
|
||||
## Latest Changes
|
||||
|
||||
## 0.63.0
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Improve type annotations, add support for mypy --strict, internally and for external packages. PR [#2547](https://github.com/tiangolo/fastapi/pull/2547) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Breaking changes
|
||||
|
||||
* ⬆️ Upgrade Uvicorn when installing `fastapi[all]` to the latest version including `uvloop`, the new range is `uvicorn[standard] >=0.12.0,<0.14.0`. PR [#2548](https://github.com/tiangolo/fastapi/pull/2548) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Fixes
|
||||
|
||||
* 🐛 PR [#2547](https://github.com/tiangolo/fastapi/pull/2547) (read above) also fixes some false-positive mypy errors with `callbacks` parameters and when using the `OAuth2` class.
|
||||
|
||||
### Docs
|
||||
|
||||
* 📝 Update Uvicorn installation instructions to use uvicorn[standard] (includes uvloop). PR [#2543](https://github.com/tiangolo/fastapi/pull/2543) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update title for Deta tutorial. PR [#2466](https://github.com/tiangolo/fastapi/pull/2466) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👥 Update FastAPI People. PR [#2454](https://github.com/tiangolo/fastapi/pull/2454) by [@github-actions[bot]](https://github.com/apps/github-actions).
|
||||
|
||||
### Translations
|
||||
|
||||
* 🌐 Add docs lang selector widget. PR [#2542](https://github.com/tiangolo/fastapi/pull/2542) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🌐 Add Chinese translation for Tutorial - Response Status Code. PR [#2442](https://github.com/tiangolo/fastapi/pull/2442) by [@waynerv](https://github.com/waynerv).
|
||||
* 🌐 Start translation of the documentation for the Albanian language. PR [#2516](https://github.com/tiangolo/fastapi/pull/2516) by [@vjanz](https://github.com/vjanz).
|
||||
* 🌐 Add Chinese translation for Tutorial - Extra Models. PR [#2416](https://github.com/tiangolo/fastapi/pull/2416) by [@waynerv](https://github.com/waynerv).
|
||||
* 🌐 Add Chinese translation for Tutorial - Response Model. PR [#2414](https://github.com/tiangolo/fastapi/pull/2414) by [@waynerv](https://github.com/waynerv).
|
||||
* 🌐 Add Chinese translation for Tutorial - Schema Extra Example. PR [#2411](https://github.com/tiangolo/fastapi/pull/2411) by [@maoyibo](https://github.com/maoyibo).
|
||||
* 🌐 Add Korean translation for Index. PR [#2192](https://github.com/tiangolo/fastapi/pull/2192) by [@hard-coders](https://github.com/hard-coders).
|
||||
* 🌐 Add Japanese translation for Advanced User Guide - Additional Status Codes. PR [#2145](https://github.com/tiangolo/fastapi/pull/2145) by [@Attsun1031](https://github.com/Attsun1031).
|
||||
|
||||
### Internal
|
||||
|
||||
* 🐛 Fix docs overrides directory for translations. PR [#2541](https://github.com/tiangolo/fastapi/pull/2541) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ➖ Remove Typer as a docs building dependency (covered by typer-cli) to fix pip resolver conflicts. PR [#2539](https://github.com/tiangolo/fastapi/pull/2539) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✨ Add newsletter: FastAPI and friends. PR [#2509](https://github.com/tiangolo/fastapi/pull/2509) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✨ Add new Gold Sponsor: InvestSuite 🎉. PR [#2508](https://github.com/tiangolo/fastapi/pull/2508) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Add issue template configs. PR [#2476](https://github.com/tiangolo/fastapi/pull/2476) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.62.0
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Add support for shared/top-level parameters (dependencies, tags, etc). PR [#2434](https://github.com/tiangolo/fastapi/pull/2434) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
Up to now, for several options, the only way to apply them to a group of *path operations* was in `include_router`. That works well, but the call to `app.include_router()` or `router.include_router()` is normally done in another file.
|
||||
|
||||
That means that, for example, to apply authentication to all the *path operations* in a router it would end up being done in a different file, instead of keeping related logic together.
|
||||
|
||||
Setting options in `include_router` still makes sense in some cases, for example, to override or increase configurations from a third party router included in an app. But in a router that is part of a bigger application, it would probably make more sense to add those settings when creating the `APIRouter`.
|
||||
|
||||
**In `FastAPI`**
|
||||
|
||||
This allows setting the (mostly new) parameters (additionally to the already existing parameters):
|
||||
|
||||
* `default_response_class`: updated to handle defaults in `APIRouter` and `include_router`.
|
||||
* `dependencies`: to include ✨ top-level dependencies ✨ that apply to the whole application. E.g. to add global authentication.
|
||||
* `callbacks`: OpenAPI callbacks that apply to all the *path operations*.
|
||||
* `deprecated`: to mark all the *path operations* as deprecated. 🤷
|
||||
* `include_in_schema`: to allow excluding all the *path operations* from the OpenAPI schema.
|
||||
* `responses`: OpenAPI responses that apply to all the *path operations*.
|
||||
|
||||
For example:
|
||||
|
||||
```Python
|
||||
from fastapi import FastAPI, Depends
|
||||
|
||||
|
||||
async def some_dependency():
|
||||
return
|
||||
|
||||
|
||||
app = FastAPI(dependencies=[Depends(some_dependency)])
|
||||
```
|
||||
|
||||
**In `APIRouter`**
|
||||
|
||||
This allows setting the (mostly new) parameters (additionally to the already existing parameters):
|
||||
|
||||
* `default_response_class`: updated to handle defaults in `APIRouter` and `include_router`. For example, it's not needed to set it explicitly when [creating callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
|
||||
* `dependencies`: to include ✨ router-level dependencies ✨ that apply to all the *path operations* in a router. Up to now, this was only possible with `include_router`.
|
||||
* `callbacks`: OpenAPI callbacks that apply to all the *path operations* in this router.
|
||||
* `deprecated`: to mark all the *path operations* in a router as deprecated.
|
||||
* `include_in_schema`: to allow excluding all the *path operations* in a router from the OpenAPI schema.
|
||||
* `responses`: OpenAPI responses that apply to all the *path operations* in a router.
|
||||
* `prefix`: to set the path prefix for a router. Up to now, this was only possible when calling `include_router`.
|
||||
* `tags`: OpenAPI tags to apply to all the *path operations* in this router.
|
||||
|
||||
For example:
|
||||
|
||||
```Python
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
|
||||
async def some_dependency():
|
||||
return
|
||||
|
||||
|
||||
router = APIRouter(prefix="/users", dependencies=[Depends(some_dependency)])
|
||||
```
|
||||
|
||||
**In `include_router`**
|
||||
|
||||
Most of these settings are now supported in `APIRouter`, which normally lives closer to the related code, so it is recommended to use `APIRouter` when possible.
|
||||
|
||||
But `include_router` is still useful to, for example, adding options (like `dependencies`, `prefix`, and `tags`) when including a third party router, or a generic router that is shared between several projects.
|
||||
|
||||
This PR allows setting the (mostly new) parameters (additionally to the already existing parameters):
|
||||
|
||||
* `default_response_class`: updated to handle defaults in `APIRouter` and `FastAPI`.
|
||||
* `deprecated`: to mark all the *path operations* in a router as deprecated in OpenAPI.
|
||||
* `include_in_schema`: to allow disabling all the *path operations* from showing in the OpenAPI schema.
|
||||
* `callbacks`: OpenAPI callbacks that apply to all the *path operations* in this router.
|
||||
|
||||
Note: all the previous parameters are still there, so it's still possible to declare `dependencies` in `include_router`.
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
* PR [#2434](https://github.com/tiangolo/fastapi/pull/2434) includes several improvements that shouldn't affect normal use cases, but could affect in advanced scenarios:
|
||||
* If you are testing the generated OpenAPI (you shouldn't, FastAPI already tests it extensively for you): the order for `tags` in `include_router` and *path operations* was updated for consistency, but it's a simple order change.
|
||||
* If you have advanced custom logic to access each route's `route.response_class`, or the `router.default_response_class`, or the `app.default_response_class`: the default value for `response_class` in `APIRoute` and for `default_response_class` in `APIRouter` and `FastAPI` is now a `DefaultPlaceholder` used internally to handle and solve default values and overrides. The actual response class inside the `DefaultPlaceholder` is available at `route.response_class.value`.
|
||||
|
||||
### Docs
|
||||
|
||||
* PR [#2434](https://github.com/tiangolo/fastapi/pull/2434) (above) includes new or updated docs:
|
||||
* <a href="https://fastapi.tiangolo.com/advanced/openapi-callbacks/" class="external-link" target="_blank">Advanced User Guide - OpenAPI Callbacks</a>.
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/bigger-applications/" class="external-link" target="_blank">Tutorial - Bigger Applications</a>.
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/" class="external-link" target="_blank">Tutorial - Dependencies - Dependencies in path operation decorators</a>.
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/" class="external-link" target="_blank">Tutorial - Dependencies - Global Dependencies</a>.
|
||||
|
||||
* 📝 Add FastAPI monitoring blog post to External Links. PR [#2324](https://github.com/tiangolo/fastapi/pull/2324) by [@louisguitton](https://github.com/louisguitton).
|
||||
* ✏️ Fix typo in Deta tutorial. PR [#2320](https://github.com/tiangolo/fastapi/pull/2320) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✨ Add Discord chat. PR [#2322](https://github.com/tiangolo/fastapi/pull/2322) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Fix image links for sponsors. PR [#2304](https://github.com/tiangolo/fastapi/pull/2304) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Translations
|
||||
|
||||
* 🌐 Add Japanese translation for Advanced - Custom Response. PR [#2193](https://github.com/tiangolo/fastapi/pull/2193) by [@Attsun1031](https://github.com/Attsun1031).
|
||||
* 🌐 Add Chinese translation for Benchmarks. PR [#2119](https://github.com/tiangolo/fastapi/pull/2119) by [@spaceack](https://github.com/spaceack).
|
||||
* 🌐 Add Chinese translation for Tutorial - Body - Nested Models. PR [#1609](https://github.com/tiangolo/fastapi/pull/1609) by [@waynerv](https://github.com/waynerv).
|
||||
* 🌐 Add Chinese translation for Advanced - Custom Response. PR [#1459](https://github.com/tiangolo/fastapi/pull/1459) by [@RunningIkkyu](https://github.com/RunningIkkyu).
|
||||
* 🌐 Add Chinese translation for Advanced - Return a Response Directly. PR [#1452](https://github.com/tiangolo/fastapi/pull/1452) by [@RunningIkkyu](https://github.com/RunningIkkyu).
|
||||
* 🌐 Add Chinese translation for Advanced - Additional Status Codes. PR [#1451](https://github.com/tiangolo/fastapi/pull/1451) by [@RunningIkkyu](https://github.com/RunningIkkyu).
|
||||
* 🌐 Add Chinese translation for Advanced - Path Operation Advanced Configuration. PR [#1447](https://github.com/tiangolo/fastapi/pull/1447) by [@RunningIkkyu](https://github.com/RunningIkkyu).
|
||||
* 🌐 Add Chinese translation for Advanced User Guide - Intro. PR [#1445](https://github.com/tiangolo/fastapi/pull/1445) by [@RunningIkkyu](https://github.com/RunningIkkyu).
|
||||
|
||||
### Internal
|
||||
|
||||
* 🔧 Update TestDriven link to course in sponsors section. PR [#2435](https://github.com/tiangolo/fastapi/pull/2435) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🍱 Update sponsor logos. PR [#2418](https://github.com/tiangolo/fastapi/pull/2418) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 💚 Fix disabling install of Material for MkDocs Insiders in forks, strike 1 ⚾. PR [#2340](https://github.com/tiangolo/fastapi/pull/2340) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🐛 Fix disabling Material for MkDocs Insiders install in forks. PR [#2339](https://github.com/tiangolo/fastapi/pull/2339) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✨ Add silver sponsor WeTransfer. PR [#2338](https://github.com/tiangolo/fastapi/pull/2338) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✨ Set up and enable Material for MkDocs Insiders for the docs. PR [#2325](https://github.com/tiangolo/fastapi/pull/2325) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.61.2
|
||||
|
||||
### Fixes
|
||||
|
||||
@@ -16,14 +16,18 @@ Let's say you have a file structure like this:
|
||||
├── app
|
||||
│ ├── __init__.py
|
||||
│ ├── main.py
|
||||
│ ├── dependencies.py
|
||||
│ └── routers
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── items.py
|
||||
│ │ └── users.py
|
||||
│ └── internal
|
||||
│ ├── __init__.py
|
||||
│ ├── items.py
|
||||
│ └── users.py
|
||||
│ └── admin.py
|
||||
```
|
||||
|
||||
!!! tip
|
||||
There are two `__init__.py` files: one in each directory or subdirectory.
|
||||
There are several `__init__.py` files: one in each directory or subdirectory.
|
||||
|
||||
This is what allows importing code from one file into another.
|
||||
|
||||
@@ -33,18 +37,33 @@ Let's say you have a file structure like this:
|
||||
from app.routers import items
|
||||
```
|
||||
|
||||
* The `app` directory contains everything.
|
||||
* This `app` directory has an empty file `app/__init__.py`.
|
||||
* So, the `app` directory is a "Python package" (a collection of "Python modules").
|
||||
* The `app` directory also has a `app/main.py` file.
|
||||
* As it is inside a Python package directory (because there's a file `__init__.py`), it is a "module" of that package: `app.main`.
|
||||
* There's a subdirectory `app/routers/`.
|
||||
* The subdirectory `app/routers` also has an empty file `__init__.py`.
|
||||
* So, it is a "Python subpackage".
|
||||
* The file `app/routers/items.py` is beside the `app/routers/__init__.py`.
|
||||
* So, it's a submodule: `app.routers.items`.
|
||||
* The file `app/routers/users.py` is beside the `app/routers/__init__.py`.
|
||||
* So, it's a submodule: `app.routers.users`.
|
||||
* The `app` directory contains everything. And it has an empty file `app/__init__.py`, so it is a "Python package" (a collection of "Python modules"): `app`.
|
||||
* It contains an `app/main.py` file. As it is inside a Python package (a directory with a file `__init__.py`), it is a "module" of that package: `app.main`.
|
||||
* There's also an `app/dependencies.py` file, just like `app/main.py`, it is a "module": `app.dependencies`.
|
||||
* There's a subdirectory `app/routers/` with another file `__init__.py`, so it's a "Python subpackage": `app.routers`.
|
||||
* The file `app/routers/items.py` is inside a package, `app/routers/`, so, it's a submodule: `app.routers.items`.
|
||||
* The same with `app/routers/users.py`, it's another submodule: `app.routers.users`.
|
||||
* There's also a subdirectory `app/internal/` with another file `__init__.py`, so it's another "Python subpackage": `app.internal`.
|
||||
* And the file `app/internal/admin.py` is another submodule: `app.internal.admin`.
|
||||
|
||||
<img src="/img/tutorial/bigger-applications/package.svg">
|
||||
|
||||
The same file structure with comments:
|
||||
|
||||
```
|
||||
.
|
||||
├── app # "app" is a Python package
|
||||
│ ├── __init__.py # this file makes "app" a "Python package"
|
||||
│ ├── main.py # "main" module, e.g. import app.main
|
||||
│ ├── dependencies.py # "dependencies" module, e.g. import app.dependencies
|
||||
│ └── routers # "routers" is a "Python subpackage"
|
||||
│ │ ├── __init__.py # makes "routers" a "Python subpackage"
|
||||
│ │ ├── items.py # "items" submodule, e.g. import app.routers.items
|
||||
│ │ └── users.py # "users" submodule, e.g. import app.routers.users
|
||||
│ └── internal # "internal" is a "Python subpackage"
|
||||
│ ├── __init__.py # makes "internal" a "Python subpackage"
|
||||
│ └── admin.py # "admin" submodule, e.g. import app.internal.admin
|
||||
```
|
||||
|
||||
## `APIRouter`
|
||||
|
||||
@@ -78,16 +97,33 @@ You can think of `APIRouter` as a "mini `FastAPI`" class.
|
||||
|
||||
All the same options are supported.
|
||||
|
||||
All the same parameters, responses, dependencies, tags, etc.
|
||||
All the same `parameters`, `responses`, `dependencies`, `tags`, etc.
|
||||
|
||||
!!! tip
|
||||
In this example, the variable is called `router`, but you can name it however you want.
|
||||
|
||||
We are going to include this `APIRouter` in the main `FastAPI` app, but first, let's add another `APIRouter`.
|
||||
We are going to include this `APIRouter` in the main `FastAPI` app, but first, let's check the dependencies and another `APIRouter`.
|
||||
|
||||
## Dependencies
|
||||
|
||||
We see that we are going to need some dependencies used in several places of the application.
|
||||
|
||||
So we put them in their own `dependencies` module (`app/dependencies.py`).
|
||||
|
||||
We will now use a simple dependency to read a custom `X-Token` header:
|
||||
|
||||
```Python hl_lines="1 4-6"
|
||||
{!../../../docs_src/bigger_applications/app/dependencies.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
We are using an invented header to simplify this example.
|
||||
|
||||
But in real cases you will get better results using the integrated [Security utilities](./security/index.md){.internal-link target=_blank}.
|
||||
|
||||
## Another module with `APIRouter`
|
||||
|
||||
Let's say you also have the endpoints dedicated to handling "Items" from your application in the module at `app/routers/items.py`.
|
||||
Let's say you also have the endpoints dedicated to handling "items" from your application in the module at `app/routers/items.py`.
|
||||
|
||||
You have *path operations* for:
|
||||
|
||||
@@ -96,24 +132,148 @@ You have *path operations* for:
|
||||
|
||||
It's all the same structure as with `app/routers/users.py`.
|
||||
|
||||
But let's say that this time we are more lazy.
|
||||
But we want to be smarter and simplify the code a bit.
|
||||
|
||||
And we don't want to have to explicitly type `/items/` and `tags=["items"]` in every *path operation* (we will be able to do it later):
|
||||
We know all the *path operations* in this module have the same:
|
||||
|
||||
```Python hl_lines="6 11"
|
||||
* Path `prefix`: `/items`.
|
||||
* `tags`: (just one tag: `items`).
|
||||
* Extra `responses`.
|
||||
* `dependencies`: they all need that `X-Token` dependency we created.
|
||||
|
||||
So, instead of adding all that to each *path operation*, we can add it to the `APIRouter`.
|
||||
|
||||
```Python hl_lines="5-10 16 21"
|
||||
{!../../../docs_src/bigger_applications/app/routers/items.py!}
|
||||
```
|
||||
|
||||
As the path of each *path operation* has to start with `/`, like in:
|
||||
|
||||
```Python hl_lines="1"
|
||||
@router.get("/{item_id}")
|
||||
async def read_item(item_id: str):
|
||||
...
|
||||
```
|
||||
|
||||
...the prefix must not include a final `/`.
|
||||
|
||||
So, the prefix in this case is `/items`.
|
||||
|
||||
We can also add a list of `tags` and extra `responses` that will be applied to all the *path operations* included in this router.
|
||||
|
||||
And we can add a list of `dependencies` that will be added to all the *path operations* in the router and will be executed/solved for each request made to them.
|
||||
|
||||
!!! tip
|
||||
Note that, much like [dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, no value will be passed to your *path operation function*.
|
||||
|
||||
The end result is that the item paths are now:
|
||||
|
||||
* `/items/`
|
||||
* `/items/{item_id}`
|
||||
|
||||
...as we intended.
|
||||
|
||||
* They will be marked with a list of tags that contain a single string `"items"`.
|
||||
* These "tags" are especially useful for the automatic interactive documentation systems (using OpenAPI).
|
||||
* All of them will include the predefined `responses`.
|
||||
* All these *path operations* will have the list of `dependencies` evaluated/executed before them.
|
||||
* If you also declare dependencies in a specific *path operation*, **they will be executed too**.
|
||||
* The router dependencies are executed first, then the [`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, and then the normal parameter dependencies.
|
||||
* You can also add [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.
|
||||
|
||||
!!! tip
|
||||
Having `dependencies` in the `APIRouter` can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them.
|
||||
|
||||
!!! check
|
||||
The `prefix`, `tags`, `responses`, and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication.
|
||||
|
||||
### Import the dependencies
|
||||
|
||||
This codes lives in the module `app.routers.items`, the file `app/routers/items.py`.
|
||||
|
||||
And we need to get the dependency function from the module `app.dependencies`, the file `app/dependencies.py`.
|
||||
|
||||
So we use a relative import with `..` for the dependencies:
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!../../../docs_src/bigger_applications/app/routers/items.py!}
|
||||
```
|
||||
|
||||
#### How relative imports work
|
||||
|
||||
!!! tip
|
||||
If you know perfectly how imports work, continue to the next section below.
|
||||
|
||||
A single dot `.`, like in:
|
||||
|
||||
```Python
|
||||
from .dependencies import get_token_header
|
||||
```
|
||||
|
||||
would mean:
|
||||
|
||||
* Starting in the same package that this module (the file `app/routers/items.py`) lives in (the directory `app/routers/`)...
|
||||
* find the module `dependencies` (an imaginary file at `app/routers/dependencies.py`)...
|
||||
* and from it, import the function `get_token_header`.
|
||||
|
||||
But that file doesn't exist, our dependencies are in a file at `app/dependencies.py`.
|
||||
|
||||
Remember how our app/file structure looks like:
|
||||
|
||||
<img src="/img/tutorial/bigger-applications/package.svg">
|
||||
|
||||
---
|
||||
|
||||
The two dots `..`, like in:
|
||||
|
||||
```Python
|
||||
from ..dependencies import get_token_header
|
||||
```
|
||||
|
||||
mean:
|
||||
|
||||
* Starting in the same package that this module (the file `app/routers/items.py`) lives in (the directory `app/routers/`)...
|
||||
* go to the parent package (the directory `app/`)...
|
||||
* and in there, find the module `dependencies` (the file at `app/routers/dependencies.py`)...
|
||||
* and from it, import the function `get_token_header`.
|
||||
|
||||
That works correctly! 🎉
|
||||
|
||||
---
|
||||
|
||||
The same way, if we had used three dots `...`, like in:
|
||||
|
||||
```Python
|
||||
from ...dependencies import get_token_header
|
||||
```
|
||||
|
||||
that would mean:
|
||||
|
||||
* Starting in the same package that this module (the file `app/routers/items.py`) lives in (the directory `app/routers/`)...
|
||||
* go to the parent package (the directory `app/`)...
|
||||
* then go to the parent of that package (there's no parent package, `app` is the top level 😱)...
|
||||
* and in there, find the module `dependencies` (the file at `app/routers/dependencies.py`)...
|
||||
* and from it, import the function `get_token_header`.
|
||||
|
||||
That would refer to some package above `app/`, with its own file `__init__.py`, etc. But we don't have that. So, that would throw an error in our example. 🚨
|
||||
|
||||
But now you know how it works, so you can use relative imports in your own apps no matter how complex they are. 🤓
|
||||
|
||||
### Add some custom `tags`, `responses`, and `dependencies`
|
||||
|
||||
We are not adding the prefix `/items/` nor the `tags=["items"]` to add them later.
|
||||
We are not adding the prefix `/items` nor the `tags=["items"]` to each *path operation* because we added them to the `APIRouter`.
|
||||
|
||||
But we can add custom `tags` and `responses` that will be applied to a specific *path operation*:
|
||||
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="18-19"
|
||||
```Python hl_lines="30-31"
|
||||
{!../../../docs_src/bigger_applications/app/routers/items.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
This last path operation will have the combination of tags: `["items", "custom"]`.
|
||||
|
||||
And it will also have both responses in the documentation, one for `404` and one for `403`.
|
||||
|
||||
## The main `FastAPI`
|
||||
|
||||
Now, let's see the module at `app/main.py`.
|
||||
@@ -122,25 +282,27 @@ Here's where you import and use the class `FastAPI`.
|
||||
|
||||
This will be the main file in your application that ties everything together.
|
||||
|
||||
And as most of your logic will now live in its own specific module, the main file will be quite simple.
|
||||
|
||||
### Import `FastAPI`
|
||||
|
||||
You import and create a `FastAPI` class as normally:
|
||||
You import and create a `FastAPI` class as normally.
|
||||
|
||||
```Python hl_lines="1 5"
|
||||
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"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
### Import the `APIRouter`
|
||||
|
||||
But this time we are not adding *path operations* directly with the `FastAPI` `app`.
|
||||
Now we import the other submodules that have `APIRouter`s:
|
||||
|
||||
We import the other submodules that have `APIRouter`s:
|
||||
|
||||
```Python hl_lines="3"
|
||||
```Python hl_lines="5"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
As the file `app/routers/items.py` is part of the same Python package, we can import it using "dot notation".
|
||||
As the files `app/routers/users.py` and `app/routers/items.py` are submodules that are part of the same Python package `app`, we can use a single dot `.` to import them using "relative imports".
|
||||
|
||||
### How the importing works
|
||||
|
||||
@@ -156,7 +318,9 @@ Means:
|
||||
* look for the subpackage `routers` (the directory at `app/routers/`)...
|
||||
* and from it, import the submodule `items` (the file at `app/routers/items.py`) and `users` (the file at `app/routers/users.py`)...
|
||||
|
||||
The module `items` will have a variable `router` (`items.router`). This is the same one we created in the file `app/routers/items.py`. It's an `APIRouter`. The same for the module `users`.
|
||||
The module `items` will have a variable `router` (`items.router`). This is the same one we created in the file `app/routers/items.py`, it's an `APIRouter` object.
|
||||
|
||||
And then we do the same for the module `users`.
|
||||
|
||||
We could also import them like:
|
||||
|
||||
@@ -165,9 +329,17 @@ from app.routers import items, users
|
||||
```
|
||||
|
||||
!!! info
|
||||
The first version is a "relative import".
|
||||
The first version is a "relative import":
|
||||
|
||||
The second version is an "absolute import".
|
||||
```Python
|
||||
from .routers import items, users
|
||||
```
|
||||
|
||||
The second version is an "absolute import":
|
||||
|
||||
```Python
|
||||
from app.routers import items, users
|
||||
```
|
||||
|
||||
To learn more about Python Packages and Modules, read <a href="https://docs.python.org/3/tutorial/modules.html" class="external-link" target="_blank">the official Python documentation about Modules</a>.
|
||||
|
||||
@@ -188,22 +360,24 @@ 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="3"
|
||||
```Python hl_lines="4"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
### Include an `APIRouter`
|
||||
### Include the `APIRouter`s for `users` and `items`
|
||||
|
||||
Now, let's include the `router` from the submodule `users`:
|
||||
Now, let's include the `router`s from the submodules `users` and `items`:
|
||||
|
||||
```Python hl_lines="13"
|
||||
```Python hl_lines="10-11"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
`users.router` contains the `APIRouter` inside of the file `app/routers/users.py`.
|
||||
|
||||
With `app.include_router()` we can add an `APIRouter` to the main `FastAPI` application.
|
||||
And `items.router` contains the `APIRouter` inside of the file `app/routers/items.py`.
|
||||
|
||||
With `app.include_router()` we can add each `APIRouter` to the main `FastAPI` application.
|
||||
|
||||
It will include all the routes from that router as part of it.
|
||||
|
||||
@@ -217,67 +391,52 @@ It will include all the routes from that router as part of it.
|
||||
|
||||
This will take microseconds and will only happen at startup.
|
||||
|
||||
So it won't affect performance.
|
||||
So it won't affect performance. ⚡
|
||||
|
||||
### Include an `APIRouter` with a `prefix`, `tags`, `responses`, and `dependencies`
|
||||
### Include an `APIRouter` with a custom `prefix`, `tags`, `responses`, and `dependencies`
|
||||
|
||||
Now, let's include the router from the `items` submodule.
|
||||
Now, let's imagine your organization gave you the `app/internal/admin.py` file.
|
||||
|
||||
But, remember that we were lazy and didn't add `/items/` nor `tags` to all the *path operations*?
|
||||
It contains an `APIRouter` with some admin *path operations* that your organization shares between several projects.
|
||||
|
||||
We can add a prefix to all the *path operations* using the parameter `prefix` of `app.include_router()`.
|
||||
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`:
|
||||
|
||||
As the path of each *path operation* has to start with `/`, like in:
|
||||
|
||||
```Python hl_lines="1"
|
||||
@router.get("/{item_id}")
|
||||
async def read_item(item_id: str):
|
||||
...
|
||||
```Python hl_lines="3"
|
||||
{!../../../docs_src/bigger_applications/app/internal/admin.py!}
|
||||
```
|
||||
|
||||
...the prefix must not include a final `/`.
|
||||
But we still want to set a custom `prefix` when including the `APIRouter` so that all its *path operations* start with `/admin`, we want to secure it with the `dependencies` we already have for this project, and we want to include `tags` and `responses`.
|
||||
|
||||
So, the prefix in this case would be `/items`.
|
||||
We can declare all that without having to modify the original `APIRouter` by passing those parameters to `app.include_router()`:
|
||||
|
||||
We can also add a list of `tags` that will be applied to all the *path operations* included in this router.
|
||||
|
||||
And we can add predefined `responses` that will be included in all the *path operations* too.
|
||||
|
||||
And we can add a list of `dependencies` that will be added to all the *path operations* in the router and will be executed/solved for each request made to them. Note that, much like dependencies in *path operation decorators*, no value will be passed to your *path operation function*.
|
||||
|
||||
```Python hl_lines="8-10 14-20"
|
||||
```Python hl_lines="14-17"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
The end result is that the item paths are now:
|
||||
That way, the original `APIRouter` will keep unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization.
|
||||
|
||||
* `/items/`
|
||||
* `/items/{item_id}`
|
||||
The result is that in our app, each of the *path operations* from the `admin` module will have:
|
||||
|
||||
...as we intended.
|
||||
* The prefix `/admin`.
|
||||
* The tag `admin`.
|
||||
* The dependency `get_token_header`.
|
||||
* The response `418`. 🍵
|
||||
|
||||
* They will be marked with a list of tags that contain a single string `"items"`.
|
||||
* The *path operation* that declared a `"custom"` tag will have both tags, `items` and `custom`.
|
||||
* These "tags" are especially useful for the automatic interactive documentation systems (using OpenAPI).
|
||||
* All of them will include the predefined `responses`.
|
||||
* The *path operation* that declared a custom `403` response will have both the predefined responses (`404`) and the `403` declared in it directly.
|
||||
* All these *path operations* will have the list of `dependencies` evaluated/executed before them.
|
||||
* If you also declare dependencies in a specific *path operation*, **they will be executed too**.
|
||||
* The router dependencies are executed first, then the [`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, and then the normal parameter dependencies.
|
||||
* You can also add [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.
|
||||
But that will only affect that `APIRouter` in our app, not in any other code that uses it.
|
||||
|
||||
!!! tip
|
||||
Having `dependencies` in a decorator can be used, for example, to require authentication for a whole group of *path operations*. Even if the dependencies are not added individually to each one of them.
|
||||
So, for example, other projects could use the same `APIRouter` with a different authentication method.
|
||||
|
||||
!!! check
|
||||
The `prefix`, `tags`, `responses` and `dependencies` parameters are (as in many other cases) just a feature from **FastAPI** to help you avoid code duplication.
|
||||
### Include a *path operation*
|
||||
|
||||
!!! tip
|
||||
You could also add *path operations* directly, for example with: `@app.get(...)`.
|
||||
We can also add *path operations* directly to the `FastAPI` app.
|
||||
|
||||
Apart from `app.include_router()`, in the same **FastAPI** app.
|
||||
Here we do it... just to show that we can 🤷:
|
||||
|
||||
It would still work the same.
|
||||
```Python hl_lines="21-23"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
and it will work correctly, together with all the other *path operations* added with `app.include_router()`.
|
||||
|
||||
!!! info "Very Technical Details"
|
||||
**Note**: this is a very technical detail that you probably can **just skip**.
|
||||
@@ -317,3 +476,13 @@ You can also use `.include_router()` multiple times with the *same* router using
|
||||
This could be useful, for example, to expose the same API under different prefixes, e.g. `/api/v1` and `/api/latest`.
|
||||
|
||||
This is an advanced usage that you might not really need, but it's there in case you do.
|
||||
|
||||
## Include an `APIRouter` in another
|
||||
|
||||
The same way you can include an `APIRouter` in a `FastAPI` application, you can include an `APIRouter` in another `APIRouter` using:
|
||||
|
||||
```Python
|
||||
router.include_router(other_router)
|
||||
```
|
||||
|
||||
Make sure you do it before including `router` in the `FastAPI` app, so that the *path operations* from `other_router` are also included.
|
||||
|
||||
@@ -27,6 +27,11 @@ These dependencies will be executed/solved the same way normal dependencies. But
|
||||
|
||||
It might also help avoid confusion for new developers that see an unused parameter in your code and could think it's unnecessary.
|
||||
|
||||
!!! info
|
||||
In this example we use invented custom headers `X-Key` and `X-Token`.
|
||||
|
||||
But in real cases, when implementing security, you would get more benefits from using the integrated [Security utilities (the next chapter)](../security/index.md){.internal-link target=_blank}.
|
||||
|
||||
## Dependencies errors and return values
|
||||
|
||||
You can use the same dependency *functions* you use normally.
|
||||
@@ -60,3 +65,7 @@ So, you can re-use a normal dependency (that returns a value) you already use so
|
||||
## Dependencies for a group of *path operations*
|
||||
|
||||
Later, when reading about how to structure bigger applications ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possibly with multiple files, you will learn how to declare a single `dependencies` parameter for a group of *path operations*.
|
||||
|
||||
## Global Dependencies
|
||||
|
||||
Next we will see how to add dependencies to the whole `FastAPI` application, so that they apply to each *path operation*.
|
||||
|
||||
17
docs/en/docs/tutorial/dependencies/global-dependencies.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Global Dependencies
|
||||
|
||||
For some types of applications you might want to add dependencies to the whole application.
|
||||
|
||||
Similar to the way you can [add `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, you can add them to the `FastAPI` application.
|
||||
|
||||
In that case, they will be applied to all the *path operations* in the application:
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!../../../docs_src/dependencies/tutorial012.py!}
|
||||
```
|
||||
|
||||
And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app.
|
||||
|
||||
## Dependencies for groups of *path operations*
|
||||
|
||||
Later, when reading about how to structure bigger applications ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possibly with multiple files, you will learn how to declare a single `dependencies` parameter for a group of *path operations*.
|
||||
@@ -64,7 +64,7 @@ $ pip install fastapi[all]
|
||||
Also install `uvicorn` to work as the server:
|
||||
|
||||
```
|
||||
pip install uvicorn
|
||||
pip install uvicorn[standard]
|
||||
```
|
||||
|
||||
And the same for each of the optional dependencies that you want to use.
|
||||
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -69,6 +83,7 @@ nav:
|
||||
- tutorial/dependencies/classes-as-dependencies.md
|
||||
- tutorial/dependencies/sub-dependencies.md
|
||||
- tutorial/dependencies/dependencies-in-path-operation-decorators.md
|
||||
- tutorial/dependencies/global-dependencies.md
|
||||
- tutorial/dependencies/dependencies-with-yield.md
|
||||
- Security:
|
||||
- tutorial/security/index.md
|
||||
@@ -168,6 +183,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- css/termynal.css
|
||||
- css/custom.css
|
||||
@@ -175,5 +215,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- js/termynal.js
|
||||
- js/custom.js
|
||||
- js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
9
docs/en/overrides/main.html
Normal file
@@ -0,0 +1,9 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block announce %}
|
||||
<a class="announce" href="https://fastapi.tiangolo.com/newsletter/">
|
||||
<span class="twemoji">
|
||||
{% include ".icons/material/email.svg" %}
|
||||
</span> Subscribe to the <strong>FastAPI and friends</strong> newsletter 🎉
|
||||
</a>
|
||||
{% endblock %}
|
||||
@@ -14,9 +14,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -130,7 +127,7 @@ También vas a necesitar un servidor ASGI para producción cómo <a href="https:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -64,7 +64,7 @@ $ pip install fastapi[all]
|
||||
También debes instalar `uvicorn` para que funcione como tu servidor:
|
||||
|
||||
```
|
||||
pip install uvicorn
|
||||
pip install uvicorn[standard]
|
||||
```
|
||||
|
||||
Y lo mismo para cada una de las dependencias opcionales que quieras utilizar.
|
||||
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/es/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -73,6 +87,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
@@ -80,5 +119,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
- https://fastapi.tiangolo.com/js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
0
docs/es/overrides/.gitignore
vendored
Normal file
@@ -18,9 +18,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -135,7 +132,7 @@ You will also need an ASGI server, for production such as <a href="https://www.u
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/fr/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -66,6 +80,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
@@ -73,5 +112,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
- https://fastapi.tiangolo.com/js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
0
docs/fr/overrides/.gitignore
vendored
Normal file
@@ -18,9 +18,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://badge.fury.io/py/fastapi.svg" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -135,7 +132,7 @@ You will also need an ASGI server, for production such as <a href="https://www.u
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/it/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -66,6 +80,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
@@ -73,5 +112,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
- https://fastapi.tiangolo.com/js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
0
docs/it/overrides/.gitignore
vendored
Normal file
37
docs/ja/docs/advanced/additional-status-codes.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# 追加のステータスコード
|
||||
|
||||
デフォルトでは、 **FastAPI** は `JSONResponse` を使ってレスポンスを返します。その `JSONResponse` の中には、 *path operation* が返した内容が入ります。
|
||||
|
||||
それは、デフォルトのステータスコードか、 *path operation* でセットしたものを利用します。
|
||||
|
||||
## 追加のステータスコード
|
||||
|
||||
メインのステータスコードとは別に、他のステータスコードを返したい場合は、`Response` (`JSONResponse` など) に追加のステータスコードを設定して直接返します。
|
||||
|
||||
例えば、itemを更新し、成功した場合は200 "OK"のHTTPステータスコードを返す *path operation* を作りたいとします。
|
||||
|
||||
しかし、新しいitemも許可したいです。itemが存在しない場合は、それらを作成して201 "Created"を返します。
|
||||
|
||||
これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。
|
||||
|
||||
```Python hl_lines="4 23"
|
||||
{!../../../docs_src/additional_status_codes/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! warning "注意"
|
||||
上記の例のように `Response` を明示的に返す場合、それは直接返されます。
|
||||
|
||||
モデルなどはシリアライズされません。
|
||||
|
||||
必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。
|
||||
|
||||
!!! note "技術詳細"
|
||||
`from starlette.responses import JSONResponse` を利用することもできます。
|
||||
|
||||
**FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。
|
||||
|
||||
## OpenAPIとAPIドキュメント
|
||||
|
||||
ステータスコードとレスポンスを直接返す場合、それらはOpenAPIスキーマ (APIドキュメント) には含まれません。なぜなら、FastAPIは何が返されるのか事前に知ることができないからです。
|
||||
|
||||
しかし、 [Additional Responses](additional-responses.md){.internal-link target=_blank} を使ってコードの中にドキュメントを書くことができます。
|
||||
223
docs/ja/docs/advanced/custom-response.md
Normal file
@@ -0,0 +1,223 @@
|
||||
# カスタムレスポンス - HTML、ストリーム、ファイル、その他のレスポンス
|
||||
|
||||
デフォルトでは、**FastAPI** は `JSONResponse` を使ってレスポンスを返します。
|
||||
|
||||
[レスポンスを直接返す](response-directly.md){.internal-link target=_blank}で見たように、 `Response` を直接返すことでこの挙動をオーバーライドできます。
|
||||
|
||||
しかし、`Response` を直接返すと、データは自動的に変換されず、ドキュメントも自動生成されません (例えば、生成されるOpenAPIの一部としてHTTPヘッダー `Content-Type` に特定の「メディアタイプ」を含めるなど) 。
|
||||
|
||||
しかし、*path operationデコレータ* に、使いたい `Response` を宣言することもできます。
|
||||
|
||||
*path operation関数* から返されるコンテンツは、その `Response` に含まれます。
|
||||
|
||||
そしてもし、`Response` が、`JSONResponse` や `UJSONResponse` の場合のようにJSONメディアタイプ (`application/json`) ならば、データは *path operationデコレータ* に宣言したPydantic `response_model` により自動的に変換 (もしくはフィルタ) されます。
|
||||
|
||||
!!! note "備考"
|
||||
メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。
|
||||
|
||||
## `ORJSONResponse` を使う
|
||||
|
||||
例えば、パフォーマンスを出したい場合は、<a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a>をインストールし、`ORJSONResponse`をレスポンスとしてセットすることができます。
|
||||
|
||||
使いたい `Response` クラス (サブクラス) をインポートし、 *path operationデコレータ* に宣言します。
|
||||
|
||||
```Python hl_lines="2 7"
|
||||
{!../../../docs_src/custom_response/tutorial001b.py!}
|
||||
```
|
||||
|
||||
!!! info "情報"
|
||||
パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。
|
||||
|
||||
この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。
|
||||
|
||||
そして、OpenAPIにはそのようにドキュメントされます。
|
||||
|
||||
!!! tip "豆知識"
|
||||
`ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。
|
||||
|
||||
## HTMLレスポンス
|
||||
|
||||
**FastAPI** からHTMLを直接返す場合は、`HTMLResponse` を使います。
|
||||
|
||||
* `HTMLResponse` をインポートする。
|
||||
* *path operation* のパラメータ `content_type` に `HTMLResponse` を渡す。
|
||||
|
||||
```Python hl_lines="2 7"
|
||||
{!../../../docs_src/custom_response/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! info "情報"
|
||||
パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。
|
||||
|
||||
この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。
|
||||
|
||||
そして、OpenAPIにはそのようにドキュメント化されます。
|
||||
|
||||
### `Response` を返す
|
||||
|
||||
[レスポンスを直接返す](response-directly.md){.internal-link target=_blank}で見たように、レスポンスを直接返すことで、*path operation* の中でレスポンスをオーバーライドできます。
|
||||
|
||||
上記と同じ例において、 `HTMLResponse` を返すと、このようになります:
|
||||
|
||||
```Python hl_lines="2 7 19"
|
||||
{!../../../docs_src/custom_response/tutorial003.py!}
|
||||
```
|
||||
|
||||
!!! warning "注意"
|
||||
*path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。
|
||||
|
||||
!!! info "情報"
|
||||
もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。
|
||||
|
||||
### OpenAPIドキュメントと `Response` のオーバーライド
|
||||
|
||||
関数の中でレスポンスをオーバーライドしつつも、OpenAPI に「メディアタイプ」をドキュメント化したいなら、 `response_class` パラメータを使い、 `Response` オブジェクトを返します。
|
||||
|
||||
`response_class` はOpenAPIの *path operation* ドキュメントにのみ使用されますが、 `Response` はそのまま使用されます。
|
||||
|
||||
#### `HTMLResponse` を直接返す
|
||||
|
||||
例えば、このようになります:
|
||||
|
||||
```Python hl_lines="7 21 23"
|
||||
{!../../../docs_src/custom_response/tutorial004.py!}
|
||||
```
|
||||
|
||||
この例では、関数 `generate_html_response()` は、`str` のHTMLを返すのではなく `Response` を生成して返しています。
|
||||
|
||||
`generate_html_response()` を呼び出した結果を返すことにより、**FastAPI** の振る舞いを上書きする `Response` が既に返されています。
|
||||
|
||||
しかし、一方では `response_class` に `HTMLResponse` を渡しているため、 **FastAPI** はOpenAPIや対話的ドキュメントでHTMLとして `text/html` でドキュメント化する方法を知っています。
|
||||
|
||||
<img src="/img/tutorial/custom-response/image01.png">
|
||||
|
||||
## 利用可能なレスポンス
|
||||
|
||||
以下が利用可能なレスポンスの一部です。
|
||||
|
||||
`Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。
|
||||
|
||||
!!! note "技術詳細"
|
||||
`from starlette.responses import HTMLResponse` も利用できます。
|
||||
|
||||
**FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
|
||||
|
||||
### `Response`
|
||||
|
||||
メインの `Response` クラスで、他の全てのレスポンスはこれを継承しています。
|
||||
|
||||
直接返すことができます。
|
||||
|
||||
以下のパラメータを受け付けます。
|
||||
|
||||
* `content` - `str` か `bytes`。
|
||||
* `status_code` - `int` のHTTPステータスコード。
|
||||
* `headers` - 文字列の `dict` 。
|
||||
* `media_type` - メディアタイプを示す `str` 。例えば `"text/html"` 。
|
||||
|
||||
FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含みます。また、media_typeに基づいたContent-Typeヘッダーを含み、テキストタイプのためにcharsetを追加します。
|
||||
|
||||
```Python hl_lines="1 18"
|
||||
{!../../../docs_src/response_directly/tutorial002.py!}
|
||||
```
|
||||
|
||||
### `HTMLResponse`
|
||||
|
||||
上で読んだように、テキストやバイトを受け取り、HTMLレスポンスを返します。
|
||||
|
||||
### `PlainTextResponse`
|
||||
|
||||
テキストやバイトを受け取り、プレーンテキストのレスポンスを返します。
|
||||
|
||||
```Python hl_lines="2 7 9"
|
||||
{!../../../docs_src/custom_response/tutorial005.py!}
|
||||
```
|
||||
|
||||
### `JSONResponse`
|
||||
|
||||
データを受け取り、 `application/json` としてエンコードされたレスポンスを返します。
|
||||
|
||||
上で読んだように、**FastAPI** のデフォルトのレスポンスとして利用されます。
|
||||
|
||||
### `ORJSONResponse`
|
||||
|
||||
上で読んだように、<a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a>を使った、高速な代替のJSONレスポンスです。
|
||||
|
||||
### `UJSONResponse`
|
||||
|
||||
<a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>を使った、代替のJSONレスポンスです。
|
||||
|
||||
!!! warning "注意"
|
||||
`ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。
|
||||
|
||||
```Python hl_lines="2 7"
|
||||
{!../../../docs_src/custom_response/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! tip "豆知識"
|
||||
`ORJSONResponse` のほうが高速な代替かもしれません。
|
||||
|
||||
### `RedirectResponse`
|
||||
|
||||
HTTPリダイレクトを返します。デフォルトでは307ステータスコード (Temporary Redirect) となります。
|
||||
|
||||
```Python hl_lines="2 9"
|
||||
{!../../../docs_src/custom_response/tutorial006.py!}
|
||||
```
|
||||
|
||||
### `StreamingResponse`
|
||||
|
||||
非同期なジェネレータか通常のジェネレータ・イテレータを受け取り、レスポンスボディをストリームします。
|
||||
|
||||
```Python hl_lines="2 14"
|
||||
{!../../../docs_src/custom_response/tutorial007.py!}
|
||||
```
|
||||
|
||||
#### `StreamingResponse` をファイルライクなオブジェクトとともに使う
|
||||
|
||||
ファイルライクなオブジェクト (例えば、 `open()` で返されたオブジェクト) がある場合、 `StreamingResponse` に含めて返すことができます。
|
||||
|
||||
これにはクラウドストレージとの連携や映像処理など、多くのライブラリが含まれています。
|
||||
|
||||
```Python hl_lines="2 10-11"
|
||||
{!../../../docs_src/custom_response/tutorial008.py!}
|
||||
```
|
||||
|
||||
!!! tip "豆知識"
|
||||
ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。
|
||||
|
||||
### `FileResponse`
|
||||
|
||||
レスポンスとしてファイルを非同期的にストリームします。
|
||||
|
||||
他のレスポンスタイプとは異なる引数のセットを受け取りインスタンス化します。
|
||||
|
||||
* `path` - ストリームするファイルのファイルパス。
|
||||
* `headers` - 含めたい任意のカスタムヘッダーの辞書。
|
||||
* `media_type` - メディアタイプを示す文字列。セットされなかった場合は、ファイル名やパスからメディアタイプが推察されます。
|
||||
* `filename` - セットされた場合、レスポンスの `Content-Disposition` に含まれます。
|
||||
|
||||
ファイルレスポンスには、適切な `Content-Length` 、 `Last-Modified` 、 `ETag` ヘッダーが含まれます。
|
||||
|
||||
```Python hl_lines="2 10"
|
||||
{!../../../docs_src/custom_response/tutorial009.py!}
|
||||
```
|
||||
|
||||
## デフォルトレスポンスクラス
|
||||
|
||||
**FastAPI** クラスのインスタンスか `APIRouter` を生成するときに、デフォルトのレスポンスクラスを指定できます。
|
||||
|
||||
定義するためのパラメータは、 `default_response_class` です。
|
||||
|
||||
以下の例では、 **FastAPI** は、全ての *path operation* で `JSONResponse` の代わりに `ORJSONResponse` をデフォルトとして利用します。
|
||||
|
||||
```Python hl_lines="2 4"
|
||||
{!../../../docs_src/custom_response/tutorial010.py!}
|
||||
```
|
||||
|
||||
!!! tip "豆知識"
|
||||
前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。
|
||||
|
||||
## その他のドキュメント
|
||||
|
||||
また、OpenAPIでは `responses` を使ってメディアタイプやその他の詳細を宣言することもできます: [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}
|
||||
@@ -84,10 +84,6 @@ GitHubレポジトリで<a href="https://github.com/tiangolo/fastapi/issues/new/
|
||||
|
||||
## チャットに参加
|
||||
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
|
||||
Gitterでチャットに参加: <a href="https://gitter.im/tiangolo/fastapi" class="external-link" target="_blank">https://gitter.im/tiangolo/fastapi</a>.
|
||||
|
||||
そこで、他の人と手早く会話したり、手助けやアイデアの共有などができます。
|
||||
|
||||
@@ -14,9 +14,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://badge.fury.io/py/fastapi.svg" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -131,7 +128,7 @@ $ pip install fastapi
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -64,7 +64,7 @@ $ pip install fastapi[all]
|
||||
また、サーバーとして動作するように`uvicorn` をインストールします:
|
||||
|
||||
```
|
||||
pip install uvicorn
|
||||
pip install uvicorn[standard]
|
||||
```
|
||||
|
||||
そして、使用したい依存関係をそれぞれ同様にインストールします。
|
||||
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/ja/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -45,11 +59,13 @@ nav:
|
||||
- tutorial/body.md
|
||||
- tutorial/query-params-str-validations.md
|
||||
- tutorial/header-params.md
|
||||
- tutorial/cors.md
|
||||
- セキュリティ:
|
||||
- tutorial/security/first-steps.md
|
||||
- tutorial/cors.md
|
||||
- 高度なユーザーガイド:
|
||||
- advanced/additional-status-codes.md
|
||||
- advanced/response-directly.md
|
||||
- advanced/custom-response.md
|
||||
- project-generation.md
|
||||
- alternatives.md
|
||||
- history-design-future.md
|
||||
@@ -86,6 +102,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
@@ -93,5 +134,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
- https://fastapi.tiangolo.com/js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
0
docs/ja/overrides/.gitignore
vendored
Normal file
@@ -1,12 +1,8 @@
|
||||
|
||||
{!../../../docs/missing-translation.md!}
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<em>FastAPI framework, high performance, easy to learn, fast to code, ready for production</em>
|
||||
<em>FastAPI 프레임워크, 고성능, 간편한 학습, 빠른 코드 작성, 준비된 프로덕션</em>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank">
|
||||
@@ -18,36 +14,33 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
**Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
|
||||
**문서**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
|
||||
|
||||
**Source Code**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
|
||||
**소스 코드**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
|
||||
|
||||
---
|
||||
|
||||
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
|
||||
FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.6+의 API를 빌드하기 위한 웹 프레임워크입니다.
|
||||
|
||||
The key features are:
|
||||
주요 특징으로:
|
||||
|
||||
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
|
||||
* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#performance).
|
||||
|
||||
* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
|
||||
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
|
||||
* **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
|
||||
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
|
||||
* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
|
||||
* **Robust**: Get production-ready code. With automatic interactive documentation.
|
||||
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="http://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
|
||||
* **빠른 코드 작성**: 약 200%에서 300%까지 기능 개발 속도 증가. *
|
||||
* **적은 버그**: 사람(개발자)에 의한 에러 약 40% 감소. *
|
||||
* **직관적**: 훌륭한 편집기 지원. 모든 곳에서 <abbr title="also known as auto-complete, autocompletion, IntelliSense">자동완성</abbr>. 적은 디버깅 시간.
|
||||
* **쉬움**: 쉽게 사용하고 배우도록 설계. 적은 문서 읽기 시간.
|
||||
* **짧음**: 코드 중복 최소화. 각 매개변수 선언의 여러 기능. 적은 버그.
|
||||
* **견고함**: 준비된 프로덕션 용 코드를 얻으세요. 자동 대화형 문서와 함께.
|
||||
* **표준 기반**: API에 대한 (완전히 호환되는) 개방형 표준 기반: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (이전에 Swagger로 알려졌던) 및 <a href="http://json-schema.org/" class="external-link" target="_blank">JSON 스키마</a>.
|
||||
|
||||
<small>* estimation based on tests on an internal development team, building production applications.</small>
|
||||
<small>* 내부 개발팀의 프로덕션 애플리케이션을 빌드한 테스트에 근거한 측정</small>
|
||||
|
||||
## Gold Sponsors
|
||||
## 골드 스폰서
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
@@ -59,66 +52,66 @@ The key features are:
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">Other sponsors</a>
|
||||
<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">다른 스폰서</a>
|
||||
|
||||
## Opinions
|
||||
## 의견들
|
||||
|
||||
"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
|
||||
"_[...] 저는 요즘 **FastAPI**를 많이 사용하고 있습니다. [...] 사실 우리 팀의 **마이크로소프트 ML 서비스** 전부를 바꿀 계획입니다. 그중 일부는 핵심 **Windows**와 몇몇의 **Office** 제품들이 통합되고 있습니다._"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div>
|
||||
<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>마이크로소프트</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
|
||||
"_**FastAPI** 라이브러리를 채택하여 **예측**을 얻기 위해 쿼리를 실행 할 수 있는 **REST** 서버를 생성했습니다. [Ludwig을 위해]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div>
|
||||
<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin 그리고 Sai Sumanth Miryala - <strong>우버</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
|
||||
"_**Netflix**는 우리의 오픈 소스 배포판인 **위기 관리** 오케스트레이션 프레임워크를 발표할 수 있어 기쁩니다: 바로 **Dispatch**입니다! [**FastAPI**로 빌드]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Kevin Glisson, Marc Vilanova, Forest Monsen - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target="_blank"><small>(ref)</small></a></div>
|
||||
<div style="text-align: right; margin-right: 10%;">Kevin Glisson, Marc Vilanova, Forest Monsen - <strong>넷플릭스</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_I’m over the moon excited about **FastAPI**. It’s so fun!_"
|
||||
"_**FastAPI**가 너무 좋아서 구름 위를 걷는듯 합니다. 정말 즐겁습니다!_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Brian Okken - <strong><a href="https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855" target="_blank">Python Bytes</a> podcast host</strong> <a href="https://twitter.com/brianokken/status/1112220079972728832" target="_blank"><small>(ref)</small></a></div>
|
||||
<div style="text-align: right; margin-right: 10%;">Brian Okken - <strong><a href="https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855" target="_blank">Python Bytes</a> 팟캐스트 호스트</strong> <a href="https://twitter.com/brianokken/status/1112220079972728832" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_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._"
|
||||
"_솔직히, 당신이 만든 것은 매우 견고하고 세련되어 보입니다. 여러 면에서 **Hug**가 이렇게 되었으면 합니다 - 그걸 만든 누군가를 보는 것은 많은 영감을 줍니다._"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong><a href="http://www.hug.rest/" target="_blank">Hug</a> creator</strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(ref)</small></a></div>
|
||||
<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong><a href="http://www.hug.rest/" target="_blank">Hug</a> 제작자</strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_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 [...]_"
|
||||
"_REST API를 만들기 위해 **현대적인 프레임워크**를 찾고 있다면 **FastAPI**를 확인해 보세요. [...] 빠르고, 쓰기 쉽고, 배우기도 쉽습니다 [...]_"
|
||||
|
||||
"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_"
|
||||
"_우리 **API**를 **FastAPI**로 바꿨습니다 [...] 아마 여러분도 좋아하실 겁니다 [...]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> founders - <a href="https://spacy.io" target="_blank">spaCy</a> creators</strong> <a href="https://twitter.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://twitter.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div>
|
||||
<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> 설립자 - <a href="https://spacy.io" target="_blank">spaCy</a> 제작자</strong> <a href="https://twitter.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://twitter.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
## **Typer**, the FastAPI of CLIs
|
||||
## **Typer**, FastAPI의 CLI
|
||||
|
||||
<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
|
||||
|
||||
If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be used in the terminal instead of a web API, check out <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>.
|
||||
웹 API 대신 터미널에서 사용할 <abbr title="Command Line Interface">CLI</abbr> 앱을 만들고 있다면, <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>를 확인해 보세요.
|
||||
|
||||
**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
|
||||
**Typer**는 FastAPI의 동생입니다. 그리고 **FastAPI의 CLI**가 되기 위해 생겼습니다. ⌨️ 🚀
|
||||
|
||||
## Requirements
|
||||
## 요구사항
|
||||
|
||||
Python 3.6+
|
||||
|
||||
FastAPI stands on the shoulders of giants:
|
||||
FastAPI는 거인들의 어깨 위에 서 있습니다:
|
||||
|
||||
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts.
|
||||
* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> for the data parts.
|
||||
* 웹 부분을 위한 <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a>.
|
||||
* 데이터 부분을 위한 <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>.
|
||||
|
||||
## Installation
|
||||
## 설치
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -130,23 +123,23 @@ $ pip install fastapi
|
||||
|
||||
</div>
|
||||
|
||||
You will also need an ASGI server, for production such as <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
프로덕션을 위해 <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> 또는 <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>과 같은 ASGI 서버도 필요할 겁니다.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Example
|
||||
## 예제
|
||||
|
||||
### Create it
|
||||
### 만들기
|
||||
|
||||
* Create a file `main.py` with:
|
||||
* `main.py` 파일을 만드세요:
|
||||
|
||||
```Python
|
||||
from typing import Optional
|
||||
@@ -167,9 +160,9 @@ def read_item(item_id: int, q: Optional[str] = None):
|
||||
```
|
||||
|
||||
<details markdown="1">
|
||||
<summary>Or use <code>async def</code>...</summary>
|
||||
<summary>또는 <code>async def</code> 사용하기...</summary>
|
||||
|
||||
If your code uses `async` / `await`, use `async def`:
|
||||
여러분의 코드가 `async` / `await`을 사용한다면, `async def`를 사용하세요:
|
||||
|
||||
```Python hl_lines="9 14"
|
||||
from typing import Optional
|
||||
@@ -191,13 +184,13 @@ async def read_item(item_id: int, q: Optional[str] = None):
|
||||
|
||||
**Note**:
|
||||
|
||||
If you don't know, check the _"In a hurry?"_ section about <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">`async` and `await` in the docs</a>.
|
||||
잘 모르겠다면, <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">문서에서 `async`와 `await`</a>에 관한 _"급하세요?"_ 섹션을 확인해 보세요.
|
||||
|
||||
</details>
|
||||
|
||||
### Run it
|
||||
### 실행하기
|
||||
|
||||
Run the server with:
|
||||
서버를 실행하세요:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -214,54 +207,54 @@ INFO: Application startup complete.
|
||||
</div>
|
||||
|
||||
<details markdown="1">
|
||||
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
|
||||
<summary><code>uvicorn main:app --reload</code> 명령에 관하여...</summary>
|
||||
|
||||
The command `uvicorn main:app` refers to:
|
||||
명령 `uvicorn main:app`은 다음을 나타냅니다:
|
||||
|
||||
* `main`: the file `main.py` (the Python "module").
|
||||
* `main`: `main.py` 파일 (파이썬 "모듈").
|
||||
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
|
||||
* `--reload`: make the server restart after code changes. Only do this for development.
|
||||
* `--reload`: 코드가 변경된 후 서버 재시작하기. 개발환경에서만 사용하세요.
|
||||
|
||||
</details>
|
||||
|
||||
### Check it
|
||||
### 확인하기
|
||||
|
||||
Open your browser at <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
|
||||
브라우저로 <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>를 열어보세요.
|
||||
|
||||
You will see the JSON response as:
|
||||
아래의 JSON 응답을 볼 수 있습니다:
|
||||
|
||||
```JSON
|
||||
{"item_id": 5, "q": "somequery"}
|
||||
```
|
||||
|
||||
You already created an API that:
|
||||
여러분은 벌써 API를 만들었습니다:
|
||||
|
||||
* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
|
||||
* Both _paths_ take `GET` <em>operations</em> (also known as HTTP _methods_).
|
||||
* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
|
||||
* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.
|
||||
* _경로_ `/` 및 `/items/{item_id}`에서 HTTP 요청 받기.
|
||||
* 두 _경로_ 모두 `GET` <em>연산</em>(HTTP _메소드_ 로 알려진)을 받습니다.
|
||||
* _경로_ `/items/{item_id}`는 _경로 매개변수_ `int`형 이어야 하는 `item_id`를 가지고 있습니다.
|
||||
* _경로_ `/items/{item_id}`는 선택적인 `str`형 이어야 하는 _경로 매개변수_ `q`를 가지고 있습니다.
|
||||
|
||||
### Interactive API docs
|
||||
### 대화형 API 문서
|
||||
|
||||
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
이제 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>로 가보세요.
|
||||
|
||||
You will see the automatic interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
|
||||
자동 대화형 API 문서를 볼 수 있습니다 (<a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a> 제공):
|
||||
|
||||

|
||||
|
||||
### Alternative API docs
|
||||
### 대안 API 문서
|
||||
|
||||
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
그리고 이제 <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>로 가보세요.
|
||||
|
||||
You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
|
||||
다른 자동 문서를 볼 수 있습니다(<a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a> 제공):
|
||||
|
||||

|
||||
|
||||
## Example upgrade
|
||||
## 예제 개선
|
||||
|
||||
Now modify the file `main.py` to receive a body from a `PUT` request.
|
||||
이제 `PUT` 요청에 있는 본문(Body)을 받기 위해 `main.py`를 수정해봅시다.
|
||||
|
||||
Declare the body using standard Python types, thanks to Pydantic.
|
||||
Pydantic을 이용해 파이썬 표준 타입으로 본문을 선언합니다.
|
||||
|
||||
```Python hl_lines="4 9 10 11 12 25 26 27"
|
||||
from typing import Optional
|
||||
@@ -293,175 +286,175 @@ def update_item(item_id: int, item: Item):
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
|
||||
서버가 자동으로 리로딩 할 수 있어야 합니다 (위에서 `uvicorn` 명령에 `--reload`을 추가 했기 때문입니다).
|
||||
|
||||
### Interactive API docs upgrade
|
||||
### 대화형 API 문서 업그레이드
|
||||
|
||||
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
이제 <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>로 이동합니다.
|
||||
|
||||
* The interactive API documentation will be automatically updated, including the new body:
|
||||
* 대화형 API 문서가 새 본문과 함께 자동으로 업데이트 합니다:
|
||||
|
||||

|
||||
|
||||
* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
|
||||
* "Try it out" 버튼을 클릭하면, 매개변수를 채울 수 있게 해주고 직접 API와 상호작용 할 수 있습니다:
|
||||
|
||||

|
||||
|
||||
* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
|
||||
* 그러고 나서 "Execute" 버튼을 누르면, 사용자 인터페이스는 API와 통신하고 매개변수를 전송하며 그 결과를 가져와서 화면에 표시합니다:
|
||||
|
||||

|
||||
|
||||
### Alternative API docs upgrade
|
||||
### 대안 API 문서 업그레이드
|
||||
|
||||
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
그리고 이제, <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>로 이동합니다.
|
||||
|
||||
* The alternative documentation will also reflect the new query parameter and body:
|
||||
* 대안 문서 역시 새 쿼리 매개변수와 본문을 반영합니다:
|
||||
|
||||

|
||||
|
||||
### Recap
|
||||
### 요약
|
||||
|
||||
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
|
||||
요약하면, 여러분은 매개변수의 타입, 본문 등을 함수 매개변수로써 **한번에** 선언했습니다.
|
||||
|
||||
You do that with standard modern Python types.
|
||||
여러분은 현대 표준 파이썬 타입으로 이를 행했습니다.
|
||||
|
||||
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
|
||||
새로운 문법, 특정 라이브러리의 메소드나 클래스 등을 배울 필요가 없습니다.
|
||||
|
||||
Just standard **Python 3.6+**.
|
||||
그저 표준 **Python 3.6+**입니다.
|
||||
|
||||
For example, for an `int`:
|
||||
예를 들어, `int`에 대해선:
|
||||
|
||||
```Python
|
||||
item_id: int
|
||||
```
|
||||
|
||||
or for a more complex `Item` model:
|
||||
또는 좀 더 복잡한 `Item` 모델에 대해선:
|
||||
|
||||
```Python
|
||||
item: Item
|
||||
```
|
||||
|
||||
...and with that single declaration you get:
|
||||
...그리고 단 하나의 선언으로 여러분이 얻는 것은:
|
||||
|
||||
* Editor support, including:
|
||||
* Completion.
|
||||
* Type checks.
|
||||
* Validation of data:
|
||||
* Automatic and clear errors when the data is invalid.
|
||||
* Validation even for deeply nested JSON objects.
|
||||
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network to Python data and types. Reading from:
|
||||
* 다음을 포함한 편집기 지원:
|
||||
* 자동완성.
|
||||
* 타입 검사.
|
||||
* 데이터 검증:
|
||||
* 데이터가 유효하지 않을 때 자동으로 생성하는 명확한 에러.
|
||||
* 중첩된 JSON 객체에 대한 유효성 검사.
|
||||
* 입력 데이터 <abbr title="다음으로 알려진: 직렬화, 파싱, 마샬링">변환</abbr>: 네트워크에서 파이썬 데이터 및 타입으로 전송. 읽을 수 있는 것들:
|
||||
* JSON.
|
||||
* Path parameters.
|
||||
* Query parameters.
|
||||
* Cookies.
|
||||
* Headers.
|
||||
* Forms.
|
||||
* Files.
|
||||
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of output data: converting from Python data and types to network data (as JSON):
|
||||
* Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
|
||||
* `datetime` objects.
|
||||
* `UUID` objects.
|
||||
* Database models.
|
||||
* ...and many more.
|
||||
* Automatic interactive API documentation, including 2 alternative user interfaces:
|
||||
* 경로 매개변수.
|
||||
* 쿼리 매개변수.
|
||||
* 쿠키.
|
||||
* 헤더.
|
||||
* 폼(Forms).
|
||||
* 파일.
|
||||
* 출력 데이터 <abbr title="다음으로 알려진: 직렬화, 파싱, 마샬링">변환</abbr>: 파이썬 데이터 및 타입을 네트워크 데이터로 전환(JSON 형식으로):
|
||||
* 파이썬 타입 변환 (`str`, `int`, `float`, `bool`, `list`, 등).
|
||||
* `datetime` 객체.
|
||||
* `UUID` 객체.
|
||||
* 데이터베이스 모델.
|
||||
* ...더 많은 것들.
|
||||
* 대안가능한 사용자 인터페이스를 2개 포함한 자동 대화형 API 문서:
|
||||
* Swagger UI.
|
||||
* ReDoc.
|
||||
|
||||
---
|
||||
|
||||
Coming back to the previous code example, **FastAPI** will:
|
||||
이전 코드 예제로 돌아가서, **FastAPI**는 다음처럼 처리합니다:
|
||||
|
||||
* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
|
||||
* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
|
||||
* If it is not, the client will see a useful, clear error.
|
||||
* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests.
|
||||
* As the `q` parameter is declared with `= None`, it is optional.
|
||||
* Without the `None` it would be required (as is the body in the case with `PUT`).
|
||||
* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
|
||||
* Check that it has a required attribute `name` that should be a `str`.
|
||||
* Check that it has a required attribute `price` that has to be a `float`.
|
||||
* Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
|
||||
* All this would also work for deeply nested JSON objects.
|
||||
* Convert from and to JSON automatically.
|
||||
* Document everything with OpenAPI, that can be used by:
|
||||
* Interactive documentation systems.
|
||||
* Automatic client code generation systems, for many languages.
|
||||
* Provide 2 interactive documentation web interfaces directly.
|
||||
* `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으로, 그리고 에서부터 자동 변환.
|
||||
* 다음에서 사용할 수 있는 모든 것을 OpenAPI로 문서화:
|
||||
* 대화형 문서 시스템.
|
||||
* 여러 언어들에 대한 자동 클라이언트 코드 생성 시스템.
|
||||
* 2개의 대화형 문서 웹 인터페이스를 직접 제공.
|
||||
|
||||
---
|
||||
|
||||
We just scratched the surface, but you already get the idea of how it all works.
|
||||
우리는 그저 수박 겉핡기만 했을 뿐인데 여러분은 벌써 어떻게 작동하는지 알고 있습니다.
|
||||
|
||||
Try changing the line with:
|
||||
다음 줄을 바꿔보세요:
|
||||
|
||||
```Python
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
...from:
|
||||
...에서:
|
||||
|
||||
```Python
|
||||
... "item_name": item.name ...
|
||||
```
|
||||
|
||||
...to:
|
||||
...으로:
|
||||
|
||||
```Python
|
||||
... "item_price": item.price ...
|
||||
```
|
||||
|
||||
...and see how your editor will auto-complete the attributes and know their types:
|
||||
...그러고 나서 여러분의 편집기가 속성과 타입을 알고 자동 완성하는지 보세요:
|
||||
|
||||

|
||||
|
||||
For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
|
||||
더 많은 기능을 포함한 보다 완전한 예제의 경우, <a href="https://fastapi.tiangolo.com/tutorial/">튜토리얼 - 사용자 가이드</a>를 보세요.
|
||||
|
||||
**Spoiler alert**: the tutorial - user guide includes:
|
||||
**스포일러 주의**: 튜토리얼 - 사용자 가이드는:
|
||||
|
||||
* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
|
||||
* How to set **validation constraints** as `maximum_length` or `regex`.
|
||||
* A very powerful and easy to use **<abbr title="also known as components, resources, providers, services, injectables">Dependency Injection</abbr>** system.
|
||||
* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
|
||||
* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
|
||||
* Many extra features (thanks to Starlette) as:
|
||||
* **WebSockets**
|
||||
* 서로 다른 장소에서 **매개변수** 선언: **헤더**, **쿠키**, **폼 필드** 그리고 **파일**.
|
||||
* `maximum_length` 또는 `regex`처럼 **유효성 제약**하는 방법.
|
||||
* 강력하고 사용하기 쉬운 **<abbr title="컴포넌트, 리소스, 제공자, 서비스, injectables라 알려진">의존성 주입</abbr>** 시스템.
|
||||
* **OAuth2** 지원을 포함한 **JWT tokens** 및 **HTTP Basic**을 갖는 보안과 인증.
|
||||
* (Pydantic 덕분에) **깊은 중첩 JSON 모델**을 선언하는데 더 진보한 (하지만 마찬가지로 쉬운) 기술.
|
||||
* (Starlette 덕분에) 많은 추가 기능:
|
||||
* **웹 소켓**
|
||||
* **GraphQL**
|
||||
* extremely easy tests based on `requests` and `pytest`
|
||||
* `requests` 및 `pytest`에 기반한 극히 쉬운 테스트
|
||||
* **CORS**
|
||||
* **Cookie Sessions**
|
||||
* ...and more.
|
||||
* **쿠키 세션**
|
||||
* ...기타 등등.
|
||||
|
||||
## Performance
|
||||
## 성능
|
||||
|
||||
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
|
||||
독립된 TechEmpower 벤치마크에서 Uvicorn에서 작동하는 FastAPI 어플리케이션이 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">사용 가능한 가장 빠른 프레임워크 중 하나</a>로 Starlette와 Uvicorn(FastAPI에서 내부적으로 사용)에만 밑돌고 있습니다. (*)
|
||||
|
||||
To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
|
||||
자세한 내용은 <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">벤치마크</a> 섹션을 보세요.
|
||||
|
||||
## Optional Dependencies
|
||||
## 선택가능한 종속사항
|
||||
|
||||
Used by Pydantic:
|
||||
Pydantic이 사용하는:
|
||||
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - for faster JSON <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
|
||||
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - 더 빠른 JSON <abbr title="HTTP 요청에서 파이썬 데이터로 가는 문자열 변환">"파싱"</abbr>.
|
||||
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - 이메일 유효성 검사.
|
||||
|
||||
Used by Starlette:
|
||||
Starlette이 사용하는:
|
||||
|
||||
* <a href="http://docs.python-requests.org" target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
|
||||
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Required if you want to use `FileResponse` or `StaticFiles`.
|
||||
* <a href="http://jinja.pocoo.org" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
|
||||
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
|
||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
|
||||
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` support.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
|
||||
* <a href="http://docs.python-requests.org" target="_blank"><code>requests</code></a> - `TestClient`를 사용하려면 필요.
|
||||
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - `FileResponse` 또는 `StaticFiles`를 사용하려면 필요.
|
||||
* <a href="http://jinja.pocoo.org" target="_blank"><code>jinja2</code></a> - 기본 템플릿 설정을 사용하려면 필요.
|
||||
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - `request.form()`과 함께 <abbr title="HTTP 요청에서 파이썬 데이터로 가는 문자열 변환">"parsing"</abbr>의 지원을 원하면 필요.
|
||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - `SessionMiddleware` 지원을 위해 필요.
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요가 없을 겁니다).
|
||||
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - `GraphQLApp` 지원을 위해 필요.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - `UJSONResponse`를 사용하려면 필요.
|
||||
|
||||
Used by FastAPI / Starlette:
|
||||
FastAPI / Starlette이 사용하는:
|
||||
|
||||
* <a href="http://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
|
||||
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
|
||||
* <a href="http://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - 애플리케이션을 로드하고 제공하는 서버.
|
||||
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - `ORJSONResponse`을 사용하려면 필요.
|
||||
|
||||
You can install all of these with `pip install fastapi[all]`.
|
||||
`pip install fastapi[all]`를 통해 이 모두를 설치 할 수 있습니다.
|
||||
|
||||
## License
|
||||
## 라이센스
|
||||
|
||||
This project is licensed under the terms of the MIT license.
|
||||
이 프로젝트는 MIT 라이센스 조약에 따라 라이센스가 부여됩니다.
|
||||
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/ko/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -66,6 +80,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
@@ -73,5 +112,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
- https://fastapi.tiangolo.com/js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
0
docs/ko/overrides/.gitignore
vendored
Normal file
@@ -336,7 +336,7 @@ Você apenas precisa instalar um servidor ASGI compatível como:
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -14,9 +14,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -124,7 +121,7 @@ Você também precisará de um servidor ASGI para produção, tal como <a href="
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -64,7 +64,7 @@ $ pip install fastapi[all]
|
||||
Também instale o `uvicorn` para funcionar como servidor:
|
||||
|
||||
```
|
||||
pip install uvicorn
|
||||
pip install uvicorn[standard]
|
||||
```
|
||||
|
||||
E o mesmo para cada dependência opcional que você quiser usar.
|
||||
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/pt/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -74,6 +88,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
@@ -81,5 +120,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
- https://fastapi.tiangolo.com/js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
0
docs/pt/overrides/.gitignore
vendored
Normal file
@@ -18,9 +18,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://badge.fury.io/py/fastapi.svg" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -135,7 +132,7 @@ You will also need an ASGI server, for production such as <a href="https://www.u
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/ru/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -66,6 +80,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
@@ -73,5 +112,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
- https://fastapi.tiangolo.com/js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
0
docs/ru/overrides/.gitignore
vendored
Normal file
464
docs/sq/docs/index.md
Normal file
@@ -0,0 +1,464 @@
|
||||
|
||||
{!../../../docs/missing-translation.md!}
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://fastapi.tiangolo.com"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt="FastAPI"></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<em>FastAPI framework, high performance, easy to learn, fast to code, ready for production</em>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/tiangolo/fastapi/actions?query=workflow%3ATest" target="_blank">
|
||||
<img src="https://github.com/tiangolo/fastapi/workflows/Test/badge.svg" alt="Test">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi?color=%2334D058" alt="Coverage">
|
||||
</a>
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
**Documentation**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
|
||||
|
||||
**Source Code**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
|
||||
|
||||
---
|
||||
|
||||
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
|
||||
|
||||
The key features are:
|
||||
|
||||
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
|
||||
|
||||
* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
|
||||
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
|
||||
* **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
|
||||
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
|
||||
* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
|
||||
* **Robust**: Get production-ready code. With automatic interactive documentation.
|
||||
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (previously known as Swagger) and <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
|
||||
|
||||
<small>* estimation based on tests on an internal development team, building production applications.</small>
|
||||
|
||||
## Gold Sponsors
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
{% if sponsors %}
|
||||
{% for sponsor in sponsors.gold -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">Other sponsors</a>
|
||||
|
||||
## Opinions
|
||||
|
||||
"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Kabir Khan - <strong>Microsoft</strong> <a href="https://github.com/tiangolo/fastapi/pull/26" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - <strong>Uber</strong> <a href="https://eng.uber.com/ludwig-v0-2/" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Kevin Glisson, Marc Vilanova, Forest Monsen - <strong>Netflix</strong> <a href="https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_I’m over the moon excited about **FastAPI**. It’s so fun!_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Brian Okken - <strong><a href="https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855" target="_blank">Python Bytes</a> podcast host</strong> <a href="https://twitter.com/brianokken/status/1112220079972728832" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_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._"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Timothy Crosley - <strong><a href="https://www.hug.rest/" target="_blank">Hug</a> creator</strong> <a href="https://news.ycombinator.com/item?id=19455465" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
"_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 [...]_"
|
||||
|
||||
<div style="text-align: right; margin-right: 10%;">Ines Montani - Matthew Honnibal - <strong><a href="https://explosion.ai" target="_blank">Explosion AI</a> founders - <a href="https://spacy.io" target="_blank">spaCy</a> creators</strong> <a href="https://twitter.com/_inesmontani/status/1144173225322143744" target="_blank"><small>(ref)</small></a> - <a href="https://twitter.com/honnibal/status/1144031421859655680" target="_blank"><small>(ref)</small></a></div>
|
||||
|
||||
---
|
||||
|
||||
## **Typer**, the FastAPI of CLIs
|
||||
|
||||
<a href="https://typer.tiangolo.com" target="_blank"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style="width: 20%;"></a>
|
||||
|
||||
If you are building a <abbr title="Command Line Interface">CLI</abbr> app to be used in the terminal instead of a web API, check out <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>.
|
||||
|
||||
**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀
|
||||
|
||||
## Requirements
|
||||
|
||||
Python 3.6+
|
||||
|
||||
FastAPI stands on the shoulders of giants:
|
||||
|
||||
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> for the web parts.
|
||||
* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> for the data parts.
|
||||
|
||||
## Installation
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install fastapi
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
You will also need an ASGI server, for production such as <a href="https://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> or <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Example
|
||||
|
||||
### Create it
|
||||
|
||||
* Create a file `main.py` with:
|
||||
|
||||
```Python
|
||||
from typing import Optional
|
||||
|
||||
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: Optional[str] = None):
|
||||
return {"item_id": item_id, "q": q}
|
||||
```
|
||||
|
||||
<details markdown="1">
|
||||
<summary>Or use <code>async def</code>...</summary>
|
||||
|
||||
If your code uses `async` / `await`, use `async def`:
|
||||
|
||||
```Python hl_lines="9 14"
|
||||
from typing import Optional
|
||||
|
||||
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: Optional[str] = None):
|
||||
return {"item_id": item_id, "q": q}
|
||||
```
|
||||
|
||||
**Note**:
|
||||
|
||||
If you don't know, check the _"In a hurry?"_ section about <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">`async` and `await` in the docs</a>.
|
||||
|
||||
</details>
|
||||
|
||||
### Run it
|
||||
|
||||
Run the server with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```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.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
<details markdown="1">
|
||||
<summary>About the command <code>uvicorn main:app --reload</code>...</summary>
|
||||
|
||||
The command `uvicorn main:app` refers to:
|
||||
|
||||
* `main`: the file `main.py` (the Python "module").
|
||||
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
|
||||
* `--reload`: make the server restart after code changes. Only do this for development.
|
||||
|
||||
</details>
|
||||
|
||||
### Check it
|
||||
|
||||
Open your browser at <a href="http://127.0.0.1:8000/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1:8000/items/5?q=somequery</a>.
|
||||
|
||||
You will see the JSON response as:
|
||||
|
||||
```JSON
|
||||
{"item_id": 5, "q": "somequery"}
|
||||
```
|
||||
|
||||
You already created an API that:
|
||||
|
||||
* Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`.
|
||||
* Both _paths_ take `GET` <em>operations</em> (also known as HTTP _methods_).
|
||||
* The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.
|
||||
* The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.
|
||||
|
||||
### Interactive API docs
|
||||
|
||||
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
|
||||
You will see the automatic interactive API documentation (provided by <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
|
||||
|
||||

|
||||
|
||||
### Alternative API docs
|
||||
|
||||
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
|
||||
You will see the alternative automatic documentation (provided by <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
|
||||
|
||||

|
||||
|
||||
## Example upgrade
|
||||
|
||||
Now modify the file `main.py` to receive a body from a `PUT` request.
|
||||
|
||||
Declare the body using standard Python types, thanks to Pydantic.
|
||||
|
||||
```Python hl_lines="4 9-12 25-27"
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import FastAPI
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
price: float
|
||||
is_offer: Optional[bool] = None
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
return {"Hello": "World"}
|
||||
|
||||
|
||||
@app.get("/items/{item_id}")
|
||||
def read_item(item_id: int, q: Optional[str] = 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}
|
||||
```
|
||||
|
||||
The server should reload automatically (because you added `--reload` to the `uvicorn` command above).
|
||||
|
||||
### Interactive API docs upgrade
|
||||
|
||||
Now go to <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
|
||||
* The interactive API documentation will be automatically updated, including the new body:
|
||||
|
||||

|
||||
|
||||
* Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API:
|
||||
|
||||

|
||||
|
||||
* Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen:
|
||||
|
||||

|
||||
|
||||
### Alternative API docs upgrade
|
||||
|
||||
And now, go to <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
|
||||
* The alternative documentation will also reflect the new query parameter and body:
|
||||
|
||||

|
||||
|
||||
### Recap
|
||||
|
||||
In summary, you declare **once** the types of parameters, body, etc. as function parameters.
|
||||
|
||||
You do that with standard modern Python types.
|
||||
|
||||
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
|
||||
|
||||
Just standard **Python 3.6+**.
|
||||
|
||||
For example, for an `int`:
|
||||
|
||||
```Python
|
||||
item_id: int
|
||||
```
|
||||
|
||||
or for a more complex `Item` model:
|
||||
|
||||
```Python
|
||||
item: Item
|
||||
```
|
||||
|
||||
...and with that single declaration you get:
|
||||
|
||||
* Editor support, including:
|
||||
* Completion.
|
||||
* Type checks.
|
||||
* Validation of data:
|
||||
* Automatic and clear errors when the data is invalid.
|
||||
* Validation even for deeply nested JSON objects.
|
||||
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of input data: coming from the network to Python data and types. Reading from:
|
||||
* JSON.
|
||||
* Path parameters.
|
||||
* Query parameters.
|
||||
* Cookies.
|
||||
* Headers.
|
||||
* Forms.
|
||||
* Files.
|
||||
* <abbr title="also known as: serialization, parsing, marshalling">Conversion</abbr> of output data: converting from Python data and types to network data (as JSON):
|
||||
* Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc).
|
||||
* `datetime` objects.
|
||||
* `UUID` objects.
|
||||
* Database models.
|
||||
* ...and many more.
|
||||
* Automatic interactive API documentation, including 2 alternative user interfaces:
|
||||
* Swagger UI.
|
||||
* ReDoc.
|
||||
|
||||
---
|
||||
|
||||
Coming back to the previous code example, **FastAPI** will:
|
||||
|
||||
* Validate that there is an `item_id` in the path for `GET` and `PUT` requests.
|
||||
* Validate that the `item_id` is of type `int` for `GET` and `PUT` requests.
|
||||
* If it is not, the client will see a useful, clear error.
|
||||
* Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests.
|
||||
* As the `q` parameter is declared with `= None`, it is optional.
|
||||
* Without the `None` it would be required (as is the body in the case with `PUT`).
|
||||
* For `PUT` requests to `/items/{item_id}`, Read the body as JSON:
|
||||
* Check that it has a required attribute `name` that should be a `str`.
|
||||
* Check that it has a required attribute `price` that has to be a `float`.
|
||||
* Check that it has an optional attribute `is_offer`, that should be a `bool`, if present.
|
||||
* All this would also work for deeply nested JSON objects.
|
||||
* Convert from and to JSON automatically.
|
||||
* Document everything with OpenAPI, that can be used by:
|
||||
* Interactive documentation systems.
|
||||
* Automatic client code generation systems, for many languages.
|
||||
* Provide 2 interactive documentation web interfaces directly.
|
||||
|
||||
---
|
||||
|
||||
We just scratched the surface, but you already get the idea of how it all works.
|
||||
|
||||
Try changing the line with:
|
||||
|
||||
```Python
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
...from:
|
||||
|
||||
```Python
|
||||
... "item_name": item.name ...
|
||||
```
|
||||
|
||||
...to:
|
||||
|
||||
```Python
|
||||
... "item_price": item.price ...
|
||||
```
|
||||
|
||||
...and see how your editor will auto-complete the attributes and know their types:
|
||||
|
||||

|
||||
|
||||
For a more complete example including more features, see the <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
|
||||
|
||||
**Spoiler alert**: the tutorial - user guide includes:
|
||||
|
||||
* Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**.
|
||||
* How to set **validation constraints** as `maximum_length` or `regex`.
|
||||
* A very powerful and easy to use **<abbr title="also known as components, resources, providers, services, injectables">Dependency Injection</abbr>** system.
|
||||
* Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth.
|
||||
* More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic).
|
||||
* Many extra features (thanks to Starlette) as:
|
||||
* **WebSockets**
|
||||
* **GraphQL**
|
||||
* extremely easy tests based on `requests` and `pytest`
|
||||
* **CORS**
|
||||
* **Cookie Sessions**
|
||||
* ...and more.
|
||||
|
||||
## Performance
|
||||
|
||||
Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">one of the fastest Python frameworks available</a>, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)
|
||||
|
||||
To understand more about it, see the section <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
|
||||
|
||||
## Optional Dependencies
|
||||
|
||||
Used by Pydantic:
|
||||
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - for faster JSON <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>.
|
||||
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - for email validation.
|
||||
|
||||
Used by Starlette:
|
||||
|
||||
* <a href="https://requests.readthedocs.io" target="_blank"><code>requests</code></a> - Required if you want to use the `TestClient`.
|
||||
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Required if you want to use `FileResponse` or `StaticFiles`.
|
||||
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
|
||||
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
|
||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Required for `SessionMiddleware` support.
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
|
||||
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Required for `GraphQLApp` support.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
|
||||
|
||||
Used by FastAPI / Starlette:
|
||||
|
||||
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application.
|
||||
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - Required if you want to use `ORJSONResponse`.
|
||||
|
||||
You can install all of these with `pip install fastapi[all]`.
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the terms of the MIT license.
|
||||
114
docs/sq/mkdocs.yml
Normal file
@@ -0,0 +1,114 @@
|
||||
site_name: FastAPI
|
||||
site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
|
||||
site_url: https://fastapi.tiangolo.com/sq/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
favicon: https://fastapi.tiangolo.com/img/favicon.png
|
||||
language: en
|
||||
repo_name: tiangolo/fastapi
|
||||
repo_url: https://github.com/tiangolo/fastapi
|
||||
edit_uri: ''
|
||||
google_analytics:
|
||||
- UA-133183413-1
|
||||
- auto
|
||||
plugins:
|
||||
- search
|
||||
- markdownextradata:
|
||||
data: data
|
||||
nav:
|
||||
- FastAPI: index.md
|
||||
- Languages:
|
||||
- en: /
|
||||
- es: /es/
|
||||
- fr: /fr/
|
||||
- it: /it/
|
||||
- ja: /ja/
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
markdown_extensions:
|
||||
- toc:
|
||||
permalink: true
|
||||
- markdown.extensions.codehilite:
|
||||
guess_lang: false
|
||||
- markdown_include.include:
|
||||
base_path: docs
|
||||
- admonition
|
||||
- codehilite
|
||||
- extra
|
||||
- pymdownx.superfences:
|
||||
custom_fences:
|
||||
- name: mermaid
|
||||
class: mermaid
|
||||
format: !!python/name:pymdownx.superfences.fence_div_format ''
|
||||
- pymdownx.tabbed
|
||||
extra:
|
||||
social:
|
||||
- icon: fontawesome/brands/github-alt
|
||||
link: https://github.com/tiangolo/typer
|
||||
- icon: fontawesome/brands/twitter
|
||||
link: https://twitter.com/tiangolo
|
||||
- icon: fontawesome/brands/linkedin
|
||||
link: https://www.linkedin.com/in/tiangolo
|
||||
- icon: fontawesome/brands/dev
|
||||
link: https://dev.to/tiangolo
|
||||
- icon: fontawesome/brands/medium
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
0
docs/sq/overrides/.gitignore
vendored
Normal file
@@ -18,9 +18,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -135,7 +132,7 @@ You will also need an ASGI server, for production such as <a href="https://www.u
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/tr/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -66,6 +80,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
@@ -73,5 +112,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
- https://fastapi.tiangolo.com/js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
0
docs/tr/overrides/.gitignore
vendored
Normal file
@@ -18,9 +18,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -135,7 +132,7 @@ You will also need an ASGI server, for production such as <a href="https://www.u
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/uk/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -66,6 +80,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
@@ -73,5 +112,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
- https://fastapi.tiangolo.com/js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
0
docs/uk/overrides/.gitignore
vendored
Normal file
37
docs/zh/docs/advanced/additional-status-codes.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# 额外的状态码
|
||||
|
||||
**FastAPI** 默认使用 `JSONResponse` 返回一个响应,将你的 *路径操作* 中的返回内容放到该 `JSONResponse` 中。
|
||||
|
||||
**FastAPI** 会自动使用默认的状态码或者使用你在 *路径操作* 中设置的状态码。
|
||||
|
||||
## 额外的状态码
|
||||
|
||||
如果你想要返回主要状态码之外的状态码,你可以通过直接返回一个 `Response` 来实现,比如 `JSONResponse`,然后直接设置额外的状态码。
|
||||
|
||||
例如,假设你想有一个 *路径操作* 能够更新条目,并且更新成功时返回 200 「成功」 的 HTTP 状态码。
|
||||
|
||||
但是你也希望它能够接受新的条目。并且当这些条目不存在时,会自动创建并返回 201 「创建」的 HTTP 状态码。
|
||||
|
||||
要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为为你要的值。
|
||||
|
||||
```Python hl_lines="2 19"
|
||||
{!../../../docs_src/additional_status_codes/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! warning "警告"
|
||||
当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。
|
||||
|
||||
FastAPI 不会用模型等对该响应进行序列化。
|
||||
|
||||
确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。
|
||||
|
||||
!!! note "技术细节"
|
||||
你也可以使用 `from starlette.responses import JSONResponse`。
|
||||
|
||||
出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。
|
||||
|
||||
## OpenAPI 和 API 文档
|
||||
|
||||
如果你直接返回额外的状态码和响应,它们不会包含在 OpenAPI 方案(API 文档)中,因为 FastAPI 没办法预先知道你要返回什么。
|
||||
|
||||
但是你可以使用 [额外的响应](additional-responses.md){.internal-link target=_blank} 在代码中记录这些内容。
|
||||
212
docs/zh/docs/advanced/custom-response.md
Normal file
@@ -0,0 +1,212 @@
|
||||
# 自定义响应 - HTML,流,文件和其他
|
||||
|
||||
**FastAPI** 默认会使用 `JSONResponse` 返回响应。
|
||||
|
||||
你可以通过直接返回 `Response` 来重载它,参见 [直接返回响应](response-directly.md){.internal-link target=_blank}。
|
||||
|
||||
但如果你直接返回 `Response`,返回数据不会自动转换,也不会自动生成文档(例如,在 HTTP 头 `Content-Type` 中包含特定的「媒体类型」作为生成的 OpenAPI 的一部分)。
|
||||
|
||||
你还可以在 *路径操作装饰器* 中声明你想用的 `Response`。
|
||||
|
||||
你从 *路径操作函数* 中返回的内容将被放在该 `Response` 中。
|
||||
|
||||
并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。
|
||||
|
||||
!!! note "说明"
|
||||
如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。
|
||||
|
||||
## 使用 `ORJSONResponse`
|
||||
|
||||
例如,如果你需要压榨性能,你可以安装并使用 <a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a> 并将响应设置为 `ORJSONResponse`。
|
||||
|
||||
导入你想要使用的 `Response` 类(子类)然后在 *路径操作装饰器* 中声明它。
|
||||
|
||||
```Python hl_lines="2 7"
|
||||
{!../../../docs_src/custom_response/tutorial001b.py!}
|
||||
```
|
||||
|
||||
!!! info "提示"
|
||||
参数 `response_class` 也会用来定义响应的「媒体类型」。
|
||||
|
||||
在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。
|
||||
|
||||
并且在 OpenAPI 文档中也会这样记录。
|
||||
|
||||
!!! tip "小贴士"
|
||||
`ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。
|
||||
|
||||
|
||||
|
||||
## HTML 响应
|
||||
|
||||
使用 `HTMLResponse` 来从 **FastAPI** 中直接返回一个 HTML 响应。
|
||||
|
||||
* 导入 `HTMLResponse`。
|
||||
* 将 `HTMLResponse` 作为你的 *路径操作* 的 `response_class` 参数传入。
|
||||
|
||||
```Python hl_lines="2 7"
|
||||
{!../../../docs_src/custom_response/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! info "提示"
|
||||
参数 `response_class` 也会用来定义响应的「媒体类型」。
|
||||
|
||||
在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。
|
||||
|
||||
并且在 OpenAPI 文档中也会这样记录。
|
||||
|
||||
### 返回一个 `Response`
|
||||
|
||||
正如你在 [直接返回响应](response-directly.md){.internal-link target=_blank} 中了解到的,你也可以通过直接返回响应在 *路径操作* 中直接重载响应。
|
||||
|
||||
和上面一样的例子,返回一个 `HTMLResponse` 看起来可能是这样:
|
||||
|
||||
```Python hl_lines="2 7 19"
|
||||
{!../../../docs_src/custom_response/tutorial003.py!}
|
||||
```
|
||||
|
||||
!!! warning "警告"
|
||||
*路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。
|
||||
|
||||
!!! info "提示"
|
||||
当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。
|
||||
|
||||
### OpenAPI 中的文档和重载 `Response`
|
||||
|
||||
如果你想要在函数内重载响应,但是同时在 OpenAPI 中文档化「媒体类型」,你可以使用 `response_class` 参数并返回一个 `Response` 对象。
|
||||
|
||||
接着 `response_class` 参数只会被用来文档化 OpenAPI 的 *路径操作*,你的 `Response` 用来返回响应。
|
||||
|
||||
### 直接返回 `HTMLResponse`
|
||||
|
||||
比如像这样:
|
||||
|
||||
```Python hl_lines="7 23 21"
|
||||
{!../../../docs_src/custom_response/tutorial004.py!}
|
||||
```
|
||||
|
||||
在这个例子中,函数 `generate_html_response()` 已经生成并返回 `Response` 对象而不是在 `str` 中返回 HTML。
|
||||
|
||||
通过返回函数 `generate_html_response()` 的调用结果,你已经返回一个重载 **FastAPI** 默认行为的 `Response` 对象,
|
||||
|
||||
但如果你在 `response_class` 中也传入了 `HTMLResponse`,**FastAPI** 会知道如何在 OpenAPI 和交互式文档中使用 `text/html` 将其文档化为 HTML。
|
||||
|
||||
<img src="/img/tutorial/custom-response/image01.png">
|
||||
|
||||
## 可用响应
|
||||
|
||||
这里有一些可用的响应。
|
||||
|
||||
要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。
|
||||
|
||||
!!! note "技术细节"
|
||||
你也可以使用 `from starlette.responses import HTMLResponse`。
|
||||
|
||||
**FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。
|
||||
|
||||
### `Response`
|
||||
|
||||
其他全部的响应都继承自主类 `Response`。
|
||||
|
||||
你可以直接返回它。
|
||||
|
||||
`Response` 类接受如下参数:
|
||||
|
||||
* `content` - 一个 `str` 或者 `bytes`。
|
||||
* `status_code` - 一个 `int` 类型的 HTTP 状态码。
|
||||
* `headers` - 一个由字符串组成的 `dict`。
|
||||
* `media_type` - 一个给出媒体类型的 `str`,比如 `"text/html"`。
|
||||
|
||||
FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它还将包含一个基于 media_type 的 Content-Type 头,并为文本类型附加一个字符集。
|
||||
|
||||
|
||||
```Python hl_lines="1 18"
|
||||
{!../../../docs_src/response_directly/tutorial002.py!}
|
||||
```
|
||||
|
||||
### `HTMLResponse`
|
||||
|
||||
如上文所述,接受文本或字节并返回 HTML 响应。
|
||||
|
||||
### `PlainTextResponse`
|
||||
|
||||
接受文本或字节并返回纯文本响应。
|
||||
|
||||
```Python hl_lines="2 7 9"
|
||||
{!../../../docs_src/custom_response/tutorial005.py!}
|
||||
```
|
||||
|
||||
### `JSONResponse`
|
||||
|
||||
接受数据并返回一个 `application/json` 编码的响应。
|
||||
|
||||
如上文所述,这是 **FastAPI** 中使用的默认响应。
|
||||
|
||||
### `ORJSONResponse`
|
||||
|
||||
如上文所述,`ORJSONResponse` 是一个使用 <a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a> 的快速的可选 JSON 响应。
|
||||
|
||||
|
||||
### `UJSONResponse`
|
||||
|
||||
`UJSONResponse` 是一个使用 <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a> 的可选 JSON 响应。
|
||||
|
||||
!!! warning "警告"
|
||||
在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。
|
||||
|
||||
```Python hl_lines="2 7"
|
||||
{!../../../docs_src/custom_response/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! tip "小贴士"
|
||||
`ORJSONResponse` 可能是一个更快的选择。
|
||||
|
||||
### `RedirectResponse`
|
||||
|
||||
返回 HTTP 重定向。默认情况下使用 307 状态代码(临时重定向)。
|
||||
|
||||
```Python hl_lines="2 9"
|
||||
{!../../../docs_src/custom_response/tutorial006.py!}
|
||||
```
|
||||
|
||||
### `StreamingResponse`
|
||||
|
||||
采用异步生成器或普通生成器/迭代器,然后流式传输响应主体。
|
||||
|
||||
```Python hl_lines="2 14"
|
||||
{!../../../docs_src/custom_response/tutorial007.py!}
|
||||
```
|
||||
|
||||
#### 对类似文件的对象使用 `StreamingResponse`
|
||||
|
||||
如果您有类似文件的对象(例如,由 `open()` 返回的对象),则可以在 `StreamingResponse` 中将其返回。
|
||||
|
||||
包括许多与云存储,视频处理等交互的库。
|
||||
|
||||
```Python hl_lines="2 10 11"
|
||||
{!../../../docs_src/custom_response/tutorial008.py!}
|
||||
```
|
||||
|
||||
!!! tip "小贴士"
|
||||
注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。
|
||||
|
||||
### `FileResponse`
|
||||
|
||||
异步传输文件作为响应。
|
||||
|
||||
与其他响应类型相比,接受不同的参数集进行实例化:
|
||||
|
||||
* `path` - 要流式传输的文件的文件路径。
|
||||
* `headers` - 任何自定义响应头,传入字典类型。
|
||||
* `media_type` - 给出媒体类型的字符串。如果未设置,则文件名或路径将用于推断媒体类型。
|
||||
* `filename` - 如果给出,它将包含在响应的 `Content-Disposition` 中。
|
||||
|
||||
文件响应将包含适当的 `Content-Length`,`Last-Modified` 和 `ETag` 的响应头。
|
||||
|
||||
```Python hl_lines="2 10"
|
||||
{!../../../docs_src/custom_response/tutorial009.py!}
|
||||
```
|
||||
|
||||
## 额外文档
|
||||
|
||||
您还可以使用 `response` 在 OpenAPI 中声明媒体类型和许多其他详细信息:[OpenAPI 中的额外文档](additional-responses.md){.internal-link target=_blank}。
|
||||
18
docs/zh/docs/advanced/index.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# 高级用户指南 - 简介
|
||||
|
||||
## 额外特性
|
||||
|
||||
主要的教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 应该足以让你了解 **FastAPI** 的所有主要特性。
|
||||
|
||||
你会在接下来的章节中了解到其他的选项、配置以及额外的特性。
|
||||
|
||||
!!! tip
|
||||
接下来的章节**并不一定是**「高级的」。
|
||||
|
||||
而且对于你的使用场景来说,解决方案很可能就在其中。
|
||||
|
||||
## 先阅读教程
|
||||
|
||||
你可能仍会用到 **FastAPI** 主教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 中的大多数特性。
|
||||
|
||||
接下来的章节我们认为你已经读过 [教程 - 用户指南](../tutorial/){.internal-link target=_blank},并且假设你已经知晓其中主要思想。
|
||||
@@ -0,0 +1,53 @@
|
||||
# 路径操作的高级配置
|
||||
|
||||
## OpenAPI 的 operationId
|
||||
|
||||
!!! warning
|
||||
如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。
|
||||
|
||||
你可以在路径操作中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。
|
||||
|
||||
务必确保每个操作路径的 `operation_id` 都是唯一的。
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!}
|
||||
```
|
||||
|
||||
### 使用 *路径操作函数* 的函数名作为 operationId
|
||||
|
||||
如果你想用你的 API 的函数名作为 `operationId` 的名字,你可以遍历一遍 API 的函数名,然后使用他们的 `APIRoute.name` 重写每个 *路径操作* 的 `operation_id`。
|
||||
|
||||
你应该在添加了所有 *路径操作* 之后执行此操作。
|
||||
|
||||
```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24"
|
||||
{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! tip
|
||||
如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。
|
||||
|
||||
!!! warning
|
||||
如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。
|
||||
|
||||
即使它们在不同的模块中(Python 文件)。
|
||||
|
||||
## 从 OpenAPI 中排除
|
||||
|
||||
使用参数 `include_in_schema` 并将其设置为 `False` ,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了)。
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!}
|
||||
```
|
||||
|
||||
## docstring 的高级描述
|
||||
|
||||
你可以限制 *路径操作函数* 的 `docstring` 中用于 OpenAPI 的行数。
|
||||
|
||||
添加一个 `\f` (一个「换页」的转义字符)可以使 **FastAPI** 在那一位置截断用于 OpenAPI 的输出。
|
||||
|
||||
剩余部分不会出现在文档中,但是其他工具(比如 Sphinx)可以使用剩余部分。
|
||||
|
||||
|
||||
```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29"
|
||||
{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!}
|
||||
```
|
||||
65
docs/zh/docs/advanced/response-directly.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# 直接返回响应
|
||||
|
||||
当你创建一个 **FastAPI** *路径操作* 时,你可以正常返回以下任意一种数据:`dict`,`list`,Pydantic 模型,数据库模型等等。
|
||||
|
||||
**FastAPI** 默认会使用 `jsonable_encoder` 将这些类型的返回值转换成 JSON 格式,`jsonable_encoder` 在 [JSON 兼容编码器](../tutorial/encoder.md){.internal-link target=_blank} 中有阐述。
|
||||
|
||||
然后,**FastAPI** 会在后台将这些兼容 JSON 的数据(比如字典)放到一个 `JSONResponse` 中,该 `JSONResponse` 会用来发送响应给客户端。
|
||||
|
||||
但是你可以在你的 *路径操作* 中直接返回一个 `JSONResponse`。
|
||||
|
||||
直接返回响应可能会有用处,比如返回自定义的响应头和 cookies。
|
||||
|
||||
## 返回 `Response`
|
||||
|
||||
事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。
|
||||
|
||||
!!! tip "小贴士"
|
||||
`JSONResponse` 本身是一个 `Response` 的子类。
|
||||
|
||||
当你返回一个 `Response` 时,**FastAPI** 会直接传递它。
|
||||
|
||||
**FastAPI** 不会用 Pydantic 模型做任何数据转换,不会将响应内容转换成任何类型,等等。
|
||||
|
||||
这种特性给你极大的可扩展性。你可以返回任何数据类型,重写任何数据声明或者校验,等等。
|
||||
|
||||
## 在 `Response` 中使用 `jsonable_encoder`
|
||||
|
||||
由于 **FastAPI** 并未对你返回的 `Response` 做任何改变,你必须确保你已经准备好响应内容。
|
||||
|
||||
例如,如果不首先将 Pydantic 模型转换为 `dict`,并将所有数据类型(如 `datetime`、`UUID` 等)转换为兼容 JSON 的类型,则不能将其放入JSONResponse中。
|
||||
|
||||
对于这些情况,在将数据传递给响应之前,你可以使用 `jsonable_encoder` 来转换你的数据。
|
||||
|
||||
|
||||
```Python hl_lines="4 6 20 21"
|
||||
{!../../../docs_src/response_directly/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "技术细节"
|
||||
你也可以使用 `from starlette.responses import JSONResponse`。
|
||||
|
||||
出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。
|
||||
|
||||
## 返回自定义 `Response`
|
||||
|
||||
上面的例子展示了需要的所有部分,但还不够实用,因为你本可以只是直接返回 `item`,而**FastAPI** 默认帮你把这个 `item` 放到 `JSONResponse` 中,又默认将其转换成了 `dict`等等。
|
||||
|
||||
现在,让我们看看你如何才能返回一个自定义的响应。
|
||||
|
||||
假设你想要返回一个 <a href="https://en.wikipedia.org/wiki/XML" class="external-link" target="_blank">XML</a> 响应。
|
||||
|
||||
你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。
|
||||
|
||||
```Python hl_lines="1 18"
|
||||
{!../../../docs_src/response_directly/tutorial002.py!}
|
||||
```
|
||||
|
||||
## 说明
|
||||
|
||||
当你直接返回 `Response` 时,它的数据既没有校验,又不会进行转换(序列化),也不会自动生成文档。
|
||||
|
||||
但是你仍可以参考 [OpenApI 中的额外响应](additional-responses.md){.internal-link target=_blank} 给响应编写文档。
|
||||
|
||||
在后续的章节中你可以了解到如何使用/声明这些自定义的 `Response` 的同时还保留自动化的数据转换和文档等。
|
||||
|
||||
34
docs/zh/docs/benchmarks.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# 基准测试
|
||||
|
||||
第三方机构 TechEmpower 的基准测试表明在 Uvicorn 下运行的 **FastAPI** 应用程序是 <a href="https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class="external-link" target="_blank">可用的最快的 Python 框架之一</a>,仅次与 Starlette 和 Uvicorn 本身 (由 FastAPI 内部使用)。(*)
|
||||
|
||||
但是在查看基准得分和对比时,请注意以下几点。
|
||||
|
||||
## 基准测试和速度
|
||||
|
||||
当你查看基准测试时,几个不同类型的工具被等效地做比较是很常见的情况。
|
||||
|
||||
具体来说,是将 Uvicorn,Starlette 和 FastAPI 一起比较(在许多其它工具中)。
|
||||
|
||||
该工具解决的问题最简单,它将获得更好的性能。而且大多数基准测试并未测试该工具提供的其他功能。
|
||||
|
||||
层次结构如下:
|
||||
|
||||
* **Uvicorn**:ASGI服务器
|
||||
* **Starlette**:(使用 Uvicorn)网络微框架
|
||||
* **FastAPI**:(使用 Starlette) 具有多个附加功能的API微框架,用于构建API,进行数据验证等。
|
||||
|
||||
* **Uvicorn**:
|
||||
* 具有最佳性能,因为除了服务器本身外,它没有太多额外的代码。
|
||||
* 您不会直接在 Uvicorn 中编写应用程序。这意味着您的代码至少必须包含 Starlette(或 **FastAPI**)提供的代码。如果您这样做了(即直接在 Uvicorn 中编写应用程序),最终的应用程序会和使用了框架并且最小化了应用代码和 bug 的情况具有相同的性能损耗。
|
||||
* 如果要对比与 Uvicorn 对标的服务器,请将其与 Daphne,Hypercorn,uWSGI等应用服务器进行比较。
|
||||
* **Starlette**:
|
||||
* 在 Uvicorn 后使用 Starlette,性能会略有下降。实际上,Starlette 使用 Uvicorn运行。因此,由于必须执行更多的代码,它只会比 Uvicorn 更慢。
|
||||
* 但它为您提供了构建简单的网络程序的工具,并具有基于路径的路由等功能。
|
||||
* 如果想对比与 Starlette 对标的开发框架,请将其与 Sanic,Flask,Django 等网络框架(或微框架)进行比较。
|
||||
* **FastAPI**:
|
||||
* 与 Starlette 使用 Uvicorn 一样,由于 **FastAPI** 使用 Starlette,因此 FastAPI 不能比 Starlette 更快。
|
||||
* FastAPI 在 Starlette 基础上提供了更多功能。例如在开发 API 时,所需的数据验证和序列化功能。FastAPI 可以帮助您自动生成 API文档,(文档在应用程序启动时自动生成,所以不会增加应用程序运行时的开销)。
|
||||
* 如果您不使用 FastAPI 而直接使用 Starlette(或诸如 Sanic,Flask,Responder 等其它工具),您则要自己实现所有的数据验证和序列化。那么最终您的应用程序会和使用 FastAPI 构建的程序有相同的开销。一般这种数据验证和序列化的操作在您应用程序的代码中会占很大比重。
|
||||
* 因此,通过使用 FastAPI 意味着您可以节省开发时间,减少编码错误,用更少的编码实现其功能,并且相比不使用 FastAPI 您很大可能会获得相同或更好的性能(因为那样您必须在代码中实现所有相同的功能)。
|
||||
* 如果您想对比与 FastAPI 对标的开发框架,请与能够提供数据验证,序列化和带有自动文档生成的网络应用程序框架(或工具集)进行对比,例如具有集成自动数据验证,序列化和自动化文档的 Flask-apispec,NestJS,Molten 等。
|
||||
@@ -338,7 +338,7 @@ Traefik 也集成了 Docker,所以你也可以在每个应用的配置中声
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
@@ -26,10 +26,6 @@
|
||||
|
||||
## 加入聊天室
|
||||
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
|
||||
加入 Gitter 上的聊天室:<a href="https://gitter.im/tiangolo/fastapi" class="external-link" target="_blank">https://gitter.im/tiangolo/fastapi</a>。
|
||||
|
||||
在这里你可以快速提问、帮助他人、分享想法等。
|
||||
|
||||
@@ -14,9 +14,6 @@
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/fastapi?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
<a href="https://gitter.im/tiangolo/fastapi?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge" target="_blank">
|
||||
<img src="https://badges.gitter.im/tiangolo/fastapi.svg" alt="Join the chat at https://gitter.im/tiangolo/fastapi">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -131,7 +128,7 @@ $ pip install fastapi
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
244
docs/zh/docs/tutorial/body-nested-models.md
Normal file
@@ -0,0 +1,244 @@
|
||||
# 请求体 - 嵌套模型
|
||||
|
||||
使用 **FastAPI**,你可以定义、校验、记录文档并使用任意深度嵌套的模型(归功于Pydantic)。
|
||||
|
||||
## List 字段
|
||||
|
||||
你可以将一个属性定义为拥有子元素的类型。例如 Python `list`:
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!../../../docs_src/body_nested_models/tutorial001.py!}
|
||||
```
|
||||
|
||||
这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。
|
||||
|
||||
## 具有子类型的 List 字段
|
||||
|
||||
但是 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!}
|
||||
```
|
||||
|
||||
## Set 类型
|
||||
|
||||
但是随后我们考虑了一下,意识到标签不应该重复,它们很大可能会是唯一的字符串。
|
||||
|
||||
Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `set`。
|
||||
|
||||
然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`:
|
||||
|
||||
```Python hl_lines="1 14"
|
||||
{!../../../docs_src/body_nested_models/tutorial003.py!}
|
||||
```
|
||||
|
||||
这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。
|
||||
|
||||
而且,每当你输出该数据时,即使源数据有重复,它们也将作为一组唯一项输出。
|
||||
|
||||
并且还会被相应地标注 / 记录文档。
|
||||
|
||||
## 嵌套模型
|
||||
|
||||
Pydantic 模型的每个属性都具有类型。
|
||||
|
||||
但是这个类型本身可以是另一个 Pydantic 模型。
|
||||
|
||||
因此,你可以声明拥有特定属性名称、类型和校验的深度嵌套的 JSON 对象。
|
||||
|
||||
上述这些都可以任意的嵌套。
|
||||
|
||||
### 定义子模型
|
||||
|
||||
例如,我们可以定义一个 `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` 继承的更复杂的单一值类型。
|
||||
|
||||
要了解所有的可用选项,请查看关于 <a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">来自 Pydantic 的外部类型</a> 的文档。你将在下一章节中看到一些示例。
|
||||
|
||||
例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`:
|
||||
|
||||
```Python hl_lines="4 10"
|
||||
{!../../../docs_src/body_nested_models/tutorial005.py!}
|
||||
```
|
||||
|
||||
该字符串将被检查是否为有效的 URL,并在 JSON Schema / 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` 键现在具有一组 image 对象是如何发生的。
|
||||
|
||||
## 深度嵌套模型
|
||||
|
||||
你可以定义任意深度的嵌套模型:
|
||||
|
||||
```Python hl_lines="9 14 20 23 27"
|
||||
{!../../../docs_src/body_nested_models/tutorial007.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。
|
||||
|
||||
## 纯列表请求体
|
||||
|
||||
如果你期望的 JSON 请求体的最外层是一个 JSON `array`(即 Python `list`),则可以在路径操作函数的参数中声明此类型,就像声明 Pydantic 模型一样:
|
||||
|
||||
```Python
|
||||
images: List[Image]
|
||||
```
|
||||
|
||||
例如:
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!../../../docs_src/body_nested_models/tutorial008.py!}
|
||||
```
|
||||
|
||||
## 无处不在的编辑器支持
|
||||
|
||||
你可以随处获得编辑器支持。
|
||||
|
||||
即使是列表中的元素:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/tutorial/body-nested-models/image01.png">
|
||||
|
||||
如果你直接使用 `dict` 而不是 Pydantic 模型,那你将无法获得这种编辑器支持。
|
||||
|
||||
但是你根本不必担心这两者,传入的字典会自动被转换,你的输出也会自动被转换为 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 模型提供的极高灵活性,同时保持代码的简单、简短和优雅。
|
||||
|
||||
而且还具有下列好处:
|
||||
|
||||
* 编辑器支持(处处皆可自动补全!)
|
||||
* 数据转换(也被称为解析/序列化)
|
||||
* 数据校验
|
||||
* 模式文档
|
||||
* 自动生成的文档
|
||||
199
docs/zh/docs/tutorial/extra-models.md
Normal file
@@ -0,0 +1,199 @@
|
||||
# 额外的模型
|
||||
|
||||
我们从前面的示例继续,拥有多个相关的模型是很常见的。
|
||||
|
||||
对用户模型来说尤其如此,因为:
|
||||
|
||||
* **输入模型**需要拥有密码属性。
|
||||
* **输出模型**不应该包含密码。
|
||||
* **数据库模型**很可能需要保存密码的哈希值。
|
||||
|
||||
!!! 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`(它是一个 `dict` 而不是 Pydantic 模型对象)。
|
||||
|
||||
如果我们调用:
|
||||
|
||||
```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** 的核心思想之一。
|
||||
|
||||
因为代码重复会增加出现 bug、安全性问题、代码失步问题(当你在一个位置更新了代码但没有在其他位置更新)等的可能性。
|
||||
|
||||
上面的这些模型都共享了大量数据,并拥有重复的属性名称和类型。
|
||||
|
||||
我们可以做得更好。
|
||||
|
||||
我们可以声明一个 `UserBase` 模型作为其他模型的基类。然后我们可以创建继承该模型属性(类型声明,校验等)的子类。
|
||||
|
||||
所有的数据转换、校验、文档生成等仍将正常运行。
|
||||
|
||||
这样,我们可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码)。
|
||||
|
||||
```Python hl_lines="9 15-16 19-20 23-24"
|
||||
{!../../../docs_src/extra_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
## `Union` 或者 `anyOf`
|
||||
|
||||
你可以将一个响应声明为两种类型的 `Union`,这意味着该响应将是两种类型中的任何一种。
|
||||
|
||||
这将在 OpenAPI 中使用 `anyOf` 进行定义。
|
||||
|
||||
为此,请使用标准的 Python 类型提示 <a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>:
|
||||
|
||||
|
||||
!!! note
|
||||
定义一个 <a href="https://pydantic-docs.helpmanual.io/usage/types/#unions" class="external-link" target="_blank">`Union`</a> 类型时,首先包括最详细的类型,然后是不太详细的类型。在下面的示例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。
|
||||
|
||||
```Python hl_lines="1 14-15 18-20 33"
|
||||
{!../../../docs_src/extra_models/tutorial003.py!}
|
||||
```
|
||||
|
||||
## 模型列表
|
||||
|
||||
你可以用同样的方式声明由对象列表构成的响应。
|
||||
|
||||
为此,请使用标准的 Python `typing.List`:
|
||||
|
||||
```Python hl_lines="1 20"
|
||||
{!../../../docs_src/extra_models/tutorial004.py!}
|
||||
```
|
||||
|
||||
## 任意 `dict` 构成的响应
|
||||
|
||||
你还可以使用一个任意的普通 `dict` 声明响应,仅声明键和值的类型,而不使用 Pydantic 模型。
|
||||
|
||||
如果你事先不知道有效的字段/属性名称(对于 Pydantic 模型是必需的),这将很有用。
|
||||
|
||||
在这种情况下,你可以使用 `typing.Dict`:
|
||||
|
||||
```Python hl_lines="1 8"
|
||||
{!../../../docs_src/extra_models/tutorial005.py!}
|
||||
```
|
||||
|
||||
## 总结
|
||||
|
||||
使用多个 Pydantic 模型,并针对不同场景自由地继承。
|
||||
|
||||
如果一个实体必须能够具有不同的「状态」,你无需为每个状态的实体定义单独的数据模型。以用户「实体」为例,其状态有包含 `password`、包含 `password_hash` 以及不含密码。
|
||||
@@ -64,7 +64,7 @@ $ pip install fastapi[all]
|
||||
并且安装`uvicorn`来作为服务器:
|
||||
|
||||
```
|
||||
pip install uvicorn
|
||||
pip install uvicorn[standard]
|
||||
```
|
||||
|
||||
然后对你想使用的每个可选依赖项也执行相同的操作。
|
||||
|
||||
209
docs/zh/docs/tutorial/response-model.md
Normal file
@@ -0,0 +1,209 @@
|
||||
# 响应模型
|
||||
|
||||
你可以在任意的*路径操作*中使用 `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` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
|
||||
|
||||
它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。
|
||||
|
||||
FastAPI 将使用此 `response_model` 来:
|
||||
|
||||
* 将输出数据转换为其声明的类型。
|
||||
* 校验数据。
|
||||
* 在 OpenAPI 的*路径操作*中为响应添加一个 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 都会在响应中返回相同的密码。
|
||||
|
||||
在这个案例中,这可能不算是问题,因为用户自己正在发送密码。
|
||||
|
||||
但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。
|
||||
|
||||
!!! danger
|
||||
永远不要存储用户的明文密码,也不要在响应中发送密码。
|
||||
|
||||
## 添加输出模型
|
||||
|
||||
相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型:
|
||||
|
||||
```Python hl_lines="9 11 16"
|
||||
{!../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户:
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型:
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。
|
||||
|
||||
## 在文档中查看
|
||||
|
||||
当你查看自动化文档时,你可以检查输入模型和输出模型是否都具有自己的 JSON Schema:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/tutorial/response-model/image01.png">
|
||||
|
||||
并且两种模型都将在交互式 API 文档中使用:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/tutorial/response-model/image02.png">
|
||||
|
||||
## 响应模型编码参数
|
||||
|
||||
你的响应模型可以具有默认值,例如:
|
||||
|
||||
```Python hl_lines="11 13-14"
|
||||
{!../../../docs_src/response_model/tutorial004.py!}
|
||||
```
|
||||
|
||||
* `description: Optional[str] = None` 具有默认值 `None`。
|
||||
* `tax: float = 10.5` 具有默认值 `10.5`.
|
||||
* `tags: List[str] = []` 具有一个空列表作为默认值: `[]`.
|
||||
|
||||
但如果它们并没有存储实际的值,你可能想从结果中忽略它们的默认值。
|
||||
|
||||
举个例子,当你在 NoSQL 数据库中保存了具有许多可选属性的模型,但你又不想发送充满默认值的很长的 JSON 响应。
|
||||
|
||||
### 使用 `response_model_exclude_unset` 参数
|
||||
|
||||
你可以设置*路径操作装饰器*的 `response_model_exclude_unset=True` 参数:
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!../../../docs_src/response_model/tutorial004.py!}
|
||||
```
|
||||
|
||||
然后响应中将不会包含那些默认值,而是仅有实际设置的值。
|
||||
|
||||
因此,如果你向*路径操作*发送 ID 为 `foo` 的商品的请求,则响应(不包括默认值)将为:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"name": "Foo",
|
||||
"price": 50.2
|
||||
}
|
||||
```
|
||||
|
||||
!!! info
|
||||
FastAPI 通过 Pydantic 模型的 `.dict()` 配合 <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">该方法的 `exclude_unset` 参数</a> 来实现此功能。
|
||||
|
||||
!!! info
|
||||
你还可以使用:
|
||||
|
||||
* `response_model_exclude_defaults=True`
|
||||
* `response_model_exclude_none=True`
|
||||
|
||||
参考 <a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydantic 文档</a> 中对 `exclude_defaults` 和 `exclude_none` 的描述。
|
||||
|
||||
#### 默认值字段有实际值的数据
|
||||
|
||||
但是,如果你的数据在具有默认值的模型字段中有实际的值,例如 ID 为 `bar` 的项:
|
||||
|
||||
```Python hl_lines="3 5"
|
||||
{
|
||||
"name": "Bar",
|
||||
"description": "The bartenders",
|
||||
"price": 62,
|
||||
"tax": 20.2
|
||||
}
|
||||
```
|
||||
|
||||
这些值将包含在响应中。
|
||||
|
||||
#### 具有与默认值相同值的数据
|
||||
|
||||
如果数据具有与默认值相同的值,例如 ID 为 `baz` 的项:
|
||||
|
||||
```Python hl_lines="3 5-6"
|
||||
{
|
||||
"name": "Baz",
|
||||
"description": None,
|
||||
"price": 50.2,
|
||||
"tax": 10.5,
|
||||
"tags": []
|
||||
}
|
||||
```
|
||||
|
||||
即使 `description`、`tax` 和 `tags` 具有与默认值相同的值,FastAPI 足够聪明 (实际上是 Pydantic 足够聪明) 去认识到这一点,它们的值被显式地所设定(而不是取自默认值)。
|
||||
|
||||
因此,它们将包含在 JSON 响应中。
|
||||
|
||||
!!! tip
|
||||
请注意默认值可以是任何值,而不仅是`None`。
|
||||
|
||||
它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。
|
||||
|
||||
### `response_model_include` 和 `response_model_exclude`
|
||||
|
||||
你还可以使用*路径操作装饰器*的 `response_model_include` 和 `response_model_exclude` 参数。
|
||||
|
||||
它们接收一个由属性名称 `str` 组成的 `set` 来包含(忽略其他的)或者排除(包含其他的)这些属性。
|
||||
|
||||
如果你只有一个 Pydantic 模型,并且想要从输出中移除一些数据,则可以使用这种快捷方法。
|
||||
|
||||
!!! tip
|
||||
但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。
|
||||
|
||||
这是因为即使使用 `response_model_include` 或 `response_model_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"])`。
|
||||
|
||||
#### 使用 `list` 而不是 `set`
|
||||
|
||||
如果你忘记使用 `set` 而是使用 `list` 或 `tuple`,FastAPI 仍会将其转换为 `set` 并且正常工作:
|
||||
|
||||
```Python hl_lines="31 37"
|
||||
{!../../../docs_src/response_model/tutorial006.py!}
|
||||
```
|
||||
|
||||
## 总结
|
||||
|
||||
使用*路径操作装饰器*的 `response_model` 参数来定义响应模型,特别是确保私有数据被过滤掉。
|
||||
|
||||
使用 `response_model_exclude_unset` 来仅返回显式设定的值。
|
||||
89
docs/zh/docs/tutorial/response-status-code.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# 响应状态码
|
||||
|
||||
与指定响应模型的方式相同,你也可以在以下任意的*路径操作*中使用 `status_code` 参数来声明用于响应的 HTTP 状态码:
|
||||
|
||||
* `@app.get()`
|
||||
* `@app.post()`
|
||||
* `@app.put()`
|
||||
* `@app.delete()`
|
||||
* 等等。
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!../../../docs_src/response_status_code/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note
|
||||
注意,`status_code` 是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。
|
||||
|
||||
`status_code` 参数接收一个表示 HTTP 状态码的数字。
|
||||
|
||||
!!! info
|
||||
`status_code` 也能够接收一个 `IntEnum` 类型,比如 Python 的 <a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>。
|
||||
|
||||
它将会:
|
||||
|
||||
* 在响应中返回该状态码。
|
||||
* 在 OpenAPI 模式中(以及在用户界面中)将其记录为:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image01.png">
|
||||
|
||||
!!! note
|
||||
一些响应状态码(请参阅下一部分)表示响应没有响应体。
|
||||
|
||||
FastAPI 知道这一点,并将生成表明没有响应体的 OpenAPI 文档。
|
||||
|
||||
## 关于 HTTP 状态码
|
||||
|
||||
!!! note
|
||||
如果你已经了解什么是 HTTP 状态码,请跳到下一部分。
|
||||
|
||||
在 HTTP 协议中,你将发送 3 位数的数字状态码作为响应的一部分。
|
||||
|
||||
这些状态码有一个识别它们的关联名称,但是重要的还是数字。
|
||||
|
||||
简而言之:
|
||||
|
||||
* `100` 及以上状态码用于「消息」响应。你很少直接使用它们。具有这些状态代码的响应不能带有响应体。
|
||||
* **`200`** 及以上状态码用于「成功」响应。这些是你最常使用的。
|
||||
* `200` 是默认状态代码,它表示一切「正常」。
|
||||
* 另一个例子会是 `201`,「已创建」。它通常在数据库中创建了一条新记录后使用。
|
||||
* 一个特殊的例子是 `204`,「无内容」。此响应在没有内容返回给客户端时使用,因此该响应不能包含响应体。
|
||||
* **`300`** 及以上状态码用于「重定向」。具有这些状态码的响应可能有或者可能没有响应体,但 `304`「未修改」是个例外,该响应不得含有响应体。
|
||||
* **`400`** 及以上状态码用于「客户端错误」响应。这些可能是你第二常使用的类型。
|
||||
* 一个例子是 `404`,用于「未找到」响应。
|
||||
* 对于来自客户端的一般错误,你可以只使用 `400`。
|
||||
* `500` 及以上状态码用于服务器端错误。你几乎永远不会直接使用它们。当你的应用程序代码或服务器中的某些部分出现问题时,它将自动返回这些状态代码之一。
|
||||
|
||||
!!! tip
|
||||
要了解有关每个状态代码以及适用场景的更多信息,请查看 <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="external-link" target="_blank"><abbr title="Mozilla Developer Network">MDN</abbr> 关于 HTTP 状态码的文档</a>。
|
||||
|
||||
## 记住名称的捷径
|
||||
|
||||
让我们再次看看之前的例子:
|
||||
|
||||
```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!}
|
||||
```
|
||||
|
||||
它们只是一种便捷方式,它们具有同样的数字代码,但是这样使用你就可以使用编辑器的自动补全功能来查找它们:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/tutorial/response-status-code/image02.png">
|
||||
|
||||
!!! note "技术细节"
|
||||
你也可以使用 `from starlette import status`。
|
||||
|
||||
为了给你(即开发者)提供方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。
|
||||
|
||||
## 更改默认状态码
|
||||
|
||||
稍后,在[高级用户指南](../advanced/response-change-status-code.md){.internal-link target=_blank}中你将了解如何返回与在此声明的默认状态码不同的状态码。
|
||||
58
docs/zh/docs/tutorial/schema-extra-example.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# 模式的额外信息 - 例子
|
||||
|
||||
您可以在JSON模式中定义额外的信息。
|
||||
|
||||
一个常见的用例是添加一个将在文档中显示的`example`。
|
||||
|
||||
有几种方法可以声明额外的 JSON 模式信息。
|
||||
|
||||
## Pydantic `schema_extra`
|
||||
|
||||
您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如<a href="https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization" class="external-link" target="_blank">Pydantic 文档:定制 Schema </a>中所述:
|
||||
|
||||
```Python hl_lines="15-23"
|
||||
{!../../../docs_src/schema_extra_example/tutorial001.py!}
|
||||
```
|
||||
|
||||
这些额外的信息将按原样添加到输出的JSON模式中。
|
||||
|
||||
## `Field` 的附加参数
|
||||
|
||||
在 `Field`, `Path`, `Query`, `Body` 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 `example`:
|
||||
|
||||
```Python hl_lines="4 10-13"
|
||||
{!../../../docs_src/schema_extra_example/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! warning
|
||||
请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。
|
||||
|
||||
## `Body` 额外参数
|
||||
|
||||
你可以通过传递额外信息给 `Field` 同样的方式操作`Path`, `Query`, `Body`等。
|
||||
|
||||
比如,你可以将请求体的一个 `example` 传递给 `Body`:
|
||||
|
||||
```Python hl_lines="21-26"
|
||||
{!../../../docs_src/schema_extra_example/tutorial003.py!}
|
||||
```
|
||||
|
||||
## 文档 UI 中的例子
|
||||
|
||||
使用上面的任何方法,它在 `/docs` 中看起来都是这样的:
|
||||
|
||||
<img src="/img/tutorial/body-fields/image01.png">
|
||||
|
||||
## 技术细节
|
||||
|
||||
关于 `example` 和 `examples`...
|
||||
|
||||
JSON Schema在最新的一个版本中定义了一个字段 <a href="https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.9.5" class="external-link" target="_blank">`examples`</a> ,但是 OpenAPI 基于之前的一个旧版JSON Schema,并没有 `examples`.
|
||||
|
||||
所以 OpenAPI为了相似的目的定义了自己的 <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#fixed-fields-20" class="external-link" target="_blank">`example`</a> (使用 `example`, 而不是 `examples`), 这也是文档 UI 所使用的 (使用 Swagger UI).
|
||||
|
||||
所以,虽然 `example` 不是JSON Schema的一部分,但它是OpenAPI的一部分,这将被文档UI使用。
|
||||
|
||||
## 其他信息
|
||||
|
||||
同样的方法,你可以添加你自己的额外信息,这些信息将被添加到每个模型的JSON模式中,例如定制前端用户界面,等等。
|
||||
@@ -3,10 +3,23 @@ site_description: FastAPI framework, high performance, easy to learn, fast to co
|
||||
site_url: https://fastapi.tiangolo.com/zh/
|
||||
theme:
|
||||
name: material
|
||||
custom_dir: overrides
|
||||
palette:
|
||||
scheme: preference
|
||||
- scheme: default
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb-outline
|
||||
name: Switch to light mode
|
||||
- scheme: slate
|
||||
primary: teal
|
||||
accent: amber
|
||||
toggle:
|
||||
icon: material/lightbulb
|
||||
name: Switch to dark mode
|
||||
features:
|
||||
- search.suggest
|
||||
- search.highlight
|
||||
icon:
|
||||
repo: fontawesome/brands/github-alt
|
||||
logo: https://fastapi.tiangolo.com/img/icon-white.svg
|
||||
@@ -33,6 +46,7 @@ nav:
|
||||
- ko: /ko/
|
||||
- pt: /pt/
|
||||
- ru: /ru/
|
||||
- sq: /sq/
|
||||
- tr: /tr/
|
||||
- uk: /uk/
|
||||
- zh: /zh/
|
||||
@@ -48,9 +62,21 @@ nav:
|
||||
- tutorial/path-params-numeric-validations.md
|
||||
- tutorial/body-multiple-params.md
|
||||
- tutorial/body-fields.md
|
||||
- tutorial/body-nested-models.md
|
||||
- tutorial/response-model.md
|
||||
- tutorial/extra-models.md
|
||||
- tutorial/response-status-code.md
|
||||
- tutorial/schema-extra-example.md
|
||||
- 高级用户指南:
|
||||
- advanced/index.md
|
||||
- advanced/path-operation-advanced-configuration.md
|
||||
- advanced/additional-status-codes.md
|
||||
- advanced/response-directly.md
|
||||
- advanced/custom-response.md
|
||||
- deployment.md
|
||||
- contributing.md
|
||||
- help-fastapi.md
|
||||
- benchmarks.md
|
||||
markdown_extensions:
|
||||
- toc:
|
||||
permalink: true
|
||||
@@ -81,6 +107,31 @@ extra:
|
||||
link: https://medium.com/@tiangolo
|
||||
- icon: fontawesome/solid/globe
|
||||
link: https://tiangolo.com
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /es/
|
||||
name: es - español
|
||||
- link: /fr/
|
||||
name: fr - français
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
name: ko - 한국어
|
||||
- link: /pt/
|
||||
name: pt - português
|
||||
- link: /ru/
|
||||
name: ru - русский язык
|
||||
- link: /sq/
|
||||
name: sq - shqip
|
||||
- link: /tr/
|
||||
name: tr - Türkçe
|
||||
- link: /uk/
|
||||
name: uk - українська мова
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
extra_css:
|
||||
- https://fastapi.tiangolo.com/css/termynal.css
|
||||
- https://fastapi.tiangolo.com/css/custom.css
|
||||
@@ -88,5 +139,3 @@ extra_javascript:
|
||||
- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js
|
||||
- https://fastapi.tiangolo.com/js/termynal.js
|
||||
- https://fastapi.tiangolo.com/js/custom.js
|
||||
- https://fastapi.tiangolo.com/js/chat.js
|
||||
- https://sidecar.gitter.im/dist/sidecar.v1.js
|
||||
|
||||
0
docs/zh/overrides/.gitignore
vendored
Normal file
11
docs_src/bigger_applications/app/dependencies.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
|
||||
async def get_token_header(x_token: str = Header(...)):
|
||||
if x_token != "fake-super-secret-token":
|
||||
raise HTTPException(status_code=400, detail="X-Token header invalid")
|
||||
|
||||
|
||||
async def get_query_token(token: str):
|
||||
if token != "jessica":
|
||||
raise HTTPException(status_code=400, detail="No Jessica token provided")
|
||||
8
docs_src/bigger_applications/app/internal/admin.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/")
|
||||
async def update_admin():
|
||||
return {"message": "Admin getting schwifty"}
|
||||
@@ -1,20 +1,23 @@
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException
|
||||
from fastapi import Depends, FastAPI
|
||||
|
||||
from .dependencies import get_query_token, get_token_header
|
||||
from .internal import admin
|
||||
from .routers import items, users
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
async def get_token_header(x_token: str = Header(...)):
|
||||
if x_token != "fake-super-secret-token":
|
||||
raise HTTPException(status_code=400, detail="X-Token header invalid")
|
||||
app = FastAPI(dependencies=[Depends(get_query_token)])
|
||||
|
||||
|
||||
app.include_router(users.router)
|
||||
app.include_router(items.router)
|
||||
app.include_router(
|
||||
items.router,
|
||||
prefix="/items",
|
||||
tags=["items"],
|
||||
admin.router,
|
||||
prefix="/admin",
|
||||
tags=["admin"],
|
||||
dependencies=[Depends(get_token_header)],
|
||||
responses={404: {"description": "Not found"}},
|
||||
responses={418: {"description": "I'm a teapot"}},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"message": "Hello Bigger Applications!"}
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
router = APIRouter()
|
||||
from ..dependencies import get_token_header
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/items",
|
||||
tags=["items"],
|
||||
dependencies=[Depends(get_token_header)],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
|
||||
fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}}
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def read_items():
|
||||
return [{"name": "Item Foo"}, {"name": "item Bar"}]
|
||||
return fake_items_db
|
||||
|
||||
|
||||
@router.get("/{item_id}")
|
||||
async def read_item(item_id: str):
|
||||
return {"name": "Fake Specific Item", "item_id": item_id}
|
||||
if item_id not in fake_items_db:
|
||||
raise HTTPException(status_code=404, detail="Item not found")
|
||||
return {"name": fake_items_db[item_id]["name"], "item_id": item_id}
|
||||
|
||||
|
||||
@router.put(
|
||||
@@ -19,6 +31,8 @@ async def read_item(item_id: str):
|
||||
responses={403: {"description": "Operation forbidden"}},
|
||||
)
|
||||
async def update_item(item_id: str):
|
||||
if item_id != "foo":
|
||||
raise HTTPException(status_code=403, detail="You can only update the item: foo")
|
||||
return {"item_id": item_id, "name": "The Fighters"}
|
||||
if item_id != "plumbus":
|
||||
raise HTTPException(
|
||||
status_code=403, detail="You can only update the item: plumbus"
|
||||
)
|
||||
return {"item_id": item_id, "name": "The great Plumbus"}
|
||||
|
||||
@@ -5,7 +5,7 @@ router = APIRouter()
|
||||
|
||||
@router.get("/users/", tags=["users"])
|
||||
async def read_users():
|
||||
return [{"username": "Foo"}, {"username": "Bar"}]
|
||||
return [{"username": "Rick"}, {"username": "Morty"}]
|
||||
|
||||
|
||||
@router.get("/users/me", tags=["users"])
|
||||
|
||||
25
docs_src/dependencies/tutorial012.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException
|
||||
|
||||
|
||||
async def verify_token(x_token: str = Header(...)):
|
||||
if x_token != "fake-super-secret-token":
|
||||
raise HTTPException(status_code=400, detail="X-Token header invalid")
|
||||
|
||||
|
||||
async def verify_key(x_key: str = Header(...)):
|
||||
if x_key != "fake-super-secret-key":
|
||||
raise HTTPException(status_code=400, detail="X-Key header invalid")
|
||||
return x_key
|
||||
|
||||
|
||||
app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
|
||||
|
||||
|
||||
@app.get("/items/")
|
||||
async def read_items():
|
||||
return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
|
||||
|
||||
|
||||
@app.get("/users/")
|
||||
async def read_users():
|
||||
return [{"username": "Rick"}, {"username": "Morty"}]
|
||||
@@ -1,7 +1,6 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, FastAPI
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, HttpUrl
|
||||
|
||||
app = FastAPI()
|
||||
@@ -23,11 +22,11 @@ class InvoiceEventReceived(BaseModel):
|
||||
ok: bool
|
||||
|
||||
|
||||
invoices_callback_router = APIRouter(default_response_class=JSONResponse)
|
||||
invoices_callback_router = APIRouter()
|
||||
|
||||
|
||||
@invoices_callback_router.post(
|
||||
"{$callback_url}/invoices/{$request.body.id}", response_model=InvoiceEventReceived,
|
||||
"{$callback_url}/invoices/{$request.body.id}", response_model=InvoiceEventReceived
|
||||
)
|
||||
def invoice_notification(body: InvoiceEvent):
|
||||
pass
|
||||
|
||||
@@ -1,25 +1,24 @@
|
||||
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
|
||||
|
||||
__version__ = "0.61.2"
|
||||
__version__ = "0.63.0"
|
||||
|
||||
from starlette import status
|
||||
from starlette import status as status
|
||||
|
||||
from .applications import FastAPI
|
||||
from .background import BackgroundTasks
|
||||
from .datastructures import UploadFile
|
||||
from .exceptions import HTTPException
|
||||
from .param_functions import (
|
||||
Body,
|
||||
Cookie,
|
||||
Depends,
|
||||
File,
|
||||
Form,
|
||||
Header,
|
||||
Path,
|
||||
Query,
|
||||
Security,
|
||||
)
|
||||
from .requests import Request
|
||||
from .responses import Response
|
||||
from .routing import APIRouter
|
||||
from .websockets import WebSocket, WebSocketDisconnect
|
||||
from .applications import FastAPI as FastAPI
|
||||
from .background import BackgroundTasks as BackgroundTasks
|
||||
from .datastructures import UploadFile as UploadFile
|
||||
from .exceptions import HTTPException as HTTPException
|
||||
from .param_functions import Body as Body
|
||||
from .param_functions import Cookie as Cookie
|
||||
from .param_functions import Depends as Depends
|
||||
from .param_functions import File as File
|
||||
from .param_functions import Form as Form
|
||||
from .param_functions import Header as Header
|
||||
from .param_functions import Path as Path
|
||||
from .param_functions import Query as Query
|
||||
from .param_functions import Security as Security
|
||||
from .requests import Request as Request
|
||||
from .responses import Response as Response
|
||||
from .routing import APIRouter as APIRouter
|
||||
from .websockets import WebSocket as WebSocket
|
||||
from .websockets import WebSocketDisconnect as WebSocketDisconnect
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
from typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union
|
||||
from typing import Any, Callable, Coroutine, Dict, List, Optional, Sequence, Type, Union
|
||||
|
||||
from fastapi import routing
|
||||
from fastapi.concurrency import AsyncExitStack
|
||||
from fastapi.datastructures import Default, DefaultPlaceholder
|
||||
from fastapi.encoders import DictIntStrAny, SetIntStr
|
||||
from fastapi.exception_handlers import (
|
||||
http_exception_handler,
|
||||
@@ -16,6 +17,7 @@ from fastapi.openapi.docs import (
|
||||
)
|
||||
from fastapi.openapi.utils import get_openapi
|
||||
from fastapi.params import Depends
|
||||
from fastapi.types import DecoratedCallable
|
||||
from starlette.applications import Starlette
|
||||
from starlette.datastructures import State
|
||||
from starlette.exceptions import HTTPException
|
||||
@@ -23,7 +25,7 @@ from starlette.middleware import Middleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import HTMLResponse, JSONResponse, Response
|
||||
from starlette.routing import BaseRoute
|
||||
from starlette.types import Receive, Scope, Send
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
|
||||
|
||||
class FastAPI(Starlette):
|
||||
@@ -38,32 +40,48 @@ class FastAPI(Starlette):
|
||||
openapi_url: Optional[str] = "/openapi.json",
|
||||
openapi_tags: Optional[List[Dict[str, Any]]] = None,
|
||||
servers: Optional[List[Dict[str, Union[str, Any]]]] = None,
|
||||
default_response_class: Type[Response] = JSONResponse,
|
||||
dependencies: Optional[Sequence[Depends]] = None,
|
||||
default_response_class: Type[Response] = Default(JSONResponse),
|
||||
docs_url: Optional[str] = "/docs",
|
||||
redoc_url: Optional[str] = "/redoc",
|
||||
swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect",
|
||||
swagger_ui_init_oauth: Optional[dict] = None,
|
||||
swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,
|
||||
middleware: Optional[Sequence[Middleware]] = None,
|
||||
exception_handlers: Optional[
|
||||
Dict[Union[int, Type[Exception]], Callable]
|
||||
Dict[
|
||||
Union[int, Type[Exception]],
|
||||
Callable[[Request, Any], Coroutine[Any, Any, Response]],
|
||||
]
|
||||
] = None,
|
||||
on_startup: Optional[Sequence[Callable]] = None,
|
||||
on_shutdown: Optional[Sequence[Callable]] = None,
|
||||
on_startup: Optional[Sequence[Callable[[], Any]]] = None,
|
||||
on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,
|
||||
openapi_prefix: str = "",
|
||||
root_path: str = "",
|
||||
root_path_in_servers: bool = True,
|
||||
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
deprecated: Optional[bool] = None,
|
||||
include_in_schema: bool = True,
|
||||
**extra: Any,
|
||||
) -> None:
|
||||
self.default_response_class = default_response_class
|
||||
self._debug = debug
|
||||
self.state = State()
|
||||
self._debug: bool = debug
|
||||
self.state: State = State()
|
||||
self.router: routing.APIRouter = routing.APIRouter(
|
||||
routes,
|
||||
routes=routes,
|
||||
dependency_overrides_provider=self,
|
||||
on_startup=on_startup,
|
||||
on_shutdown=on_shutdown,
|
||||
default_response_class=default_response_class,
|
||||
dependencies=dependencies,
|
||||
callbacks=callbacks,
|
||||
deprecated=deprecated,
|
||||
include_in_schema=include_in_schema,
|
||||
responses=responses,
|
||||
)
|
||||
self.exception_handlers = (
|
||||
self.exception_handlers: Dict[
|
||||
Union[int, Type[Exception]],
|
||||
Callable[[Request, Any], Coroutine[Any, Any, Response]],
|
||||
] = (
|
||||
{} if exception_handlers is None else dict(exception_handlers)
|
||||
)
|
||||
self.exception_handlers.setdefault(HTTPException, http_exception_handler)
|
||||
@@ -71,8 +89,10 @@ class FastAPI(Starlette):
|
||||
RequestValidationError, request_validation_exception_handler
|
||||
)
|
||||
|
||||
self.user_middleware = [] if middleware is None else list(middleware)
|
||||
self.middleware_stack = self.build_middleware_stack()
|
||||
self.user_middleware: List[Middleware] = (
|
||||
[] if middleware is None else list(middleware)
|
||||
)
|
||||
self.middleware_stack: ASGIApp = self.build_middleware_stack()
|
||||
|
||||
self.title = title
|
||||
self.description = description
|
||||
@@ -95,7 +115,7 @@ class FastAPI(Starlette):
|
||||
self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url
|
||||
self.swagger_ui_init_oauth = swagger_ui_init_oauth
|
||||
self.extra = extra
|
||||
self.dependency_overrides: Dict[Callable, Callable] = {}
|
||||
self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {}
|
||||
|
||||
self.openapi_version = "3.0.2"
|
||||
|
||||
@@ -105,7 +125,7 @@ class FastAPI(Starlette):
|
||||
self.openapi_schema: Optional[Dict[str, Any]] = None
|
||||
self.setup()
|
||||
|
||||
def openapi(self) -> Dict:
|
||||
def openapi(self) -> Dict[str, Any]:
|
||||
if not self.openapi_schema:
|
||||
self.openapi_schema = get_openapi(
|
||||
title=self.title,
|
||||
@@ -183,7 +203,7 @@ class FastAPI(Starlette):
|
||||
def add_api_route(
|
||||
self,
|
||||
path: str,
|
||||
endpoint: Callable,
|
||||
endpoint: Callable[..., Coroutine[Any, Any, Response]],
|
||||
*,
|
||||
response_model: Optional[Type[Any]] = None,
|
||||
status_code: int = 200,
|
||||
@@ -203,7 +223,9 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults: bool = False,
|
||||
response_model_exclude_none: bool = False,
|
||||
include_in_schema: bool = True,
|
||||
response_class: Optional[Type[Response]] = None,
|
||||
response_class: Union[Type[Response], DefaultPlaceholder] = Default(
|
||||
JSONResponse
|
||||
),
|
||||
name: Optional[str] = None,
|
||||
) -> None:
|
||||
self.router.add_api_route(
|
||||
@@ -211,12 +233,12 @@ class FastAPI(Starlette):
|
||||
endpoint=endpoint,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=tags or [],
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
summary=summary,
|
||||
description=description,
|
||||
response_description=response_description,
|
||||
responses=responses or {},
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
methods=methods,
|
||||
operation_id=operation_id,
|
||||
@@ -227,7 +249,7 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults=response_model_exclude_defaults,
|
||||
response_model_exclude_none=response_model_exclude_none,
|
||||
include_in_schema=include_in_schema,
|
||||
response_class=response_class or self.default_response_class,
|
||||
response_class=response_class,
|
||||
name=name,
|
||||
)
|
||||
|
||||
@@ -253,21 +275,21 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults: bool = False,
|
||||
response_model_exclude_none: bool = False,
|
||||
include_in_schema: bool = True,
|
||||
response_class: Optional[Type[Response]] = None,
|
||||
response_class: Type[Response] = Default(JSONResponse),
|
||||
name: Optional[str] = None,
|
||||
) -> Callable:
|
||||
def decorator(func: Callable) -> Callable:
|
||||
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
||||
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
||||
self.router.add_api_route(
|
||||
path,
|
||||
func,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=tags or [],
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
summary=summary,
|
||||
description=description,
|
||||
response_description=response_description,
|
||||
responses=responses or {},
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
methods=methods,
|
||||
operation_id=operation_id,
|
||||
@@ -278,7 +300,7 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults=response_model_exclude_defaults,
|
||||
response_model_exclude_none=response_model_exclude_none,
|
||||
include_in_schema=include_in_schema,
|
||||
response_class=response_class or self.default_response_class,
|
||||
response_class=response_class,
|
||||
name=name,
|
||||
)
|
||||
return func
|
||||
@@ -286,12 +308,14 @@ class FastAPI(Starlette):
|
||||
return decorator
|
||||
|
||||
def add_api_websocket_route(
|
||||
self, path: str, endpoint: Callable, name: Optional[str] = None
|
||||
self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None
|
||||
) -> None:
|
||||
self.router.add_api_websocket_route(path, endpoint, name=name)
|
||||
|
||||
def websocket(self, path: str, name: Optional[str] = None) -> Callable:
|
||||
def decorator(func: Callable) -> Callable:
|
||||
def websocket(
|
||||
self, path: str, name: Optional[str] = None
|
||||
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
||||
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
||||
self.add_api_websocket_route(path, func, name=name)
|
||||
return func
|
||||
|
||||
@@ -305,16 +329,21 @@ class FastAPI(Starlette):
|
||||
tags: Optional[List[str]] = None,
|
||||
dependencies: Optional[Sequence[Depends]] = None,
|
||||
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
||||
default_response_class: Optional[Type[Response]] = None,
|
||||
deprecated: Optional[bool] = None,
|
||||
include_in_schema: bool = True,
|
||||
default_response_class: Type[Response] = Default(JSONResponse),
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
) -> None:
|
||||
self.router.include_router(
|
||||
router,
|
||||
prefix=prefix,
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
responses=responses or {},
|
||||
default_response_class=default_response_class
|
||||
or self.default_response_class,
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
include_in_schema=include_in_schema,
|
||||
default_response_class=default_response_class,
|
||||
callbacks=callbacks,
|
||||
)
|
||||
|
||||
def get(
|
||||
@@ -338,20 +367,20 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults: bool = False,
|
||||
response_model_exclude_none: bool = False,
|
||||
include_in_schema: bool = True,
|
||||
response_class: Optional[Type[Response]] = None,
|
||||
response_class: Type[Response] = Default(JSONResponse),
|
||||
name: Optional[str] = None,
|
||||
callbacks: Optional[List[routing.APIRoute]] = None,
|
||||
) -> Callable:
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
||||
return self.router.get(
|
||||
path,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=tags or [],
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
summary=summary,
|
||||
description=description,
|
||||
response_description=response_description,
|
||||
responses=responses or {},
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
operation_id=operation_id,
|
||||
response_model_include=response_model_include,
|
||||
@@ -361,7 +390,7 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults=response_model_exclude_defaults,
|
||||
response_model_exclude_none=response_model_exclude_none,
|
||||
include_in_schema=include_in_schema,
|
||||
response_class=response_class or self.default_response_class,
|
||||
response_class=response_class,
|
||||
name=name,
|
||||
callbacks=callbacks,
|
||||
)
|
||||
@@ -387,20 +416,20 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults: bool = False,
|
||||
response_model_exclude_none: bool = False,
|
||||
include_in_schema: bool = True,
|
||||
response_class: Optional[Type[Response]] = None,
|
||||
response_class: Type[Response] = Default(JSONResponse),
|
||||
name: Optional[str] = None,
|
||||
callbacks: Optional[List[routing.APIRoute]] = None,
|
||||
) -> Callable:
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
||||
return self.router.put(
|
||||
path,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=tags or [],
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
summary=summary,
|
||||
description=description,
|
||||
response_description=response_description,
|
||||
responses=responses or {},
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
operation_id=operation_id,
|
||||
response_model_include=response_model_include,
|
||||
@@ -410,7 +439,7 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults=response_model_exclude_defaults,
|
||||
response_model_exclude_none=response_model_exclude_none,
|
||||
include_in_schema=include_in_schema,
|
||||
response_class=response_class or self.default_response_class,
|
||||
response_class=response_class,
|
||||
name=name,
|
||||
callbacks=callbacks,
|
||||
)
|
||||
@@ -436,20 +465,20 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults: bool = False,
|
||||
response_model_exclude_none: bool = False,
|
||||
include_in_schema: bool = True,
|
||||
response_class: Optional[Type[Response]] = None,
|
||||
response_class: Type[Response] = Default(JSONResponse),
|
||||
name: Optional[str] = None,
|
||||
callbacks: Optional[List[routing.APIRoute]] = None,
|
||||
) -> Callable:
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
||||
return self.router.post(
|
||||
path,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=tags or [],
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
summary=summary,
|
||||
description=description,
|
||||
response_description=response_description,
|
||||
responses=responses or {},
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
operation_id=operation_id,
|
||||
response_model_include=response_model_include,
|
||||
@@ -459,7 +488,7 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults=response_model_exclude_defaults,
|
||||
response_model_exclude_none=response_model_exclude_none,
|
||||
include_in_schema=include_in_schema,
|
||||
response_class=response_class or self.default_response_class,
|
||||
response_class=response_class,
|
||||
name=name,
|
||||
callbacks=callbacks,
|
||||
)
|
||||
@@ -485,20 +514,20 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults: bool = False,
|
||||
response_model_exclude_none: bool = False,
|
||||
include_in_schema: bool = True,
|
||||
response_class: Optional[Type[Response]] = None,
|
||||
response_class: Type[Response] = Default(JSONResponse),
|
||||
name: Optional[str] = None,
|
||||
callbacks: Optional[List[routing.APIRoute]] = None,
|
||||
) -> Callable:
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
||||
return self.router.delete(
|
||||
path,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=tags or [],
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
summary=summary,
|
||||
description=description,
|
||||
response_description=response_description,
|
||||
responses=responses or {},
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
response_model_include=response_model_include,
|
||||
response_model_exclude=response_model_exclude,
|
||||
@@ -508,7 +537,7 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults=response_model_exclude_defaults,
|
||||
response_model_exclude_none=response_model_exclude_none,
|
||||
include_in_schema=include_in_schema,
|
||||
response_class=response_class or self.default_response_class,
|
||||
response_class=response_class,
|
||||
name=name,
|
||||
callbacks=callbacks,
|
||||
)
|
||||
@@ -534,20 +563,20 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults: bool = False,
|
||||
response_model_exclude_none: bool = False,
|
||||
include_in_schema: bool = True,
|
||||
response_class: Optional[Type[Response]] = None,
|
||||
response_class: Type[Response] = Default(JSONResponse),
|
||||
name: Optional[str] = None,
|
||||
callbacks: Optional[List[routing.APIRoute]] = None,
|
||||
) -> Callable:
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
||||
return self.router.options(
|
||||
path,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=tags or [],
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
summary=summary,
|
||||
description=description,
|
||||
response_description=response_description,
|
||||
responses=responses or {},
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
operation_id=operation_id,
|
||||
response_model_include=response_model_include,
|
||||
@@ -557,7 +586,7 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults=response_model_exclude_defaults,
|
||||
response_model_exclude_none=response_model_exclude_none,
|
||||
include_in_schema=include_in_schema,
|
||||
response_class=response_class or self.default_response_class,
|
||||
response_class=response_class,
|
||||
name=name,
|
||||
callbacks=callbacks,
|
||||
)
|
||||
@@ -583,20 +612,20 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults: bool = False,
|
||||
response_model_exclude_none: bool = False,
|
||||
include_in_schema: bool = True,
|
||||
response_class: Optional[Type[Response]] = None,
|
||||
response_class: Type[Response] = Default(JSONResponse),
|
||||
name: Optional[str] = None,
|
||||
callbacks: Optional[List[routing.APIRoute]] = None,
|
||||
) -> Callable:
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
||||
return self.router.head(
|
||||
path,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=tags or [],
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
summary=summary,
|
||||
description=description,
|
||||
response_description=response_description,
|
||||
responses=responses or {},
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
operation_id=operation_id,
|
||||
response_model_include=response_model_include,
|
||||
@@ -606,7 +635,7 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults=response_model_exclude_defaults,
|
||||
response_model_exclude_none=response_model_exclude_none,
|
||||
include_in_schema=include_in_schema,
|
||||
response_class=response_class or self.default_response_class,
|
||||
response_class=response_class,
|
||||
name=name,
|
||||
callbacks=callbacks,
|
||||
)
|
||||
@@ -632,20 +661,20 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults: bool = False,
|
||||
response_model_exclude_none: bool = False,
|
||||
include_in_schema: bool = True,
|
||||
response_class: Optional[Type[Response]] = None,
|
||||
response_class: Type[Response] = Default(JSONResponse),
|
||||
name: Optional[str] = None,
|
||||
callbacks: Optional[List[routing.APIRoute]] = None,
|
||||
) -> Callable:
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
||||
return self.router.patch(
|
||||
path,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=tags or [],
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
summary=summary,
|
||||
description=description,
|
||||
response_description=response_description,
|
||||
responses=responses or {},
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
operation_id=operation_id,
|
||||
response_model_include=response_model_include,
|
||||
@@ -655,7 +684,7 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults=response_model_exclude_defaults,
|
||||
response_model_exclude_none=response_model_exclude_none,
|
||||
include_in_schema=include_in_schema,
|
||||
response_class=response_class or self.default_response_class,
|
||||
response_class=response_class,
|
||||
name=name,
|
||||
callbacks=callbacks,
|
||||
)
|
||||
@@ -681,20 +710,20 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults: bool = False,
|
||||
response_model_exclude_none: bool = False,
|
||||
include_in_schema: bool = True,
|
||||
response_class: Optional[Type[Response]] = None,
|
||||
response_class: Type[Response] = Default(JSONResponse),
|
||||
name: Optional[str] = None,
|
||||
callbacks: Optional[List[routing.APIRoute]] = None,
|
||||
) -> Callable:
|
||||
callbacks: Optional[List[BaseRoute]] = None,
|
||||
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
||||
return self.router.trace(
|
||||
path,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=tags or [],
|
||||
tags=tags,
|
||||
dependencies=dependencies,
|
||||
summary=summary,
|
||||
description=description,
|
||||
response_description=response_description,
|
||||
responses=responses or {},
|
||||
responses=responses,
|
||||
deprecated=deprecated,
|
||||
operation_id=operation_id,
|
||||
response_model_include=response_model_include,
|
||||
@@ -704,7 +733,7 @@ class FastAPI(Starlette):
|
||||
response_model_exclude_defaults=response_model_exclude_defaults,
|
||||
response_model_exclude_none=response_model_exclude_none,
|
||||
include_in_schema=include_in_schema,
|
||||
response_class=response_class or self.default_response_class,
|
||||
response_class=response_class,
|
||||
name=name,
|
||||
callbacks=callbacks,
|
||||
)
|
||||
|
||||
@@ -1 +1 @@
|
||||
from starlette.background import BackgroundTasks # noqa
|
||||
from starlette.background import BackgroundTasks as BackgroundTasks # noqa
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
from typing import Any, Callable
|
||||
|
||||
from starlette.concurrency import iterate_in_threadpool # noqa
|
||||
from starlette.concurrency import run_in_threadpool # noqa
|
||||
from starlette.concurrency import run_until_first_complete # noqa
|
||||
from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa
|
||||
from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa
|
||||
from starlette.concurrency import ( # noqa
|
||||
run_until_first_complete as run_until_first_complete,
|
||||
)
|
||||
|
||||
asynccontextmanager_error_message = """
|
||||
FastAPI's contextmanager_in_threadpool require Python 3.7 or above,
|
||||
@@ -11,7 +13,7 @@ or the backport for Python 3.6, installed with:
|
||||
"""
|
||||
|
||||
|
||||
def _fake_asynccontextmanager(func: Callable) -> Callable:
|
||||
def _fake_asynccontextmanager(func: Callable[..., Any]) -> Callable[..., Any]:
|
||||
def raiser(*args: Any, **kwargs: Any) -> Any:
|
||||
raise RuntimeError(asynccontextmanager_error_message)
|
||||
|
||||
@@ -19,23 +21,25 @@ def _fake_asynccontextmanager(func: Callable) -> Callable:
|
||||
|
||||
|
||||
try:
|
||||
from contextlib import asynccontextmanager # type: ignore
|
||||
from contextlib import asynccontextmanager as asynccontextmanager # type: ignore
|
||||
except ImportError:
|
||||
try:
|
||||
from async_generator import asynccontextmanager # type: ignore
|
||||
from async_generator import ( # type: ignore # isort: skip
|
||||
asynccontextmanager as asynccontextmanager,
|
||||
)
|
||||
except ImportError: # pragma: no cover
|
||||
asynccontextmanager = _fake_asynccontextmanager
|
||||
|
||||
try:
|
||||
from contextlib import AsyncExitStack # type: ignore
|
||||
from contextlib import AsyncExitStack as AsyncExitStack # type: ignore
|
||||
except ImportError:
|
||||
try:
|
||||
from async_exit_stack import AsyncExitStack # type: ignore
|
||||
from async_exit_stack import AsyncExitStack as AsyncExitStack # type: ignore
|
||||
except ImportError: # pragma: no cover
|
||||
AsyncExitStack = None # type: ignore
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@asynccontextmanager # type: ignore
|
||||
async def contextmanager_in_threadpool(cm: Any) -> Any:
|
||||
try:
|
||||
yield await run_in_threadpool(cm.__enter__)
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
from typing import Any, Callable, Iterable, Type
|
||||
from typing import Any, Callable, Iterable, Type, TypeVar
|
||||
|
||||
from starlette.datastructures import State as State # noqa: F401
|
||||
from starlette.datastructures import UploadFile as StarletteUploadFile
|
||||
|
||||
|
||||
class UploadFile(StarletteUploadFile):
|
||||
@classmethod
|
||||
def __get_validators__(cls: Type["UploadFile"]) -> Iterable[Callable]:
|
||||
def __get_validators__(cls: Type["UploadFile"]) -> Iterable[Callable[..., Any]]:
|
||||
yield cls.validate
|
||||
|
||||
@classmethod
|
||||
@@ -13,3 +14,34 @@ class UploadFile(StarletteUploadFile):
|
||||
if not isinstance(v, StarletteUploadFile):
|
||||
raise ValueError(f"Expected UploadFile, received: {type(v)}")
|
||||
return v
|
||||
|
||||
|
||||
class DefaultPlaceholder:
|
||||
"""
|
||||
You shouldn't use this class directly.
|
||||
|
||||
It's used internally to recognize when a default value has been overwritten, even
|
||||
if the overriden default value was truthy.
|
||||
"""
|
||||
|
||||
def __init__(self, value: Any):
|
||||
self.value = value
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
return bool(self.value)
|
||||
|
||||
def __eq__(self, o: object) -> bool:
|
||||
return isinstance(o, DefaultPlaceholder) and o.value == self.value
|
||||
|
||||
|
||||
DefaultType = TypeVar("DefaultType")
|
||||
|
||||
|
||||
def Default(value: DefaultType) -> DefaultType:
|
||||
"""
|
||||
You shouldn't use this function directly.
|
||||
|
||||
It's used internally to recognize when a default value has been overwritten, even
|
||||
if the overriden default value was truthy.
|
||||
"""
|
||||
return DefaultPlaceholder(value) # type: ignore
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Callable, List, Optional, Sequence
|
||||
from typing import Any, Callable, List, Optional, Sequence
|
||||
|
||||
from fastapi.security.base import SecurityBase
|
||||
from pydantic.fields import ModelField
|
||||
@@ -24,7 +24,7 @@ class Dependant:
|
||||
dependencies: Optional[List["Dependant"]] = None,
|
||||
security_schemes: Optional[List[SecurityRequirement]] = None,
|
||||
name: Optional[str] = None,
|
||||
call: Optional[Callable] = None,
|
||||
call: Optional[Callable[..., Any]] = None,
|
||||
request_param_name: Optional[str] = None,
|
||||
websocket_param_name: Optional[str] = None,
|
||||
http_connection_param_name: Optional[str] = None,
|
||||
|
||||
@@ -90,12 +90,12 @@ def check_file_field(field: ModelField) -> None:
|
||||
if isinstance(field_info, params.Form):
|
||||
try:
|
||||
# __version__ is available in both multiparts, and can be mocked
|
||||
from multipart import __version__
|
||||
from multipart import __version__ # type: ignore
|
||||
|
||||
assert __version__
|
||||
try:
|
||||
# parse_options_header is only available in the right multipart
|
||||
from multipart.multipart import parse_options_header
|
||||
from multipart.multipart import parse_options_header # type: ignore
|
||||
|
||||
assert parse_options_header
|
||||
except ImportError:
|
||||
@@ -133,7 +133,7 @@ def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> De
|
||||
def get_sub_dependant(
|
||||
*,
|
||||
depends: params.Depends,
|
||||
dependency: Callable,
|
||||
dependency: Callable[..., Any],
|
||||
path: str,
|
||||
name: Optional[str] = None,
|
||||
security_scopes: Optional[List[str]] = None,
|
||||
@@ -163,7 +163,7 @@ def get_sub_dependant(
|
||||
return sub_dependant
|
||||
|
||||
|
||||
CacheKey = Tuple[Optional[Callable], Tuple[str, ...]]
|
||||
CacheKey = Tuple[Optional[Callable[..., Any]], Tuple[str, ...]]
|
||||
|
||||
|
||||
def get_flat_dependant(
|
||||
@@ -240,7 +240,7 @@ def is_scalar_sequence_field(field: ModelField) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def get_typed_signature(call: Callable) -> inspect.Signature:
|
||||
def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature:
|
||||
signature = inspect.signature(call)
|
||||
globalns = getattr(call, "__globals__", {})
|
||||
typed_params = [
|
||||
@@ -259,9 +259,7 @@ def get_typed_signature(call: Callable) -> inspect.Signature:
|
||||
def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any:
|
||||
annotation = param.annotation
|
||||
if isinstance(annotation, str):
|
||||
# Temporary ignore type
|
||||
# Ref: https://github.com/samuelcolvin/pydantic/issues/1738
|
||||
annotation = ForwardRef(annotation) # type: ignore
|
||||
annotation = ForwardRef(annotation)
|
||||
annotation = evaluate_forwardref(annotation, globalns, globalns)
|
||||
return annotation
|
||||
|
||||
@@ -281,7 +279,7 @@ def check_dependency_contextmanagers() -> None:
|
||||
def get_dependant(
|
||||
*,
|
||||
path: str,
|
||||
call: Callable,
|
||||
call: Callable[..., Any],
|
||||
name: Optional[str] = None,
|
||||
security_scopes: Optional[List[str]] = None,
|
||||
use_cache: bool = True,
|
||||
@@ -423,7 +421,7 @@ def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None:
|
||||
dependant.cookie_params.append(field)
|
||||
|
||||
|
||||
def is_coroutine_callable(call: Callable) -> bool:
|
||||
def is_coroutine_callable(call: Callable[..., Any]) -> bool:
|
||||
if inspect.isroutine(call):
|
||||
return inspect.iscoroutinefunction(call)
|
||||
if inspect.isclass(call):
|
||||
@@ -432,14 +430,14 @@ def is_coroutine_callable(call: Callable) -> bool:
|
||||
return inspect.iscoroutinefunction(call)
|
||||
|
||||
|
||||
def is_async_gen_callable(call: Callable) -> bool:
|
||||
def is_async_gen_callable(call: Callable[..., Any]) -> bool:
|
||||
if inspect.isasyncgenfunction(call):
|
||||
return True
|
||||
call = getattr(call, "__call__", None)
|
||||
return inspect.isasyncgenfunction(call)
|
||||
|
||||
|
||||
def is_gen_callable(call: Callable) -> bool:
|
||||
def is_gen_callable(call: Callable[..., Any]) -> bool:
|
||||
if inspect.isgeneratorfunction(call):
|
||||
return True
|
||||
call = getattr(call, "__call__", None)
|
||||
@@ -447,7 +445,7 @@ def is_gen_callable(call: Callable) -> bool:
|
||||
|
||||
|
||||
async def solve_generator(
|
||||
*, call: Callable, stack: AsyncExitStack, sub_values: Dict[str, Any]
|
||||
*, call: Callable[..., Any], stack: AsyncExitStack, sub_values: Dict[str, Any]
|
||||
) -> Any:
|
||||
if is_gen_callable(call):
|
||||
cm = contextmanager_in_threadpool(contextmanager(call)(**sub_values))
|
||||
@@ -472,29 +470,29 @@ async def solve_dependencies(
|
||||
background_tasks: Optional[BackgroundTasks] = None,
|
||||
response: Optional[Response] = None,
|
||||
dependency_overrides_provider: Optional[Any] = None,
|
||||
dependency_cache: Optional[Dict[Tuple[Callable, Tuple[str]], Any]] = None,
|
||||
dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None,
|
||||
) -> Tuple[
|
||||
Dict[str, Any],
|
||||
List[ErrorWrapper],
|
||||
Optional[BackgroundTasks],
|
||||
Response,
|
||||
Dict[Tuple[Callable, Tuple[str]], Any],
|
||||
Dict[Tuple[Callable[..., Any], Tuple[str]], Any],
|
||||
]:
|
||||
values: Dict[str, Any] = {}
|
||||
errors: List[ErrorWrapper] = []
|
||||
response = response or Response(
|
||||
content=None,
|
||||
status_code=None, # type: ignore
|
||||
headers=None,
|
||||
media_type=None,
|
||||
background=None,
|
||||
headers=None, # type: ignore # in Starlette
|
||||
media_type=None, # type: ignore # in Starlette
|
||||
background=None, # type: ignore # in Starlette
|
||||
)
|
||||
dependency_cache = dependency_cache or {}
|
||||
sub_dependant: Dependant
|
||||
for sub_dependant in dependant.dependencies:
|
||||
sub_dependant.call = cast(Callable, sub_dependant.call)
|
||||
sub_dependant.call = cast(Callable[..., Any], sub_dependant.call)
|
||||
sub_dependant.cache_key = cast(
|
||||
Tuple[Callable, Tuple[str]], sub_dependant.cache_key
|
||||
Tuple[Callable[..., Any], Tuple[str]], sub_dependant.cache_key
|
||||
)
|
||||
call = sub_dependant.call
|
||||
use_sub_dependant = sub_dependant
|
||||
|
||||
@@ -12,9 +12,11 @@ DictIntStrAny = Dict[Union[int, str], Any]
|
||||
|
||||
|
||||
def generate_encoders_by_class_tuples(
|
||||
type_encoder_map: Dict[Any, Callable]
|
||||
) -> Dict[Callable, Tuple]:
|
||||
encoders_by_class_tuples: Dict[Callable, Tuple] = defaultdict(tuple)
|
||||
type_encoder_map: Dict[Any, Callable[[Any], Any]]
|
||||
) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:
|
||||
encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(
|
||||
tuple
|
||||
)
|
||||
for type_, encoder in type_encoder_map.items():
|
||||
encoders_by_class_tuples[encoder] += (type_,)
|
||||
return encoders_by_class_tuples
|
||||
@@ -31,7 +33,7 @@ def jsonable_encoder(
|
||||
exclude_unset: bool = False,
|
||||
exclude_defaults: bool = False,
|
||||
exclude_none: bool = False,
|
||||
custom_encoder: dict = {},
|
||||
custom_encoder: Dict[Any, Callable[[Any], Any]] = {},
|
||||
sqlalchemy_safe: bool = True,
|
||||
) -> Any:
|
||||
if include is not None and not isinstance(include, set):
|
||||
@@ -43,8 +45,8 @@ def jsonable_encoder(
|
||||
if custom_encoder:
|
||||
encoder.update(custom_encoder)
|
||||
obj_dict = obj.dict(
|
||||
include=include,
|
||||
exclude=exclude,
|
||||
include=include, # type: ignore # in Pydantic
|
||||
exclude=exclude, # type: ignore # in Pydantic
|
||||
by_alias=by_alias,
|
||||
exclude_unset=exclude_unset,
|
||||
exclude_none=exclude_none,
|
||||
|
||||
@@ -1 +1 @@
|
||||
from starlette.middleware import Middleware
|
||||
from starlette.middleware import Middleware as Middleware
|
||||
|
||||
@@ -1 +1 @@
|
||||
from starlette.middleware.cors import CORSMiddleware # noqa
|
||||
from starlette.middleware.cors import CORSMiddleware as CORSMiddleware # noqa
|
||||
|
||||
@@ -1 +1 @@
|
||||
from starlette.middleware.gzip import GZipMiddleware # noqa
|
||||
from starlette.middleware.gzip import GZipMiddleware as GZipMiddleware # noqa
|
||||
|
||||
@@ -1 +1,3 @@
|
||||
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware # noqa
|
||||
from starlette.middleware.httpsredirect import ( # noqa
|
||||
HTTPSRedirectMiddleware as HTTPSRedirectMiddleware,
|
||||
)
|
||||
|
||||