mirror of
https://github.com/fastapi/fastapi.git
synced 2025-12-30 09:39:20 -05:00
Compare commits
205 Commits
0.109.0
...
Kludex-pat
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28bd5ca47e | ||
|
|
92feb73531 | ||
|
|
d693d0a980 | ||
|
|
1b01cbe092 | ||
|
|
5d74e58e95 | ||
|
|
06bdf03bce | ||
|
|
01c56c059e | ||
|
|
3e98fb9c83 | ||
|
|
ecee093e34 | ||
|
|
28e679d6dc | ||
|
|
e55c7ccbcb | ||
|
|
9af7f2a5d5 | ||
|
|
9ee70f82e7 | ||
|
|
e96e74ad36 | ||
|
|
8e9af7932c | ||
|
|
4c077492ae | ||
|
|
dcf8b24ece | ||
|
|
6aa521aa03 | ||
|
|
aae29cac5c | ||
|
|
9a5181abfc | ||
|
|
30f31540fc | ||
|
|
30f1a1c4ef | ||
|
|
a12c5db74c | ||
|
|
2341f72101 | ||
|
|
754ea10fcc | ||
|
|
39cff8d7d6 | ||
|
|
7586688cc9 | ||
|
|
9e06513033 | ||
|
|
189f679f9b | ||
|
|
6d46b60cb3 | ||
|
|
f021ccb905 | ||
|
|
aa3ed353b3 | ||
|
|
3351674918 | ||
|
|
058044fdb1 | ||
|
|
0ec0df5090 | ||
|
|
a56d32c3a4 | ||
|
|
9060c427a6 | ||
|
|
0fb326fc6e | ||
|
|
cc9c448ed4 | ||
|
|
ccdc962936 | ||
|
|
ac5e73b19d | ||
|
|
672b501b98 | ||
|
|
95d5902af1 | ||
|
|
315d8184e7 | ||
|
|
5132976253 | ||
|
|
280f49ea83 | ||
|
|
7c9cb476a4 | ||
|
|
13b908df68 | ||
|
|
5ca3d17587 | ||
|
|
74cf1c9702 | ||
|
|
43a7ff782b | ||
|
|
2c1dd4a92b | ||
|
|
149fa96dc7 | ||
|
|
c3914a19a7 | ||
|
|
690edc0385 | ||
|
|
cedea4d7b5 | ||
|
|
2f6fdf62b9 | ||
|
|
d2d5a5290c | ||
|
|
9a33950344 | ||
|
|
d7c588d693 | ||
|
|
c945d686bb | ||
|
|
851daec754 | ||
|
|
f772868a56 | ||
|
|
7514aab30b | ||
|
|
1ac6b761e1 | ||
|
|
29c8b19af8 | ||
|
|
63ffd735d1 | ||
|
|
0a105dc285 | ||
|
|
f8e77fb64c | ||
|
|
22c34a3956 | ||
|
|
6c3d8eb2d9 | ||
|
|
6f42234301 | ||
|
|
79ab317cbd | ||
|
|
3f95f6fe41 | ||
|
|
167d2524b4 | ||
|
|
d532602eed | ||
|
|
77fe266a69 | ||
|
|
66ef70a2ba | ||
|
|
792ba01745 | ||
|
|
ea6e0ffdc0 | ||
|
|
8ec9e30010 | ||
|
|
ef1ccb563d | ||
|
|
adf61e5675 | ||
|
|
83944b9e26 | ||
|
|
87a4c9ef01 | ||
|
|
eea7635713 | ||
|
|
2a8f8d1ac0 | ||
|
|
5fb87313e2 | ||
|
|
01d774d38c | ||
|
|
896f171aa2 | ||
|
|
2fe1a1387b | ||
|
|
60ea8f85a1 | ||
|
|
62e6c888b7 | ||
|
|
510c7a56a4 | ||
|
|
c3019096e7 | ||
|
|
d74b3b2565 | ||
|
|
df09e0a3f6 | ||
|
|
fc8ea413eb | ||
|
|
950d9ce74d | ||
|
|
d761a29908 | ||
|
|
d1e533e370 | ||
|
|
ae92e563b1 | ||
|
|
75ea31c79e | ||
|
|
2ce4c102fb | ||
|
|
8450dc204d | ||
|
|
2c670325af | ||
|
|
e500f99403 | ||
|
|
7b462b2e69 | ||
|
|
b518241c59 | ||
|
|
082eb21ba0 | ||
|
|
c68836ae46 | ||
|
|
6f3a134f6d | ||
|
|
94404fc1a0 | ||
|
|
289fbc83ba | ||
|
|
8ad62bd837 | ||
|
|
39bb4bbdfc | ||
|
|
5c71522974 | ||
|
|
bf9489c0ad | ||
|
|
997281bf83 | ||
|
|
1cf1ee42fe | ||
|
|
a14907a47d | ||
|
|
eed57df6f6 | ||
|
|
b73de83ca2 | ||
|
|
b21599bab0 | ||
|
|
efac3a293f | ||
|
|
217bff20ca | ||
|
|
88225ae231 | ||
|
|
17511f7768 | ||
|
|
f386011d64 | ||
|
|
c238292b44 | ||
|
|
79dbb11867 | ||
|
|
2619bbd7cd | ||
|
|
88f19be7c3 | ||
|
|
467ab2a575 | ||
|
|
15429a9c39 | ||
|
|
32ae949723 | ||
|
|
cf01195555 | ||
|
|
2b6f12a5d0 | ||
|
|
63e5396a78 | ||
|
|
69dc735fc2 | ||
|
|
dcc952d699 | ||
|
|
e90fc7bed4 | ||
|
|
f18eadb7de | ||
|
|
61a08d0c60 | ||
|
|
de0126d145 | ||
|
|
cca6203c18 | ||
|
|
83e386519d | ||
|
|
b24c4870d8 | ||
|
|
bc13faa15d | ||
|
|
5377c594da | ||
|
|
a37ac3819e | ||
|
|
4299e712fb | ||
|
|
c3e2aa9dc2 | ||
|
|
cc5711e6f1 | ||
|
|
1caee0f105 | ||
|
|
1ce27fd743 | ||
|
|
fad1a464e7 | ||
|
|
26e57903d1 | ||
|
|
b0cd4f915b | ||
|
|
bc7d026b6c | ||
|
|
c9e46ae12c | ||
|
|
a293709998 | ||
|
|
25646a5070 | ||
|
|
0ce4f80ac9 | ||
|
|
91666b3556 | ||
|
|
22e5d9e27f | ||
|
|
be0bd34446 | ||
|
|
44f3ebce6e | ||
|
|
0aee526de9 | ||
|
|
4f9ad80f5d | ||
|
|
c81ab17a59 | ||
|
|
ca33b6edac | ||
|
|
58e2f8b1d9 | ||
|
|
38915783fc | ||
|
|
7e0e16fa36 | ||
|
|
dc704036a2 | ||
|
|
f1329abf99 | ||
|
|
753c8136d8 | ||
|
|
6a4aed45f0 | ||
|
|
4c231854dc | ||
|
|
3ca38568c1 | ||
|
|
e0eaaee749 | ||
|
|
ea84587a2f | ||
|
|
5f37d3870b | ||
|
|
0c796747a3 | ||
|
|
22e68b151d | ||
|
|
fd97e8efe4 | ||
|
|
53a3dd7408 | ||
|
|
d192ddacec | ||
|
|
cbcd3fe863 | ||
|
|
b62e379a55 | ||
|
|
99769b9669 | ||
|
|
f74aeb0067 | ||
|
|
4dde172a96 | ||
|
|
e6759aa604 | ||
|
|
0be64abac7 | ||
|
|
0380ca3e69 | ||
|
|
3325635eed | ||
|
|
abe7db6b24 | ||
|
|
6761fc1fa4 | ||
|
|
838e9c964e | ||
|
|
facdc91629 | ||
|
|
1369c45c2e | ||
|
|
fedee4d028 | ||
|
|
6bda1326a4 |
6
.github/dependabot.yml
vendored
6
.github/dependabot.yml
vendored
@@ -11,6 +11,10 @@ updates:
|
||||
- package-ecosystem: "pip"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
interval: "monthly"
|
||||
groups:
|
||||
python-packages:
|
||||
patterns:
|
||||
- "*"
|
||||
commit-message:
|
||||
prefix: ⬆
|
||||
|
||||
8
.github/workflows/build-docs.yml
vendored
8
.github/workflows/build-docs.yml
vendored
@@ -39,7 +39,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.11"
|
||||
- uses: actions/cache@v3
|
||||
@@ -57,8 +57,8 @@ jobs:
|
||||
pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git
|
||||
pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git
|
||||
pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git
|
||||
- name: Verify README
|
||||
run: python ./scripts/docs.py verify-readme
|
||||
- name: Verify Docs
|
||||
run: python ./scripts/docs.py verify-docs
|
||||
- name: Export Language Codes
|
||||
id: show-langs
|
||||
run: |
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.11"
|
||||
- uses: actions/cache@v3
|
||||
|
||||
2
.github/workflows/deploy-docs.yml
vendored
2
.github/workflows/deploy-docs.yml
vendored
@@ -21,7 +21,7 @@ jobs:
|
||||
mkdir ./site
|
||||
- name: Download Artifact Docs
|
||||
id: download
|
||||
uses: dawidd6/action-download-artifact@v2.28.0
|
||||
uses: dawidd6/action-download-artifact@v3.0.0
|
||||
with:
|
||||
if_no_artifact_found: ignore
|
||||
github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }}
|
||||
|
||||
4
.github/workflows/issue-manager.yml
vendored
4
.github/workflows/issue-manager.yml
vendored
@@ -31,5 +31,9 @@ jobs:
|
||||
"answered": {
|
||||
"delay": 864000,
|
||||
"message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs."
|
||||
},
|
||||
"changes-requested": {
|
||||
"delay": 2628000,
|
||||
"message": "As this PR had requested changes to be applied but has been inactive for a while, it's now going to be closed. But if there's anyone interested, feel free to create a new PR."
|
||||
}
|
||||
}
|
||||
|
||||
8
.github/workflows/label-approved.yml
vendored
8
.github/workflows/label-approved.yml
vendored
@@ -17,3 +17,11 @@ jobs:
|
||||
- uses: docker://tiangolo/label-approved:0.0.4
|
||||
with:
|
||||
token: ${{ secrets.FASTAPI_LABEL_APPROVED }}
|
||||
config: >
|
||||
{
|
||||
"approved-1":
|
||||
{
|
||||
"number": 1,
|
||||
"await_label": "awaiting-review"
|
||||
}
|
||||
}
|
||||
|
||||
4
.github/workflows/publish.yml
vendored
4
.github/workflows/publish.yml
vendored
@@ -15,7 +15,7 @@ jobs:
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.10"
|
||||
# Issue ref: https://github.com/actions/setup-python/issues/436
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
- name: Build distribution
|
||||
run: python -m build
|
||||
- name: Publish
|
||||
uses: pypa/gh-action-pypi-publish@v1.8.10
|
||||
uses: pypa/gh-action-pypi-publish@v1.8.11
|
||||
with:
|
||||
password: ${{ secrets.PYPI_API_TOKEN }}
|
||||
- name: Dump GitHub context
|
||||
|
||||
4
.github/workflows/smokeshow.yml
vendored
4
.github/workflows/smokeshow.yml
vendored
@@ -18,13 +18,13 @@ jobs:
|
||||
env:
|
||||
GITHUB_CONTEXT: ${{ toJson(github) }}
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- uses: actions/setup-python@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.9'
|
||||
|
||||
- run: pip install smokeshow
|
||||
|
||||
- uses: dawidd6/action-download-artifact@v2.28.0
|
||||
- uses: dawidd6/action-download-artifact@v3.0.0
|
||||
with:
|
||||
github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }}
|
||||
workflow: test.yml
|
||||
|
||||
6
.github/workflows/test.yml
vendored
6
.github/workflows/test.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.11"
|
||||
# Issue ref: https://github.com/actions/setup-python/issues/436
|
||||
@@ -57,7 +57,7 @@ jobs:
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
# Issue ref: https://github.com/actions/setup-python/issues/436
|
||||
@@ -98,7 +98,7 @@ jobs:
|
||||
GITHUB_CONTEXT: ${{ toJson(github) }}
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.8'
|
||||
# Issue ref: https://github.com/actions/setup-python/issues/436
|
||||
|
||||
@@ -464,7 +464,6 @@ Used by Starlette:
|
||||
* <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://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Required if you want to use `UJSONResponse`.
|
||||
|
||||
Used by FastAPI / Starlette:
|
||||
|
||||
|
||||
3
docs/de/docs/about/index.md
Normal file
3
docs/de/docs/about/index.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Über
|
||||
|
||||
Über FastAPI, sein Design, seine Inspiration und mehr. 🤓
|
||||
69
docs/de/docs/advanced/additional-status-codes.md
Normal file
69
docs/de/docs/advanced/additional-status-codes.md
Normal file
@@ -0,0 +1,69 @@
|
||||
# Zusätzliche Statuscodes
|
||||
|
||||
Standardmäßig liefert **FastAPI** die Rückgabewerte (Responses) als `JSONResponse` zurück und fügt den Inhalt der jeweiligen *Pfadoperation* in das `JSONResponse` Objekt ein.
|
||||
|
||||
Es wird der Default-Statuscode oder derjenige verwendet, den Sie in Ihrer *Pfadoperation* festgelegt haben.
|
||||
|
||||
## Zusätzliche Statuscodes
|
||||
|
||||
Wenn Sie neben dem Hauptstatuscode weitere Statuscodes zurückgeben möchten, können Sie dies tun, indem Sie direkt eine `Response` zurückgeben, wie etwa eine `JSONResponse`, und den zusätzlichen Statuscode direkt festlegen.
|
||||
|
||||
Angenommen, Sie möchten eine *Pfadoperation* haben, die das Aktualisieren von Artikeln ermöglicht und bei Erfolg den HTTP-Statuscode 200 „OK“ zurückgibt.
|
||||
|
||||
Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente vorher nicht vorhanden waren, werden diese Elemente erstellt und der HTTP-Statuscode 201 „Created“ zurückgegeben.
|
||||
|
||||
Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="4 25"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="4 25"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="4 26"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ nicht annotiert"
|
||||
|
||||
!!! tip "Tipp"
|
||||
Bevorzugen Sie die `Annotated`-Version, falls möglich.
|
||||
|
||||
```Python hl_lines="2 23"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ nicht annotiert"
|
||||
|
||||
!!! tip "Tipp"
|
||||
Bevorzugen Sie die `Annotated`-Version, falls möglich.
|
||||
|
||||
```Python hl_lines="4 25"
|
||||
{!> ../../../docs_src/additional_status_codes/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! warning "Achtung"
|
||||
Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben.
|
||||
|
||||
Sie wird nicht mit einem Modell usw. serialisiert.
|
||||
|
||||
Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden).
|
||||
|
||||
!!! note "Technische Details"
|
||||
Sie können auch `from starlette.responses import JSONResponse` verwenden.
|
||||
|
||||
**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`.
|
||||
|
||||
## OpenAPI- und API-Dokumentation
|
||||
|
||||
Wenn Sie zusätzliche Statuscodes und Responses direkt zurückgeben, werden diese nicht in das OpenAPI-Schema (die API-Dokumentation) aufgenommen, da FastAPI keine Möglichkeit hat, im Voraus zu wissen, was Sie zurückgeben werden.
|
||||
|
||||
Sie können das jedoch in Ihrem Code dokumentieren, indem Sie Folgendes verwenden: [Zusätzliche Responses](additional-responses.md){.internal-link target=_blank}.
|
||||
300
docs/de/docs/advanced/custom-response.md
Normal file
300
docs/de/docs/advanced/custom-response.md
Normal file
@@ -0,0 +1,300 @@
|
||||
# Benutzerdefinierte Response – HTML, Stream, Datei, andere
|
||||
|
||||
Standardmäßig gibt **FastAPI** die Responses mittels `JSONResponse` zurück.
|
||||
|
||||
Sie können das überschreiben, indem Sie direkt eine `Response` zurückgeben, wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} gezeigt.
|
||||
|
||||
Wenn Sie jedoch direkt eine `Response` zurückgeben, werden die Daten nicht automatisch konvertiert und die Dokumentation wird nicht automatisch generiert (zum Beispiel wird der spezifische „Medientyp“, der im HTTP-Header `Content-Type` angegeben ist, nicht Teil der generierten OpenAPI).
|
||||
|
||||
Sie können aber auch die `Response`, die Sie verwenden möchten, im *Pfadoperation-Dekorator* deklarieren.
|
||||
|
||||
Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in diese `Response` eingefügt.
|
||||
|
||||
Und wenn diese `Response` einen JSON-Medientyp (`application/json`) hat, wie es bei `JSONResponse` und `UJSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic `response_model` konvertiert (und gefiltert), das Sie im *Pfadoperation-Dekorator* deklariert haben.
|
||||
|
||||
!!! note "Hinweis"
|
||||
Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation.
|
||||
|
||||
## `ORJSONResponse` verwenden
|
||||
|
||||
Um beispielsweise noch etwas Leistung herauszuholen, können Sie <a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a> installieren und verwenden, und die Response als `ORJSONResponse` deklarieren.
|
||||
|
||||
Importieren Sie die `Response`-Klasse (-Unterklasse), die Sie verwenden möchten, und deklarieren Sie sie im *Pfadoperation-Dekorator*.
|
||||
|
||||
Bei umfangreichen Responses ist die direkte Rückgabe einer `Response` viel schneller als ein Dictionary zurückzugeben.
|
||||
|
||||
Das liegt daran, dass FastAPI standardmäßig jedes enthaltene Element überprüft und sicherstellt, dass es als JSON serialisierbar ist, und zwar unter Verwendung desselben [JSON-kompatiblen Encoders](../tutorial/encoder.md){.internal-link target=_blank}, der im Tutorial erläutert wurde. Dadurch können Sie **beliebige Objekte** zurückgeben, zum Beispiel Datenbankmodelle.
|
||||
|
||||
Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSON serialisierbar** ist, können Sie ihn direkt an die Response-Klasse übergeben und die zusätzliche Arbeit vermeiden, die FastAPI hätte, indem es Ihren zurückgegebenen Inhalt durch den `jsonable_encoder` leitet, bevor es ihn an die Response-Klasse übergibt.
|
||||
|
||||
```Python hl_lines="2 7"
|
||||
{!../../../docs_src/custom_response/tutorial001b.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
|
||||
|
||||
In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt.
|
||||
|
||||
Und er wird als solcher in OpenAPI dokumentiert.
|
||||
|
||||
!!! tip "Tipp"
|
||||
Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette.
|
||||
|
||||
## HTML-Response
|
||||
|
||||
Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie `HTMLResponse`.
|
||||
|
||||
* Importieren Sie `HTMLResponse`.
|
||||
* Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*.
|
||||
|
||||
```Python hl_lines="2 7"
|
||||
{!../../../docs_src/custom_response/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! info
|
||||
Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren.
|
||||
|
||||
In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt.
|
||||
|
||||
Und er wird als solcher in OpenAPI dokumentiert.
|
||||
|
||||
### Eine `Response` zurückgeben
|
||||
|
||||
Wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} gezeigt, können Sie die Response auch direkt in Ihrer *Pfadoperation* überschreiben, indem Sie diese zurückgeben.
|
||||
|
||||
Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so aussehen:
|
||||
|
||||
```Python hl_lines="2 7 19"
|
||||
{!../../../docs_src/custom_response/tutorial003.py!}
|
||||
```
|
||||
|
||||
!!! warning "Achtung"
|
||||
Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar.
|
||||
|
||||
!!! info
|
||||
Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben.
|
||||
|
||||
### In OpenAPI dokumentieren und `Response` überschreiben
|
||||
|
||||
Wenn Sie die Response innerhalb der Funktion überschreiben und gleichzeitig den „Medientyp“ in OpenAPI dokumentieren möchten, können Sie den `response_class`-Parameter verwenden UND ein `Response`-Objekt zurückgeben.
|
||||
|
||||
Die `response_class` wird dann nur zur Dokumentation der OpenAPI-Pfadoperation* verwendet, Ihre `Response` wird jedoch unverändert verwendet.
|
||||
|
||||
#### Eine `HTMLResponse` direkt zurückgeben
|
||||
|
||||
Es könnte zum Beispiel so etwas sein:
|
||||
|
||||
```Python hl_lines="7 21 23"
|
||||
{!../../../docs_src/custom_response/tutorial004.py!}
|
||||
```
|
||||
|
||||
In diesem Beispiel generiert die Funktion `generate_html_response()` bereits eine `Response` und gibt sie zurück, anstatt das HTML in einem `str` zurückzugeben.
|
||||
|
||||
Indem Sie das Ergebnis des Aufrufs von `generate_html_response()` zurückgeben, geben Sie bereits eine `Response` zurück, die das Standardverhalten von **FastAPI** überschreibt.
|
||||
|
||||
Aber da Sie die `HTMLResponse` auch in der `response_class` übergeben haben, weiß **FastAPI**, dass sie in OpenAPI und der interaktiven Dokumentation als HTML mit `text/html` zu dokumentieren ist:
|
||||
|
||||
<img src="/img/tutorial/custom-response/image01.png">
|
||||
|
||||
## Verfügbare Responses
|
||||
|
||||
Hier sind einige der verfügbaren Responses.
|
||||
|
||||
Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen.
|
||||
|
||||
!!! note "Technische Details"
|
||||
Sie können auch `from starlette.responses import HTMLResponse` verwenden.
|
||||
|
||||
**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette.
|
||||
|
||||
### `Response`
|
||||
|
||||
Die Hauptklasse `Response`, alle anderen Responses erben von ihr.
|
||||
|
||||
Sie können sie direkt zurückgeben.
|
||||
|
||||
Sie akzeptiert die folgenden Parameter:
|
||||
|
||||
* `content` – Ein `str` oder `bytes`.
|
||||
* `status_code` – Ein `int`-HTTP-Statuscode.
|
||||
* `headers` – Ein `dict` von Strings.
|
||||
* `media_type` – Ein `str`, der den Medientyp angibt. Z. B. `"text/html"`.
|
||||
|
||||
FastAPI (eigentlich Starlette) fügt automatisch einen Content-Length-Header ein. Außerdem wird es einen Content-Type-Header einfügen, der auf dem media_type basiert, und für Texttypen einen Zeichensatz (charset) anfügen.
|
||||
|
||||
```Python hl_lines="1 18"
|
||||
{!../../../docs_src/response_directly/tutorial002.py!}
|
||||
```
|
||||
|
||||
### `HTMLResponse`
|
||||
|
||||
Nimmt Text oder Bytes entgegen und gibt eine HTML-Response zurück, wie Sie oben gelesen haben.
|
||||
|
||||
### `PlainTextResponse`
|
||||
|
||||
Nimmt Text oder Bytes entgegen und gibt eine Plain-Text-Response zurück.
|
||||
|
||||
```Python hl_lines="2 7 9"
|
||||
{!../../../docs_src/custom_response/tutorial005.py!}
|
||||
```
|
||||
|
||||
### `JSONResponse`
|
||||
|
||||
Nimmt einige Daten entgegen und gibt eine `application/json`-codierte Response zurück.
|
||||
|
||||
Dies ist die Standard-Response, die in **FastAPI** verwendet wird, wie Sie oben gelesen haben.
|
||||
|
||||
### `ORJSONResponse`
|
||||
|
||||
Eine schnelle alternative JSON-Response mit <a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a>, wie Sie oben gelesen haben.
|
||||
|
||||
### `UJSONResponse`
|
||||
|
||||
Eine alternative JSON-Response mit <a href="https://github.com/ultrajson/ultrajson" class="external-link" target="_blank">`ujson`</a>.
|
||||
|
||||
!!! warning "Achtung"
|
||||
`ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung.
|
||||
|
||||
```Python hl_lines="2 7"
|
||||
{!../../../docs_src/custom_response/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! tip "Tipp"
|
||||
Möglicherweise ist `ORJSONResponse` eine schnellere Alternative.
|
||||
|
||||
### `RedirectResponse`
|
||||
|
||||
Gibt eine HTTP-Weiterleitung (HTTP-Redirect) zurück. Verwendet standardmäßig den Statuscode 307 – Temporäre Weiterleitung (Temporary Redirect).
|
||||
|
||||
Sie können eine `RedirectResponse` direkt zurückgeben:
|
||||
|
||||
```Python hl_lines="2 9"
|
||||
{!../../../docs_src/custom_response/tutorial006.py!}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Oder Sie können sie im Parameter `response_class` verwenden:
|
||||
|
||||
|
||||
```Python hl_lines="2 7 9"
|
||||
{!../../../docs_src/custom_response/tutorial006b.py!}
|
||||
```
|
||||
|
||||
Wenn Sie das tun, können Sie die URL direkt von Ihrer *Pfadoperation*-Funktion zurückgeben.
|
||||
|
||||
In diesem Fall ist der verwendete `status_code` der Standardcode für die `RedirectResponse`, also `307`.
|
||||
|
||||
---
|
||||
|
||||
Sie können den Parameter `status_code` auch in Kombination mit dem Parameter `response_class` verwenden:
|
||||
|
||||
```Python hl_lines="2 7 9"
|
||||
{!../../../docs_src/custom_response/tutorial006c.py!}
|
||||
```
|
||||
|
||||
### `StreamingResponse`
|
||||
|
||||
Nimmt einen asynchronen Generator oder einen normalen Generator/Iterator und streamt den Responsebody.
|
||||
|
||||
```Python hl_lines="2 14"
|
||||
{!../../../docs_src/custom_response/tutorial007.py!}
|
||||
```
|
||||
|
||||
#### Verwendung von `StreamingResponse` mit dateiähnlichen Objekten
|
||||
|
||||
Wenn Sie ein dateiähnliches (file-like) Objekt haben (z. B. das von `open()` zurückgegebene Objekt), können Sie eine Generatorfunktion erstellen, um über dieses dateiähnliche Objekt zu iterieren.
|
||||
|
||||
Auf diese Weise müssen Sie nicht alles zuerst in den Arbeitsspeicher lesen und können diese Generatorfunktion an `StreamingResponse` übergeben und zurückgeben.
|
||||
|
||||
Das umfasst viele Bibliotheken zur Interaktion mit Cloud-Speicher, Videoverarbeitung und anderen.
|
||||
|
||||
```{ .python .annotate hl_lines="2 10-12 14" }
|
||||
{!../../../docs_src/custom_response/tutorial008.py!}
|
||||
```
|
||||
|
||||
1. Das ist die Generatorfunktion. Es handelt sich um eine „Generatorfunktion“, da sie `yield`-Anweisungen enthält.
|
||||
2. Durch die Verwendung eines `with`-Blocks stellen wir sicher, dass das dateiähnliche Objekt geschlossen wird, nachdem die Generatorfunktion fertig ist. Also, nachdem sie mit dem Senden der Response fertig ist.
|
||||
3. Dieses `yield from` weist die Funktion an, über das Ding namens `file_like` zu iterieren. Und dann für jeden iterierten Teil, diesen Teil so zurückzugeben, als wenn er aus dieser Generatorfunktion (`iterfile`) stammen würde.
|
||||
|
||||
Es handelt sich also hier um eine Generatorfunktion, die die „generierende“ Arbeit intern auf etwas anderes überträgt.
|
||||
|
||||
Auf diese Weise können wir das Ganze in einen `with`-Block einfügen und so sicherstellen, dass das dateiartige Objekt nach Abschluss geschlossen wird.
|
||||
|
||||
!!! tip "Tipp"
|
||||
Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren.
|
||||
|
||||
### `FileResponse`
|
||||
|
||||
Streamt eine Datei asynchron als Response.
|
||||
|
||||
Nimmt zur Instanziierung einen anderen Satz von Argumenten entgegen als die anderen Response-Typen:
|
||||
|
||||
* `path` – Der Dateipfad zur Datei, die gestreamt werden soll.
|
||||
* `headers` – Alle benutzerdefinierten Header, die inkludiert werden sollen, als Dictionary.
|
||||
* `media_type` – Ein String, der den Medientyp angibt. Wenn nicht gesetzt, wird der Dateiname oder Pfad verwendet, um auf einen Medientyp zu schließen.
|
||||
* `filename` – Wenn gesetzt, wird das in der `Content-Disposition` der Response eingefügt.
|
||||
|
||||
Datei-Responses enthalten die entsprechenden `Content-Length`-, `Last-Modified`- und `ETag`-Header.
|
||||
|
||||
```Python hl_lines="2 10"
|
||||
{!../../../docs_src/custom_response/tutorial009.py!}
|
||||
```
|
||||
|
||||
Sie können auch den Parameter `response_class` verwenden:
|
||||
|
||||
```Python hl_lines="2 8 10"
|
||||
{!../../../docs_src/custom_response/tutorial009b.py!}
|
||||
```
|
||||
|
||||
In diesem Fall können Sie den Dateipfad direkt von Ihrer *Pfadoperation*-Funktion zurückgeben.
|
||||
|
||||
## Benutzerdefinierte Response-Klasse
|
||||
|
||||
Sie können Ihre eigene benutzerdefinierte Response-Klasse erstellen, die von `Response` erbt und diese verwendet.
|
||||
|
||||
Nehmen wir zum Beispiel an, dass Sie <a href="https://github.com/ijl/orjson" class="external-link" target="_blank">`orjson`</a> verwenden möchten, aber mit einigen benutzerdefinierten Einstellungen, die in der enthaltenen `ORJSONResponse`-Klasse nicht verwendet werden.
|
||||
|
||||
Sie möchten etwa, dass Ihre Response eingerücktes und formatiertes JSON zurückgibt. Dafür möchten Sie die orjson-Option `orjson.OPT_INDENT_2` verwenden.
|
||||
|
||||
Sie könnten eine `CustomORJSONResponse` erstellen. Das Wichtigste, was Sie tun müssen, ist, eine `Response.render(content)`-Methode zu erstellen, die den Inhalt als `bytes` zurückgibt:
|
||||
|
||||
```Python hl_lines="9-14 17"
|
||||
{!../../../docs_src/custom_response/tutorial009c.py!}
|
||||
```
|
||||
|
||||
Statt:
|
||||
|
||||
```json
|
||||
{"message": "Hello World"}
|
||||
```
|
||||
|
||||
... wird die Response jetzt Folgendes zurückgeben:
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Hello World"
|
||||
}
|
||||
```
|
||||
|
||||
Natürlich werden Sie wahrscheinlich viel bessere Möglichkeiten finden, Vorteil daraus zu ziehen, als JSON zu formatieren. 😉
|
||||
|
||||
## Standard-Response-Klasse
|
||||
|
||||
Beim Erstellen einer **FastAPI**-Klasseninstanz oder eines `APIRouter`s können Sie angeben, welche Response-Klasse standardmäßig verwendet werden soll.
|
||||
|
||||
Der Parameter, der das definiert, ist `default_response_class`.
|
||||
|
||||
Im folgenden Beispiel verwendet **FastAPI** standardmäßig `ORJSONResponse` in allen *Pfadoperationen*, anstelle von `JSONResponse`.
|
||||
|
||||
```Python hl_lines="2 4"
|
||||
{!../../../docs_src/custom_response/tutorial010.py!}
|
||||
```
|
||||
|
||||
!!! tip "Tipp"
|
||||
Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher.
|
||||
|
||||
## Zusätzliche Dokumentation
|
||||
|
||||
Sie können auch den Medientyp und viele andere Details in OpenAPI mit `responses` deklarieren: [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
|
||||
286
docs/de/docs/advanced/generate-clients.md
Normal file
286
docs/de/docs/advanced/generate-clients.md
Normal file
@@ -0,0 +1,286 @@
|
||||
# Clients generieren
|
||||
|
||||
Da **FastAPI** auf der OpenAPI-Spezifikation basiert, erhalten Sie automatische Kompatibilität mit vielen Tools, einschließlich der automatischen API-Dokumentation (bereitgestellt von Swagger UI).
|
||||
|
||||
Ein besonderer Vorteil, der nicht unbedingt offensichtlich ist, besteht darin, dass Sie für Ihre API **Clients generieren** können (manchmal auch <abbr title="Software Development Kits">**SDKs**</abbr> genannt), für viele verschiedene **Programmiersprachen**.
|
||||
|
||||
## OpenAPI-Client-Generatoren
|
||||
|
||||
Es gibt viele Tools zum Generieren von Clients aus **OpenAPI**.
|
||||
|
||||
Ein gängiges Tool ist <a href="https://openapi-generator.tech/" class="external-link" target="_blank">OpenAPI Generator</a>.
|
||||
|
||||
Wenn Sie ein **Frontend** erstellen, ist <a href="https://github.com/ferdikoomen/openapi-typescript-codegen" class="external-link" target="_blank">openapi-typescript-codegen</a> eine sehr interessante Alternative.
|
||||
|
||||
## Client- und SDK-Generatoren – Sponsor
|
||||
|
||||
Es gibt auch einige **vom Unternehmen entwickelte** Client- und SDK-Generatoren, die auf OpenAPI (FastAPI) basieren. In einigen Fällen können diese Ihnen **weitere Funktionalität** zusätzlich zu qualitativ hochwertigen generierten SDKs/Clients bieten.
|
||||
|
||||
Einige von diesen ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponsern){.internal-link target=_blank} ✨, das gewährleistet die kontinuierliche und gesunde **Entwicklung** von FastAPI und seinem **Ökosystem**.
|
||||
|
||||
Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇
|
||||
|
||||
Beispielsweise könnten Sie <a href="https://speakeasyapi.dev/?utm_source=fastapi+repo&utm_medium=github+sponsorship" class="external-link" target="_blank">Speakeasy</a> ausprobieren.
|
||||
|
||||
Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und die Sie online suchen und finden können. 🤓
|
||||
|
||||
## Einen TypeScript-Frontend-Client generieren
|
||||
|
||||
Beginnen wir mit einer einfachen FastAPI-Anwendung:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="7-9 12-13 16-17 21"
|
||||
{!> ../../../docs_src/generate_clients/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="9-11 14-15 18 19 23"
|
||||
{!> ../../../docs_src/generate_clients/tutorial001.py!}
|
||||
```
|
||||
|
||||
Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-<abbr title="Die eigentlichen Nutzdaten, abzüglich der Metadaten">Payload</abbr> verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden.
|
||||
|
||||
### API-Dokumentation
|
||||
|
||||
Wenn Sie zur API-Dokumentation gehen, werden Sie sehen, dass diese die **Schemas** für die Daten enthält, welche in Requests gesendet und in Responses empfangen werden:
|
||||
|
||||
<img src="/img/tutorial/generate-clients/image01.png">
|
||||
|
||||
Sie können diese Schemas sehen, da sie mit den Modellen in der Anwendung deklariert wurden.
|
||||
|
||||
Diese Informationen sind im **OpenAPI-Schema** der Anwendung verfügbar und werden dann in der API-Dokumentation angezeigt (von Swagger UI).
|
||||
|
||||
Und dieselben Informationen aus den Modellen, die in OpenAPI enthalten sind, können zum **Generieren des Client-Codes** verwendet werden.
|
||||
|
||||
### Einen TypeScript-Client generieren
|
||||
|
||||
Nachdem wir nun die Anwendung mit den Modellen haben, können wir den Client-Code für das Frontend generieren.
|
||||
|
||||
#### `openapi-typescript-codegen` installieren
|
||||
|
||||
Sie können `openapi-typescript-codegen` in Ihrem Frontend-Code installieren mit:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ npm install openapi-typescript-codegen --save-dev
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
#### Client-Code generieren
|
||||
|
||||
Um den Client-Code zu generieren, können Sie das Kommandozeilentool `openapi` verwenden, das soeben installiert wurde.
|
||||
|
||||
Da es im lokalen Projekt installiert ist, könnten Sie diesen Befehl wahrscheinlich nicht direkt aufrufen, sondern würden ihn in Ihre Datei `package.json` einfügen.
|
||||
|
||||
Diese könnte so aussehen:
|
||||
|
||||
```JSON hl_lines="7"
|
||||
{
|
||||
"name": "frontend-app",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes"
|
||||
},
|
||||
"author": "",
|
||||
"license": "",
|
||||
"devDependencies": {
|
||||
"openapi-typescript-codegen": "^0.20.1",
|
||||
"typescript": "^4.6.2"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Nachdem Sie das NPM-Skript `generate-client` dort stehen haben, können Sie es ausführen mit:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ npm run generate-client
|
||||
|
||||
frontend-app@1.0.0 generate-client /home/user/code/frontend-app
|
||||
> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
Dieser Befehl generiert Code in `./src/client` und verwendet intern `axios` (die Frontend-HTTP-Bibliothek).
|
||||
|
||||
### Den Client-Code ausprobieren
|
||||
|
||||
Jetzt können Sie den Client-Code importieren und verwenden. Er könnte wie folgt aussehen, beachten Sie, dass Sie automatische Codevervollständigung für die Methoden erhalten:
|
||||
|
||||
<img src="/img/tutorial/generate-clients/image02.png">
|
||||
|
||||
Sie erhalten außerdem automatische Vervollständigung für die zu sendende Payload:
|
||||
|
||||
<img src="/img/tutorial/generate-clients/image03.png">
|
||||
|
||||
!!! tip "Tipp"
|
||||
Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden.
|
||||
|
||||
Sie erhalten Inline-Fehlerberichte für die von Ihnen gesendeten Daten:
|
||||
|
||||
<img src="/img/tutorial/generate-clients/image04.png">
|
||||
|
||||
Das Response-Objekt hat auch automatische Vervollständigung:
|
||||
|
||||
<img src="/img/tutorial/generate-clients/image05.png">
|
||||
|
||||
## FastAPI-Anwendung mit Tags
|
||||
|
||||
In vielen Fällen wird Ihre FastAPI-Anwendung größer sein und Sie werden wahrscheinlich Tags verwenden, um verschiedene Gruppen von *Pfadoperationen* zu separieren.
|
||||
|
||||
Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="21 26 34"
|
||||
{!> ../../../docs_src/generate_clients/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="23 28 36"
|
||||
{!> ../../../docs_src/generate_clients/tutorial002.py!}
|
||||
```
|
||||
|
||||
### Einen TypeScript-Client mit Tags generieren
|
||||
|
||||
Wenn Sie unter Verwendung von Tags einen Client für eine FastAPI-Anwendung generieren, wird normalerweise auch der Client-Code anhand der Tags getrennt.
|
||||
|
||||
Auf diese Weise können Sie die Dinge für den Client-Code richtig ordnen und gruppieren:
|
||||
|
||||
<img src="/img/tutorial/generate-clients/image06.png">
|
||||
|
||||
In diesem Fall haben Sie:
|
||||
|
||||
* `ItemsService`
|
||||
* `UsersService`
|
||||
|
||||
### Client-Methodennamen
|
||||
|
||||
Im Moment sehen die generierten Methodennamen wie `createItemItemsPost` nicht sehr sauber aus:
|
||||
|
||||
```TypeScript
|
||||
ItemsService.createItemItemsPost({name: "Plumbus", price: 5})
|
||||
```
|
||||
|
||||
... das liegt daran, dass der Client-Generator für jede *Pfadoperation* die OpenAPI-interne **Operation-ID** verwendet.
|
||||
|
||||
OpenAPI erfordert, dass jede Operation-ID innerhalb aller *Pfadoperationen* eindeutig ist. Daher verwendet FastAPI den **Funktionsnamen**, den **Pfad** und die **HTTP-Methode/-Operation**, um diese Operation-ID zu generieren. Denn so kann sichergestellt werden, dass die Operation-IDs eindeutig sind.
|
||||
|
||||
Aber ich zeige Ihnen als nächstes, wie Sie das verbessern können. 🤓
|
||||
|
||||
## Benutzerdefinierte Operation-IDs und bessere Methodennamen
|
||||
|
||||
Sie können die Art und Weise, wie diese Operation-IDs **generiert** werden, **ändern**, um sie einfacher zu machen und **einfachere Methodennamen** in den Clients zu haben.
|
||||
|
||||
In diesem Fall müssen Sie auf andere Weise sicherstellen, dass jede Operation-ID **eindeutig** ist.
|
||||
|
||||
Sie könnten beispielsweise sicherstellen, dass jede *Pfadoperation* einen Tag hat, und dann die Operation-ID basierend auf dem **Tag** und dem **Namen** der *Pfadoperation* (dem Funktionsnamen) generieren.
|
||||
|
||||
### Funktion zum Generieren einer eindeutigen ID erstellen
|
||||
|
||||
FastAPI verwendet eine **eindeutige ID** für jede *Pfadoperation*, diese wird für die **Operation-ID** und auch für die Namen aller benötigten benutzerdefinierten Modelle für Requests oder Responses verwendet.
|
||||
|
||||
Sie können diese Funktion anpassen. Sie nimmt eine `APIRoute` und gibt einen String zurück.
|
||||
|
||||
Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur einen Tag haben) und den Namen der *Pfadoperation* (den Funktionsnamen).
|
||||
|
||||
Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="6-7 10"
|
||||
{!> ../../../docs_src/generate_clients/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="8-9 12"
|
||||
{!> ../../../docs_src/generate_clients/tutorial003.py!}
|
||||
```
|
||||
|
||||
### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren
|
||||
|
||||
Wenn Sie nun den Client erneut generieren, werden Sie feststellen, dass er über die verbesserten Methodennamen verfügt:
|
||||
|
||||
<img src="/img/tutorial/generate-clients/image07.png">
|
||||
|
||||
Wie Sie sehen, haben die Methodennamen jetzt den Tag und dann den Funktionsnamen, aber keine Informationen aus dem URL-Pfad und der HTTP-Operation.
|
||||
|
||||
### Vorab-Modifikation der OpenAPI-Spezifikation für den Client-Generator
|
||||
|
||||
Der generierte Code enthält immer noch etwas **verdoppelte Information**.
|
||||
|
||||
Wir wissen bereits, dass diese Methode mit den **Items** zusammenhängt, da sich dieses Wort in `ItemsService` befindet (vom Tag übernommen), aber wir haben auch immer noch den Tagnamen im Methodennamen vorangestellt. 😕
|
||||
|
||||
Wir werden das wahrscheinlich weiterhin für OpenAPI im Allgemeinen beibehalten wollen, da dadurch sichergestellt wird, dass die Operation-IDs **eindeutig** sind.
|
||||
|
||||
Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt vor der Generierung der Clients **modifizieren**, um diese Methodennamen schöner und **sauberer** zu machen.
|
||||
|
||||
Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**:
|
||||
|
||||
=== "Python"
|
||||
|
||||
```Python
|
||||
{!> ../../../docs_src/generate_clients/tutorial004.py!}
|
||||
```
|
||||
|
||||
=== "Node.js"
|
||||
|
||||
```Javascript
|
||||
{!> ../../../docs_src/generate_clients/tutorial004.js!}
|
||||
```
|
||||
|
||||
Damit würden die Operation-IDs von Dingen wie `items-get_items` in `get_items` umbenannt, sodass der Client-Generator einfachere Methodennamen generieren kann.
|
||||
|
||||
### Einen TypeScript-Client mit der modifizierten OpenAPI generieren
|
||||
|
||||
Da das Endergebnis nun in einer Datei `openapi.json` vorliegt, würden Sie die `package.json` ändern, um diese lokale Datei zu verwenden, zum Beispiel:
|
||||
|
||||
```JSON hl_lines="7"
|
||||
{
|
||||
"name": "frontend-app",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"generate-client": "openapi --input ./openapi.json --output ./src/client --client axios --useOptions --useUnionTypes"
|
||||
},
|
||||
"author": "",
|
||||
"license": "",
|
||||
"devDependencies": {
|
||||
"openapi-typescript-codegen": "^0.20.1",
|
||||
"typescript": "^4.6.2"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Nach der Generierung des neuen Clients hätten Sie nun **saubere Methodennamen** mit allen **Autovervollständigungen**, **Inline-Fehlerberichten**, usw.:
|
||||
|
||||
<img src="/img/tutorial/generate-clients/image08.png">
|
||||
|
||||
## Vorteile
|
||||
|
||||
Wenn Sie die automatisch generierten Clients verwenden, erhalten Sie **automatische Codevervollständigung** für:
|
||||
|
||||
* Methoden.
|
||||
* Request-Payloads im Body, Query-Parameter, usw.
|
||||
* Response-Payloads.
|
||||
|
||||
Außerdem erhalten Sie für alles **Inline-Fehlerberichte**.
|
||||
|
||||
Und wann immer Sie den Backend-Code aktualisieren und das Frontend **neu generieren**, stehen alle neuen *Pfadoperationen* als Methoden zur Verfügung, die alten werden entfernt und alle anderen Änderungen werden im generierten Code reflektiert. 🤓
|
||||
|
||||
Das bedeutet auch, dass, wenn sich etwas ändert, dies automatisch im Client-Code **reflektiert** wird. Und wenn Sie den Client **erstellen**, kommt es zu einer Fehlermeldung, wenn die verwendeten Daten **nicht übereinstimmen**.
|
||||
|
||||
Sie würden also sehr früh im Entwicklungszyklus **viele Fehler erkennen**, anstatt darauf warten zu müssen, dass die Fehler Ihren Endbenutzern in der Produktion angezeigt werden, und dann zu versuchen, zu debuggen, wo das Problem liegt. ✨
|
||||
51
docs/de/docs/advanced/openapi-webhooks.md
Normal file
51
docs/de/docs/advanced/openapi-webhooks.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# OpenAPI-Webhooks
|
||||
|
||||
Es gibt Fälle, in denen Sie Ihren API-Benutzern mitteilen möchten, dass Ihre Anwendung mit einigen Daten *deren* Anwendung aufrufen (ein Request senden) könnte, normalerweise um über ein bestimmtes **Event** zu **benachrichtigen**.
|
||||
|
||||
Das bedeutet, dass anstelle des normalen Prozesses, bei dem Benutzer Requests an Ihre API senden, **Ihre API** (oder Ihre Anwendung) **Requests an deren System** (an deren API, deren Anwendung) senden könnte.
|
||||
|
||||
Das wird normalerweise als **Webhook** bezeichnet.
|
||||
|
||||
## Webhooks-Schritte
|
||||
|
||||
Der Prozess besteht normalerweise darin, dass **Sie in Ihrem Code definieren**, welche Nachricht Sie senden möchten, den **Body des Requests**.
|
||||
|
||||
Sie definieren auch auf irgendeine Weise, zu welchen **Momenten** Ihre Anwendung diese Requests oder Events sendet.
|
||||
|
||||
Und **Ihre Benutzer** definieren auf irgendeine Weise (zum Beispiel irgendwo in einem Web-Dashboard) die **URL**, an die Ihre Anwendung diese Requests senden soll.
|
||||
|
||||
Die gesamte **Logik** zur Registrierung der URLs für Webhooks und der Code zum tatsächlichen Senden dieser Requests liegt bei Ihnen. Sie schreiben es so, wie Sie möchten, in **Ihrem eigenen Code**.
|
||||
|
||||
## Webhooks mit **FastAPI** und OpenAPI dokumentieren
|
||||
|
||||
Mit **FastAPI** können Sie mithilfe von OpenAPI die Namen dieser Webhooks, die Arten von HTTP-Operationen, die Ihre Anwendung senden kann (z. B. `POST`, `PUT`, usw.) und die Request**bodys** definieren, die Ihre Anwendung senden würde.
|
||||
|
||||
Dies kann es Ihren Benutzern viel einfacher machen, **deren APIs zu implementieren**, um Ihre **Webhook**-Requests zu empfangen. Möglicherweise können diese sogar einen Teil des eigenem API-Codes automatisch generieren.
|
||||
|
||||
!!! info
|
||||
Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt.
|
||||
|
||||
## Eine Anwendung mit Webhooks
|
||||
|
||||
Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, mit dem Sie *Webhooks* definieren können, genauso wie Sie *Pfadoperationen* definieren würden, zum Beispiel mit `@app.webhooks.post()`.
|
||||
|
||||
```Python hl_lines="9-13 36-53"
|
||||
{!../../../docs_src/openapi_webhooks/tutorial001.py!}
|
||||
```
|
||||
|
||||
Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**.
|
||||
|
||||
!!! info
|
||||
Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren.
|
||||
|
||||
Beachten Sie, dass Sie bei Webhooks tatsächlich keinen *Pfad* (wie `/items/`) deklarieren, sondern dass der Text, den Sie dort übergeben, lediglich eine **Kennzeichnung** des Webhooks (der Name des Events) ist. Zum Beispiel ist in `@app.webhooks.post("new-subscription")` der Webhook-Name `new-subscription`.
|
||||
|
||||
Das liegt daran, dass erwartet wird, dass **Ihre Benutzer** den tatsächlichen **URL-Pfad**, an dem diese den Webhook-Request empfangen möchten, auf andere Weise definieren (z. B. über ein Web-Dashboard).
|
||||
|
||||
### Es in der Dokumentation ansehen
|
||||
|
||||
Jetzt können Sie Ihre Anwendung mit Uvicorn starten und auf <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a> gehen.
|
||||
|
||||
Sie werden sehen, dass Ihre Dokumentation die normalen *Pfadoperationen* und jetzt auch einige **Webhooks** enthält:
|
||||
|
||||
<img src="/img/tutorial/openapi-webhooks/image01.png">
|
||||
34
docs/de/docs/benchmarks.md
Normal file
34
docs/de/docs/benchmarks.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Benchmarks
|
||||
|
||||
Unabhängige TechEmpower-Benchmarks zeigen, **FastAPI**-Anwendungen, die unter Uvicorn ausgeführt werden, gehören zu <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">den schnellsten existierenden Python-Frameworks</a>, nur Starlette und Uvicorn selbst (intern von FastAPI verwendet) sind schneller.
|
||||
|
||||
Beim Ansehen von Benchmarks und Vergleichen sollten Sie jedoch Folgende Punkte beachten.
|
||||
|
||||
## Benchmarks und Geschwindigkeit
|
||||
|
||||
Wenn Sie sich die Benchmarks ansehen, werden häufig mehrere Tools mit unterschiedlichen Eigenschaften als gleichwertig verglichen.
|
||||
|
||||
Konkret geht es darum, Uvicorn, Starlette und FastAPI miteinander zu vergleichen (neben vielen anderen Tools).
|
||||
|
||||
Je einfacher das Problem, welches durch das Tool gelöst wird, desto besser ist die Performanz. Und die meisten Benchmarks testen nicht die zusätzlichen Funktionen, welche das Tool bietet.
|
||||
|
||||
Die Hierarchie ist wie folgt:
|
||||
|
||||
* **Uvicorn**: ein ASGI-Server
|
||||
* **Starlette**: (verwendet Uvicorn) ein Web-Mikroframework
|
||||
* **FastAPI**: (verwendet Starlette) ein API-Mikroframework mit mehreren zusätzlichen Funktionen zum Erstellen von APIs, mit Datenvalidierung, usw.
|
||||
|
||||
* **Uvicorn**:
|
||||
* Bietet die beste Leistung, da außer dem Server selbst nicht viel zusätzlicher Code vorhanden ist.
|
||||
* Sie würden eine Anwendung nicht direkt in Uvicorn schreiben. Das würde bedeuten, dass Ihr Code zumindest mehr oder weniger den gesamten von Starlette (oder **FastAPI**) bereitgestellten Code enthalten müsste. Und wenn Sie das täten, hätte Ihre endgültige Anwendung den gleichen Overhead wie die Verwendung eines Frameworks nebst Minimierung Ihres Anwendungscodes und der Fehler.
|
||||
* Wenn Sie Uvicorn vergleichen, vergleichen Sie es mit Anwendungsservern wie Daphne, Hypercorn, uWSGI, usw.
|
||||
* **Starlette**:
|
||||
* Wird nach Uvicorn die nächstbeste Performanz erbringen. Tatsächlich nutzt Starlette intern Uvicorn. Daher kann es wahrscheinlich nur „langsamer“ als Uvicorn sein, weil mehr Code ausgeführt wird.
|
||||
* Aber es bietet Ihnen die Tools zum Erstellen einfacher Webanwendungen, mit Routing basierend auf Pfaden, usw.
|
||||
* Wenn Sie Starlette vergleichen, vergleichen Sie es mit Webframeworks (oder Mikroframeworks) wie Sanic, Flask, Django, usw.
|
||||
* **FastAPI**:
|
||||
* So wie Starlette Uvicorn verwendet und nicht schneller als dieses sein kann, verwendet **FastAPI** Starlette, sodass es nicht schneller als dieses sein kann.
|
||||
* FastAPI bietet zusätzlich zu Starlette weitere Funktionen. Funktionen, die Sie beim Erstellen von APIs fast immer benötigen, wie Datenvalidierung und Serialisierung. Und wenn Sie es verwenden, erhalten Sie kostenlos automatische Dokumentation (die automatische Dokumentation verursacht nicht einmal zusätzlichen Aufwand für laufende Anwendungen, sie wird beim Start generiert).
|
||||
* Wenn Sie FastAPI nicht, und direkt Starlette (oder ein anderes Tool wie Sanic, Flask, Responder, usw.) verwenden würden, müssten Sie die gesamte Datenvalidierung und Serialisierung selbst implementieren. Ihre finale Anwendung hätte also immer noch den gleichen Overhead, als ob sie mit FastAPI erstellt worden wäre. Und in vielen Fällen ist diese Datenvalidierung und Serialisierung der größte Teil des in Anwendungen geschriebenen Codes.
|
||||
* Durch die Verwendung von FastAPI sparen Sie also Entwicklungszeit, Fehler und Codezeilen und würden wahrscheinlich die gleiche Leistung (oder eine bessere) erzielen, die Sie hätten, wenn Sie es nicht verwenden würden (da Sie alles in Ihrem Code implementieren müssten).
|
||||
* Wenn Sie FastAPI vergleichen, vergleichen Sie es mit einem Webanwendung-Framework (oder einer Reihe von Tools), welche Datenvalidierung, Serialisierung und Dokumentation bereitstellen, wie Flask-apispec, NestJS, Molten, usw. – Frameworks mit integrierter automatischer Datenvalidierung, Serialisierung und Dokumentation.
|
||||
3
docs/de/docs/help/index.md
Normal file
3
docs/de/docs/help/index.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Hilfe
|
||||
|
||||
Helfen und Hilfe erhalten, beitragen, mitmachen. 🤝
|
||||
5
docs/de/docs/learn/index.md
Normal file
5
docs/de/docs/learn/index.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Lernen
|
||||
|
||||
Hier finden Sie die einführenden Kapitel und Tutorials zum Erlernen von **FastAPI**.
|
||||
|
||||
Sie könnten dies als **Buch**, als **Kurs**, als **offizielle** und empfohlene Methode zum Erlernen von FastAPI betrachten. 😎
|
||||
8
docs/de/docs/reference/index.md
Normal file
8
docs/de/docs/reference/index.md
Normal file
@@ -0,0 +1,8 @@
|
||||
# Referenz – Code-API
|
||||
|
||||
Hier ist die Referenz oder Code-API, die Klassen, Funktionen, Parameter, Attribute und alle FastAPI-Teile, die Sie in Ihren Anwendungen verwenden können.
|
||||
|
||||
Wenn Sie **FastAPI** lernen möchten, ist es viel besser, das [FastAPI-Tutorial](https://fastapi.tiangolo.com/tutorial/) zu lesen.
|
||||
|
||||
!!! note "Hinweis Deutsche Übersetzung"
|
||||
Die nachfolgende API wird aus der Quelltext-Dokumentation erstellt, daher sind nur die Einleitungen auf Deutsch.
|
||||
3
docs/de/docs/resources/index.md
Normal file
3
docs/de/docs/resources/index.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# Ressourcen
|
||||
|
||||
Zusätzliche Ressourcen, externe Links, Artikel und mehr. ✈️
|
||||
126
docs/de/docs/tutorial/background-tasks.md
Normal file
126
docs/de/docs/tutorial/background-tasks.md
Normal file
@@ -0,0 +1,126 @@
|
||||
# Hintergrundtasks
|
||||
|
||||
Sie können Hintergrundtasks (Hintergrund-Aufgaben) definieren, die *nach* der Rückgabe einer Response ausgeführt werden sollen.
|
||||
|
||||
Das ist nützlich für Vorgänge, die nach einem Request ausgeführt werden müssen, bei denen der Client jedoch nicht unbedingt auf den Abschluss des Vorgangs warten muss, bevor er die Response erhält.
|
||||
|
||||
Hierzu zählen beispielsweise:
|
||||
|
||||
* E-Mail-Benachrichtigungen, die nach dem Ausführen einer Aktion gesendet werden:
|
||||
* Da die Verbindung zu einem E-Mail-Server und das Senden einer E-Mail in der Regel „langsam“ ist (einige Sekunden), können Sie die Response sofort zurücksenden und die E-Mail-Benachrichtigung im Hintergrund senden.
|
||||
* Daten verarbeiten:
|
||||
* Angenommen, Sie erhalten eine Datei, die einen langsamen Prozess durchlaufen muss. Sie können als Response „Accepted“ (HTTP 202) zurückgeben und die Datei im Hintergrund verarbeiten.
|
||||
|
||||
## `BackgroundTasks` verwenden
|
||||
|
||||
Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`:
|
||||
|
||||
```Python hl_lines="1 13"
|
||||
{!../../../docs_src/background_tasks/tutorial001.py!}
|
||||
```
|
||||
|
||||
**FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter.
|
||||
|
||||
## Eine Taskfunktion erstellen
|
||||
|
||||
Erstellen Sie eine Funktion, die als Hintergrundtask ausgeführt werden soll.
|
||||
|
||||
Es handelt sich schlicht um eine Standard-Funktion, die Parameter empfangen kann.
|
||||
|
||||
Es kann sich um eine `async def`- oder normale `def`-Funktion handeln. **FastAPI** weiß, wie damit zu verfahren ist.
|
||||
|
||||
In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail simulierend).
|
||||
|
||||
Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`:
|
||||
|
||||
```Python hl_lines="6-9"
|
||||
{!../../../docs_src/background_tasks/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Den Hintergrundtask hinzufügen
|
||||
|
||||
Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt:
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!../../../docs_src/background_tasks/tutorial001.py!}
|
||||
```
|
||||
|
||||
`.add_task()` erhält als Argumente:
|
||||
|
||||
* Eine Taskfunktion, die im Hintergrund ausgeführt wird (`write_notification`).
|
||||
* Eine beliebige Folge von Argumenten, die der Reihe nach an die Taskfunktion übergeben werden sollen (`email`).
|
||||
* Alle Schlüsselwort-Argumente, die an die Taskfunktion übergeben werden sollen (`message="some notification"`).
|
||||
|
||||
## Dependency Injection
|
||||
|
||||
Die Verwendung von `BackgroundTasks` funktioniert auch mit dem <abbr title="Einbringen von Abhängigkeiten">Dependency Injection</abbr> System. Sie können einen Parameter vom Typ `BackgroundTasks` auf mehreren Ebenen deklarieren: in einer *Pfadoperation-Funktion*, in einer Abhängigkeit (Dependable), in einer Unterabhängigkeit usw.
|
||||
|
||||
**FastAPI** weiß, was jeweils zu tun ist und wie dasselbe Objekt wiederverwendet werden kann, sodass alle Hintergrundtasks zusammengeführt und anschließend im Hintergrund ausgeführt werden:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="13 15 22 25"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="13 15 22 25"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="14 16 23 26"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002_an.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.10+ nicht annotiert"
|
||||
|
||||
!!! tip "Tipp"
|
||||
Bevorzugen Sie die `Annotated`-Version, falls möglich.
|
||||
|
||||
```Python hl_lines="11 13 20 23"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+ nicht annotiert"
|
||||
|
||||
!!! tip "Tipp"
|
||||
Bevorzugen Sie die `Annotated`-Version, falls möglich.
|
||||
|
||||
```Python hl_lines="13 15 22 25"
|
||||
{!> ../../../docs_src/background_tasks/tutorial002.py!}
|
||||
```
|
||||
|
||||
In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben.
|
||||
|
||||
Wenn im Request ein Query-Parameter enthalten war, wird dieser in einem Hintergrundtask in das Log geschrieben.
|
||||
|
||||
Und dann schreibt ein weiterer Hintergrundtask, der in der *Pfadoperation-Funktion* erstellt wird, eine Nachricht unter Verwendung des Pfad-Parameters `email`.
|
||||
|
||||
## Technische Details
|
||||
|
||||
Die Klasse `BackgroundTasks` stammt direkt von <a href="https://www.starlette.io/background/" class="external-link" target="_blank">`starlette.background`</a>.
|
||||
|
||||
Sie wird direkt in FastAPI importiert/inkludiert, sodass Sie sie von `fastapi` importieren können und vermeiden, versehentlich das alternative `BackgroundTask` (ohne das `s` am Ende) von `starlette.background` zu importieren.
|
||||
|
||||
Indem Sie nur `BackgroundTasks` (und nicht `BackgroundTask`) verwenden, ist es dann möglich, es als *Pfadoperation-Funktion*-Parameter zu verwenden und **FastAPI** den Rest für Sie erledigen zu lassen, genau wie bei der direkten Verwendung des `Request`-Objekts.
|
||||
|
||||
Es ist immer noch möglich, `BackgroundTask` allein in FastAPI zu verwenden, aber Sie müssen das Objekt in Ihrem Code erstellen und eine Starlette-`Response` zurückgeben, die es enthält.
|
||||
|
||||
Weitere Details finden Sie in der <a href="https://www.starlette.io/background/" class="external-link" target="_blank">offiziellen Starlette-Dokumentation für Hintergrundtasks</a>.
|
||||
|
||||
## Vorbehalt
|
||||
|
||||
Wenn Sie umfangreiche Hintergrundberechnungen durchführen müssen und diese nicht unbedingt vom selben Prozess ausgeführt werden müssen (z. B. müssen Sie Speicher, Variablen, usw. nicht gemeinsam nutzen), könnte die Verwendung anderer größerer Tools wie z. B. <a href="https://docs.celeryq.dev" class="external-link" target="_blank">Celery</a> von Vorteil sein.
|
||||
|
||||
Sie erfordern in der Regel komplexere Konfigurationen und einen Nachrichten-/Job-Queue-Manager wie RabbitMQ oder Redis, ermöglichen Ihnen jedoch die Ausführung von Hintergrundtasks in mehreren Prozessen und insbesondere auf mehreren Servern.
|
||||
|
||||
Um ein Beispiel zu sehen, sehen Sie sich die [Projektgeneratoren](../project-generation.md){.internal-link target=_blank} an. Sie alle enthalten Celery, bereits konfiguriert.
|
||||
|
||||
Wenn Sie jedoch über dieselbe **FastAPI**-Anwendung auf Variablen und Objekte zugreifen oder kleine Hintergrundtasks ausführen müssen (z. B. das Senden einer E-Mail-Benachrichtigung), können Sie einfach `BackgroundTasks` verwenden.
|
||||
|
||||
## Zusammenfassung
|
||||
|
||||
Importieren und verwenden Sie `BackgroundTasks` mit Parametern in *Pfadoperation-Funktionen* und Abhängigkeiten, um Hintergrundtasks hinzuzufügen.
|
||||
@@ -43,7 +43,7 @@ Diese Zeile zeigt die URL, unter der Ihre Anwendung auf Ihrem lokalen Computer b
|
||||
|
||||
Öffnen Sie Ihren Browser unter <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000.</a>
|
||||
|
||||
Sie werden folgende JSON-Antwort sehen:
|
||||
Sie werden folgende JSON-Response sehen:
|
||||
|
||||
```JSON
|
||||
{"message": "Hello World"}
|
||||
@@ -81,7 +81,7 @@ Diese Schemadefinition enthält Ihre API-Pfade, die möglichen Parameter, welche
|
||||
|
||||
#### Daten-„Schema“
|
||||
|
||||
Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z.B. einen JSON-Inhalt.
|
||||
Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z. B. einen JSON-Inhalt.
|
||||
|
||||
In diesem Fall sind die JSON-Attribute und deren Datentypen, usw. gemeint.
|
||||
|
||||
@@ -328,6 +328,6 @@ Es gibt viele andere Objekte und Modelle, die automatisch zu JSON konvertiert we
|
||||
|
||||
* Importieren Sie `FastAPI`.
|
||||
* Erstellen Sie eine `app` Instanz.
|
||||
* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z.B. `@app.get("/")`).
|
||||
* Schreiben Sie eine **Pfadoperation-Funktion** (wie z.B. oben `def root(): ...`).
|
||||
* Starten Sie den Entwicklungsserver (z.B. `uvicorn main:app --reload`).
|
||||
* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z. B. `@app.get("/")`).
|
||||
* Schreiben Sie eine **Pfadoperation-Funktion** (wie z. B. oben `def root(): ...`).
|
||||
* Starten Sie den Entwicklungsserver (z. B. `uvicorn main:app --reload`).
|
||||
|
||||
80
docs/de/docs/tutorial/index.md
Normal file
80
docs/de/docs/tutorial/index.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# Tutorial – Benutzerhandbuch
|
||||
|
||||
Dieses Tutorial zeigt Ihnen Schritt für Schritt, wie Sie **FastAPI** und die meisten seiner Funktionen verwenden können.
|
||||
|
||||
Jeder Abschnitt baut schrittweise auf den vorhergehenden auf. Diese Abschnitte sind aber nach einzelnen Themen gegliedert, sodass Sie direkt zu einem bestimmten Thema übergehen können, um Ihre speziellen API-Anforderungen zu lösen.
|
||||
|
||||
Außerdem dienen diese als zukünftige Referenz.
|
||||
|
||||
Dadurch können Sie jederzeit zurückkommen und sehen genau das, was Sie benötigen.
|
||||
|
||||
## Den Code ausführen
|
||||
|
||||
Alle Codeblöcke können kopiert und direkt verwendet werden (da es sich um getestete Python-Dateien handelt).
|
||||
|
||||
Um eines der Beispiele auszuführen, kopieren Sie den Code in eine Datei `main.py`, und starten Sie `uvicorn` mit:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --reload
|
||||
|
||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
||||
<span style="color: green;">INFO</span>: Started reloader process [28720]
|
||||
<span style="color: green;">INFO</span>: Started server process [28722]
|
||||
<span style="color: green;">INFO</span>: Waiting for application startup.
|
||||
<span style="color: green;">INFO</span>: Application startup complete.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
Es wird **ausdrücklich empfohlen**, dass Sie den Code schreiben oder kopieren, ihn bearbeiten und lokal ausführen.
|
||||
|
||||
Die Verwendung in Ihrem eigenen Editor zeigt Ihnen die Vorteile von FastAPI am besten, wenn Sie sehen, wie wenig Code Sie schreiben müssen, all die Typprüfungen, die automatische Vervollständigung usw.
|
||||
|
||||
---
|
||||
|
||||
## FastAPI installieren
|
||||
|
||||
Der erste Schritt besteht aus der Installation von FastAPI.
|
||||
|
||||
Für dieses Tutorial empfiehlt es sich, FastAPI mit allen optionalen Abhängigkeiten und Funktionen zu installieren:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "fastapi[all]"
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
... das beinhaltet auch `uvicorn`, welchen Sie als Server verwenden können, der ihren Code ausführt.
|
||||
|
||||
!!! note "Hinweis"
|
||||
Sie können die einzelnen Teile auch separat installieren.
|
||||
|
||||
Das folgende würden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung in der Produktion einsetzen:
|
||||
|
||||
```
|
||||
pip install fastapi
|
||||
```
|
||||
|
||||
Installieren Sie auch `uvicorn` als Server:
|
||||
|
||||
```
|
||||
pip install "uvicorn[standard]"
|
||||
```
|
||||
|
||||
Das gleiche gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten.
|
||||
|
||||
## Handbuch für fortgeschrittene Benutzer
|
||||
|
||||
Es gibt auch ein **Handbuch für fortgeschrittene Benutzer**, welches Sie später nach diesem **Tutorial – Benutzerhandbuch** lesen können.
|
||||
|
||||
Das **Handbuch für fortgeschrittene Benutzer** baut auf diesem Tutorial auf, verwendet dieselben Konzepte und bringt Ihnen einige zusätzliche Funktionen bei.
|
||||
|
||||
Allerdings sollten Sie zuerst das **Tutorial – Benutzerhandbuch** lesen (was Sie hier gerade tun).
|
||||
|
||||
Die Dokumentation ist so konzipiert, dass Sie mit dem **Tutorial – Benutzerhandbuch** eine vollständige Anwendung erstellen können und diese dann je nach Bedarf mit einigen der zusätzlichen Ideen aus dem **Handbuch für fortgeschrittene Benutzer** vervollständigen können.
|
||||
61
docs/de/docs/tutorial/middleware.md
Normal file
61
docs/de/docs/tutorial/middleware.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# Middleware
|
||||
|
||||
Sie können Middleware zu **FastAPI**-Anwendungen hinzufügen.
|
||||
|
||||
Eine „Middleware“ ist eine Funktion, die mit jedem **Request** arbeitet, bevor er von einer bestimmten *Pfadoperation* verarbeitet wird. Und auch mit jeder **Response**, bevor sie zurückgegeben wird.
|
||||
|
||||
* Sie nimmt jeden **Request** entgegen, der an Ihre Anwendung gesendet wird.
|
||||
* Sie kann dann etwas mit diesem **Request** tun oder beliebigen Code ausführen.
|
||||
* Dann gibt sie den **Request** zur Verarbeitung durch den Rest der Anwendung weiter (durch eine bestimmte *Pfadoperation*).
|
||||
* Sie nimmt dann die **Response** entgegen, die von der Anwendung generiert wurde (durch eine bestimmte *Pfadoperation*).
|
||||
* Sie kann etwas mit dieser **Response** tun oder beliebigen Code ausführen.
|
||||
* Dann gibt sie die **Response** zurück.
|
||||
|
||||
!!! note "Technische Details"
|
||||
Wenn Sie Abhängigkeiten mit `yield` haben, wird der Exit-Code *nach* der Middleware ausgeführt.
|
||||
|
||||
Wenn es Hintergrundaufgaben gab (später dokumentiert), werden sie *nach* allen Middlewares ausgeführt.
|
||||
|
||||
## Erstellung einer Middleware
|
||||
|
||||
Um eine Middleware zu erstellen, verwenden Sie den Dekorator `@app.middleware("http")` über einer Funktion.
|
||||
|
||||
Die Middleware-Funktion erhält:
|
||||
|
||||
* Den `request`.
|
||||
* Eine Funktion `call_next`, die den `request` als Parameter erhält.
|
||||
* Diese Funktion gibt den `request` an die entsprechende *Pfadoperation* weiter.
|
||||
* Dann gibt es die von der entsprechenden *Pfadoperation* generierte `response` zurück.
|
||||
* Sie können die `response` dann weiter modifizieren, bevor Sie sie zurückgeben.
|
||||
|
||||
```Python hl_lines="8-9 11 14"
|
||||
{!../../../docs_src/middleware/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! tip "Tipp"
|
||||
Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">Verwenden Sie dafür das Präfix 'X-'</a>.
|
||||
|
||||
Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette-CORS-Dokumentation</a> dokumentiert ist.
|
||||
|
||||
!!! note "Technische Details"
|
||||
Sie könnten auch `from starlette.requests import Request` verwenden.
|
||||
|
||||
**FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette.
|
||||
|
||||
### Vor und nach der `response`
|
||||
|
||||
Sie können Code hinzufügen, der mit dem `request` ausgeführt wird, bevor dieser von einer beliebigen *Pfadoperation* empfangen wird.
|
||||
|
||||
Und auch nachdem die `response` generiert wurde, bevor sie zurückgegeben wird.
|
||||
|
||||
Sie könnten beispielsweise einen benutzerdefinierten Header `X-Process-Time` hinzufügen, der die Zeit in Sekunden enthält, die benötigt wurde, um den Request zu verarbeiten und eine Response zu generieren:
|
||||
|
||||
```Python hl_lines="10 12-13"
|
||||
{!../../../docs_src/middleware/tutorial001.py!}
|
||||
```
|
||||
|
||||
## Andere Middlewares
|
||||
|
||||
Sie können später mehr über andere Middlewares in [Handbuch für fortgeschrittene Benutzer: Fortgeschrittene Middleware](../advanced/middleware.md){.internal-link target=_blank} lesen.
|
||||
|
||||
In der nächsten Sektion erfahren Sie, wie Sie <abbr title="Cross-Origin Resource Sharing">CORS</abbr> mit einer Middleware behandeln können.
|
||||
226
docs/de/docs/tutorial/query-params.md
Normal file
226
docs/de/docs/tutorial/query-params.md
Normal file
@@ -0,0 +1,226 @@
|
||||
# Query-Parameter
|
||||
|
||||
Wenn Sie in ihrer Funktion Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert.
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!../../../docs_src/query_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
Query-Parameter (Deutsch: Abfrage-Parameter) sind die Schlüssel-Wert-Paare, die nach dem `?` in einer URL aufgelistet sind, getrennt durch `&`-Zeichen.
|
||||
|
||||
Zum Beispiel sind in der URL:
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/?skip=0&limit=10
|
||||
```
|
||||
|
||||
... die Query-Parameter:
|
||||
|
||||
* `skip`: mit dem Wert `0`
|
||||
* `limit`: mit dem Wert `10`
|
||||
|
||||
Da sie Teil der URL sind, sind sie „naturgemäß“ Strings.
|
||||
|
||||
Aber wenn Sie sie mit Python-Typen deklarieren (im obigen Beispiel als `int`), werden sie zu diesem Typ konvertiert, und gegen diesen validiert.
|
||||
|
||||
Die gleichen Prozesse, die für Pfad-Parameter stattfinden, werden auch auf Query-Parameter angewendet:
|
||||
|
||||
* Editor Unterstützung (natürlich)
|
||||
* <abbr title="Konvertieren des Strings, der von einer HTTP-Anfrage kommt, in Python-Daten">„Parsen“</abbr> der Daten
|
||||
* Datenvalidierung
|
||||
* Automatische Dokumentation
|
||||
|
||||
## Defaultwerte
|
||||
|
||||
Da Query-Parameter nicht ein festgelegter Teil des Pfades sind, können sie optional sein und Defaultwerte haben.
|
||||
|
||||
Im obigen Beispiel haben sie die Defaultwerte `skip=0` und `limit=10`.
|
||||
|
||||
Wenn Sie also zur URL:
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/
|
||||
```
|
||||
|
||||
gehen, so ist das das gleiche wie die URL:
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/?skip=0&limit=10
|
||||
```
|
||||
|
||||
Aber wenn Sie zum Beispiel zu:
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/?skip=20
|
||||
```
|
||||
|
||||
gehen, werden die Parameter-Werte Ihrer Funktion sein:
|
||||
|
||||
* `skip=20`: da Sie das in der URL gesetzt haben
|
||||
* `limit=10`: weil das der Defaultwert ist
|
||||
|
||||
## Optionale Parameter
|
||||
|
||||
Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein.
|
||||
|
||||
!!! check
|
||||
Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein.
|
||||
|
||||
## Query-Parameter Typkonvertierung
|
||||
|
||||
Sie können auch `bool`-Typen deklarieren und sie werden konvertiert:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!> ../../../docs_src/query_params/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!> ../../../docs_src/query_params/tutorial003.py!}
|
||||
```
|
||||
|
||||
Wenn Sie nun zu:
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/foo?short=1
|
||||
```
|
||||
|
||||
oder
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/foo?short=True
|
||||
```
|
||||
|
||||
oder
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/foo?short=true
|
||||
```
|
||||
|
||||
oder
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/foo?short=on
|
||||
```
|
||||
|
||||
oder
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/foo?short=yes
|
||||
```
|
||||
|
||||
gehen, oder zu irgendeiner anderen Variante der Groß-/Kleinschreibung (Alles groß, Anfangsbuchstabe groß, usw.), dann wird Ihre Funktion den Parameter `short` mit dem `bool`-Wert `True` sehen, ansonsten mit dem Wert `False`.
|
||||
|
||||
## Mehrere Pfad- und Query-Parameter
|
||||
|
||||
Sie können mehrere Pfad-Parameter und Query-Parameter gleichzeitig deklarieren, **FastAPI** weiß, was welches ist.
|
||||
|
||||
Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren.
|
||||
|
||||
Parameter werden anhand ihres Namens erkannt:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="6 8"
|
||||
{!> ../../../docs_src/query_params/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="8 10"
|
||||
{!> ../../../docs_src/query_params/tutorial004.py!}
|
||||
```
|
||||
|
||||
## Erforderliche Query-Parameter
|
||||
|
||||
Wenn Sie einen Defaultwert für Nicht-Pfad-Parameter deklarieren (Bis jetzt haben wir nur Query-Parameter gesehen), dann ist der Parameter nicht erforderlich.
|
||||
|
||||
Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach optional sein soll, dann setzen Sie den Defaultwert auf `None`.
|
||||
|
||||
Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert:
|
||||
|
||||
```Python hl_lines="6-7"
|
||||
{!../../../docs_src/query_params/tutorial005.py!}
|
||||
```
|
||||
|
||||
Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`.
|
||||
|
||||
Wenn Sie in Ihrem Browser eine URL wie:
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/foo-item
|
||||
```
|
||||
|
||||
... öffnen, ohne den benötigten Parameter `needy`, dann erhalten Sie einen Fehler wie den folgenden:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"detail": [
|
||||
{
|
||||
"type": "missing",
|
||||
"loc": [
|
||||
"query",
|
||||
"needy"
|
||||
],
|
||||
"msg": "Field required",
|
||||
"input": null,
|
||||
"url": "https://errors.pydantic.dev/2.1/v/missing"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Da `needy` ein erforderlicher Parameter ist, müssen Sie ihn in der URL setzen:
|
||||
|
||||
```
|
||||
http://127.0.0.1:8000/items/foo-item?needy=sooooneedy
|
||||
```
|
||||
|
||||
... Das funktioniert:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"item_id": "foo-item",
|
||||
"needy": "sooooneedy"
|
||||
}
|
||||
```
|
||||
|
||||
Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren:
|
||||
|
||||
=== "Python 3.10+"
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!> ../../../docs_src/query_params/tutorial006_py310.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!> ../../../docs_src/query_params/tutorial006.py!}
|
||||
```
|
||||
|
||||
In diesem Fall gibt es drei Query-Parameter:
|
||||
|
||||
* `needy`, ein erforderlicher `str`.
|
||||
* `skip`, ein `int` mit einem Defaultwert `0`.
|
||||
* `limit`, ein optionales `int`.
|
||||
|
||||
!!! tip "Tipp"
|
||||
Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}.
|
||||
@@ -56,7 +56,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
|
||||
|
||||
🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔:
|
||||
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -93,7 +93,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
|
||||
|
||||
✋️ 👆 🈸, 💂♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁.
|
||||
|
||||
```Python hl_lines="153"
|
||||
```Python hl_lines="155"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -118,7 +118,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀.
|
||||
|
||||
👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚.
|
||||
|
||||
```Python hl_lines="4 139 166"
|
||||
```Python hl_lines="4 139 168"
|
||||
{!../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@
|
||||
|
||||
👆 🗄 ⚫️ & ✍ "👐" 🎏 🌌 👆 🔜 ⏮️ 🎓 `FastAPI`:
|
||||
|
||||
```Python hl_lines="1 3"
|
||||
```Python hl_lines="1 3" title="app/routers/users.py"
|
||||
{!../../../docs_src/bigger_applications/app/routers/users.py!}
|
||||
```
|
||||
|
||||
@@ -89,7 +89,7 @@
|
||||
|
||||
⚙️ ⚫️ 🎏 🌌 👆 🔜 ⚙️ `FastAPI` 🎓:
|
||||
|
||||
```Python hl_lines="6 11 16"
|
||||
```Python hl_lines="6 11 16" title="app/routers/users.py"
|
||||
{!../../../docs_src/bigger_applications/app/routers/users.py!}
|
||||
```
|
||||
|
||||
@@ -112,7 +112,7 @@
|
||||
|
||||
👥 🔜 🔜 ⚙️ 🙅 🔗 ✍ 🛃 `X-Token` 🎚:
|
||||
|
||||
```Python hl_lines="1 4-6"
|
||||
```Python hl_lines="1 4-6" title="app/dependencies.py"
|
||||
{!../../../docs_src/bigger_applications/app/dependencies.py!}
|
||||
```
|
||||
|
||||
@@ -143,7 +143,7 @@
|
||||
|
||||
, ↩️ ❎ 🌐 👈 🔠 *➡ 🛠️*, 👥 💪 🚮 ⚫️ `APIRouter`.
|
||||
|
||||
```Python hl_lines="5-10 16 21"
|
||||
```Python hl_lines="5-10 16 21" title="app/routers/items.py"
|
||||
{!../../../docs_src/bigger_applications/app/routers/items.py!}
|
||||
```
|
||||
|
||||
@@ -195,7 +195,7 @@ async def read_item(item_id: str):
|
||||
|
||||
👥 ⚙️ ⚖ 🗄 ⏮️ `..` 🔗:
|
||||
|
||||
```Python hl_lines="3"
|
||||
```Python hl_lines="3" title="app/routers/items.py"
|
||||
{!../../../docs_src/bigger_applications/app/routers/items.py!}
|
||||
```
|
||||
|
||||
@@ -265,7 +265,7 @@ that 🔜 ⛓:
|
||||
|
||||
✋️ 👥 💪 🚮 _🌅_ `tags` 👈 🔜 ✔ 🎯 *➡ 🛠️*, & ➕ `responses` 🎯 👈 *➡ 🛠️*:
|
||||
|
||||
```Python hl_lines="30-31"
|
||||
```Python hl_lines="30-31" title="app/routers/items.py"
|
||||
{!../../../docs_src/bigger_applications/app/routers/items.py!}
|
||||
```
|
||||
|
||||
@@ -290,7 +290,7 @@ that 🔜 ⛓:
|
||||
|
||||
& 👥 💪 📣 [🌐 🔗](dependencies/global-dependencies.md){.internal-link target=_blank} 👈 🔜 🌀 ⏮️ 🔗 🔠 `APIRouter`:
|
||||
|
||||
```Python hl_lines="1 3 7"
|
||||
```Python hl_lines="1 3 7" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
@@ -298,7 +298,7 @@ that 🔜 ⛓:
|
||||
|
||||
🔜 👥 🗄 🎏 🔁 👈 ✔️ `APIRouter`Ⓜ:
|
||||
|
||||
```Python hl_lines="5"
|
||||
```Python hl_lines="5" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
@@ -360,7 +360,7 @@ from .routers.users import router
|
||||
|
||||
, 💪 ⚙️ 👯♂️ 👫 🎏 📁, 👥 🗄 🔁 🔗:
|
||||
|
||||
```Python hl_lines="4"
|
||||
```Python hl_lines="5" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
@@ -368,7 +368,7 @@ from .routers.users import router
|
||||
|
||||
🔜, ➡️ 🔌 `router`Ⓜ ⚪️➡️ 🔁 `users` & `items`:
|
||||
|
||||
```Python hl_lines="10-11"
|
||||
```Python hl_lines="10-11" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
@@ -401,7 +401,7 @@ from .routers.users import router
|
||||
|
||||
👉 🖼 ⚫️ 🔜 💎 🙅. ✋️ ➡️ 💬 👈 ↩️ ⚫️ 💰 ⏮️ 🎏 🏗 🏢, 👥 🚫🔜 🔀 ⚫️ & 🚮 `prefix`, `dependencies`, `tags`, ♒️. 🔗 `APIRouter`:
|
||||
|
||||
```Python hl_lines="3"
|
||||
```Python hl_lines="3" title="app/internal/admin.py"
|
||||
{!../../../docs_src/bigger_applications/app/internal/admin.py!}
|
||||
```
|
||||
|
||||
@@ -409,7 +409,7 @@ from .routers.users import router
|
||||
|
||||
👥 💪 📣 🌐 👈 🍵 ✔️ 🔀 ⏮️ `APIRouter` 🚶♀️ 👈 🔢 `app.include_router()`:
|
||||
|
||||
```Python hl_lines="14-17"
|
||||
```Python hl_lines="14-17" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
@@ -432,7 +432,7 @@ from .routers.users import router
|
||||
|
||||
📥 👥 ⚫️... 🎦 👈 👥 💪 🤷:
|
||||
|
||||
```Python hl_lines="21-23"
|
||||
```Python hl_lines="21-23" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
|
||||
@@ -192,13 +192,13 @@ $ openssl rand -hex 32
|
||||
|
||||
=== "🐍 3️⃣.6️⃣ & 🔛"
|
||||
|
||||
```Python hl_lines="115-128"
|
||||
```Python hl_lines="115-130"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
=== "🐍 3️⃣.1️⃣0️⃣ & 🔛"
|
||||
|
||||
```Python hl_lines="114-127"
|
||||
```Python hl_lines="114-129"
|
||||
{!> ../../../docs_src/security/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
|
||||
@@ -501,7 +501,7 @@ current_user.items
|
||||
|
||||
"🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️.
|
||||
|
||||
👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/alembic/" class="external-link" target="_blank"> `alembic` 📁 ℹ 📟</a>.
|
||||
👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/" class="external-link" target="_blank"> `alembic` 📁 ℹ 📟</a>.
|
||||
|
||||
### ✍ 🔗
|
||||
|
||||
|
||||
@@ -1,5 +1,21 @@
|
||||
Articles:
|
||||
English:
|
||||
- author: Jessica Temporal
|
||||
author_link: https://jtemporal.com/socials
|
||||
link: https://jtemporal.com/tips-on-migrating-from-flask-to-fastapi-and-vice-versa/
|
||||
title: Tips on migrating from Flask to FastAPI and vice-versa
|
||||
- author: Ankit Anchlia
|
||||
author_link: https://linkedin.com/in/aanchlia21
|
||||
link: https://hackernoon.com/explore-how-to-effectively-use-jwt-with-fastapi
|
||||
title: Explore How to Effectively Use JWT With FastAPI
|
||||
- author: Nicoló Lino
|
||||
author_link: https://www.nlino.com
|
||||
link: https://github.com/softwarebloat/python-tracing-demo
|
||||
title: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo
|
||||
- author: Mikhail Rozhkov, Elena Samuylova
|
||||
author_link: https://www.linkedin.com/in/mnrozhkov/
|
||||
link: https://www.evidentlyai.com/blog/fastapi-tutorial
|
||||
title: ML serving and monitoring with FastAPI and Evidently
|
||||
- author: Visual Studio Code Team
|
||||
author_link: https://code.visualstudio.com/
|
||||
link: https://code.visualstudio.com/docs/python/tutorial-fastapi
|
||||
@@ -28,10 +44,6 @@ Articles:
|
||||
author_link: https://dev.to/
|
||||
link: https://dev.to/teresafds/authorization-on-fastapi-with-casbin-41og
|
||||
title: Authorization on FastAPI with Casbin
|
||||
- author: WayScript
|
||||
author_link: https://www.wayscript.com
|
||||
link: https://blog.wayscript.com/fast-api-quickstart/
|
||||
title: Quickstart Guide to Build and Host Responsive APIs with Fast API and WayScript
|
||||
- author: New Relic
|
||||
author_link: https://newrelic.com
|
||||
link: https://newrelic.com/instant-observability/fastapi/e559ec64-f765-4470-a15f-1901fcebb468
|
||||
@@ -84,10 +96,6 @@ Articles:
|
||||
author_link: https://dev.to/factorlive
|
||||
link: https://dev.to/factorlive/python-facebook-messenger-webhook-with-fastapi-on-glitch-4n90
|
||||
title: Python Facebook messenger webhook with FastAPI on Glitch
|
||||
- author: Dom Patmore
|
||||
author_link: https://twitter.com/dompatmore
|
||||
link: https://dompatmore.com/blog/authenticate-your-fastapi-app-with-auth0
|
||||
title: Authenticate Your FastAPI App with auth0
|
||||
- author: Valon Januzaj
|
||||
author_link: https://www.linkedin.com/in/valon-januzaj-b02692187/
|
||||
link: https://valonjanuzaj.medium.com/deploy-a-dockerized-fastapi-application-to-aws-cc757830ba1b
|
||||
@@ -100,10 +108,6 @@ Articles:
|
||||
author_link: https://twitter.com/louis_guitton
|
||||
link: https://guitton.co/posts/fastapi-monitoring/
|
||||
title: How to monitor your FastAPI service
|
||||
- author: Julien Harbulot
|
||||
author_link: https://julienharbulot.com/
|
||||
link: https://julienharbulot.com/notification-server.html
|
||||
title: HTTP server to display desktop notifications
|
||||
- author: Precious Ndubueze
|
||||
author_link: https://medium.com/@gabbyprecious2000
|
||||
link: https://medium.com/@gabbyprecious2000/creating-a-crud-app-with-fastapi-part-one-7c049292ad37
|
||||
@@ -152,18 +156,10 @@ Articles:
|
||||
author_link: https://wuilly.com/
|
||||
link: https://wuilly.com/2019/10/real-time-notifications-with-python-and-postgres/
|
||||
title: Real-time Notifications with Python and Postgres
|
||||
- author: Benjamin Ramser
|
||||
author_link: https://iwpnd.pw
|
||||
link: https://iwpnd.pw/articles/2020-03/apache-kafka-fastapi-geostream
|
||||
title: Apache Kafka producer and consumer with FastAPI and aiokafka
|
||||
- author: Navule Pavan Kumar Rao
|
||||
author_link: https://www.linkedin.com/in/navule/
|
||||
link: https://www.tutlinks.com/create-and-deploy-fastapi-app-to-heroku/
|
||||
title: Create and Deploy FastAPI app to Heroku without using Docker
|
||||
- author: Benjamin Ramser
|
||||
author_link: https://iwpnd.pw
|
||||
link: https://iwpnd.pw/articles/2020-01/deploy-fastapi-to-aws-lambda
|
||||
title: How to continuously deploy a FastAPI to AWS Lambda with AWS SAM
|
||||
- author: Arthur Henrique
|
||||
author_link: https://twitter.com/arthurheinrique
|
||||
link: https://medium.com/@arthur393/another-boilerplate-to-fastapi-azure-pipeline-ci-pytest-3c8d9a4be0bb
|
||||
@@ -188,10 +184,6 @@ Articles:
|
||||
author_link: https://dev.to/dbanty
|
||||
link: https://dev.to/dbanty/why-i-m-leaving-flask-3ki6
|
||||
title: Why I'm Leaving Flask
|
||||
- author: Rob Wagner
|
||||
author_link: https://robwagner.dev/
|
||||
link: https://robwagner.dev/tortoise-fastapi-setup/
|
||||
title: Setting up Tortoise ORM with FastAPI
|
||||
- author: Mike Moritz
|
||||
author_link: https://medium.com/@mike.p.moritz
|
||||
link: https://medium.com/@mike.p.moritz/using-docker-compose-to-deploy-a-lightweight-python-rest-api-with-a-job-queue-37e6072a209b
|
||||
@@ -314,6 +306,11 @@ Articles:
|
||||
author_link: https://qiita.com/mtitg
|
||||
link: https://qiita.com/mtitg/items/47770e9a562dd150631d
|
||||
title: FastAPI|DB接続してCRUDするPython製APIサーバーを構築
|
||||
Portuguese:
|
||||
- author: Jessica Temporal
|
||||
author_link: https://jtemporal.com/socials
|
||||
link: https://jtemporal.com/dicas-para-migrar-de-flask-para-fastapi-e-vice-versa/
|
||||
title: Dicas para migrar uma aplicação de Flask para FastAPI e vice-versa
|
||||
Russian:
|
||||
- author: Troy Köhler
|
||||
author_link: https://www.linkedin.com/in/trkohler/
|
||||
@@ -349,6 +346,10 @@ Podcasts:
|
||||
title: FastAPI on PythonBytes
|
||||
Talks:
|
||||
English:
|
||||
- author: Jeny Sadadia
|
||||
author_link: https://github.com/JenySadadia
|
||||
link: https://www.youtube.com/watch?v=uZdTe8_Z6BQ
|
||||
title: 'PyCon AU 2023: Testing asynchronous applications with FastAPI and pytest'
|
||||
- author: Sebastián Ramírez (tiangolo)
|
||||
author_link: https://twitter.com/tiangolo
|
||||
link: https://www.youtube.com/watch?v=PnpTY1f4k2U
|
||||
|
||||
@@ -28,7 +28,7 @@ For example, to declare another response with a status code `404` and a Pydantic
|
||||
```
|
||||
|
||||
!!! note
|
||||
Have in mind that you have to return the `JSONResponse` directly.
|
||||
Keep in mind that you have to return the `JSONResponse` directly.
|
||||
|
||||
!!! info
|
||||
The `model` key is not part of OpenAPI.
|
||||
|
||||
@@ -85,7 +85,7 @@ response = client.get('/')
|
||||
Note that we're using async/await with the new `AsyncClient` - the request is asynchronous.
|
||||
|
||||
!!! warning
|
||||
If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from <a href="florimondmanca/asgi-lifespan" class="external-link" target="_blank">https://github.com/florimondmanca/asgi-lifespan#usage</a>.
|
||||
If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from <a href="https://github.com/florimondmanca/asgi-lifespan#usage" class="external-link" target="_blank">florimondmanca/asgi-lifespan</a>.
|
||||
|
||||
## Other Asynchronous Function Calls
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--r
|
||||
|
||||
### About `root_path`
|
||||
|
||||
Have in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app.
|
||||
Keep in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app.
|
||||
|
||||
But if you go with your browser to <a href="http://127.0.0.1:8000" class="external-link" target="_blank">http://127.0.0.1:8000/app</a> you will see the normal response:
|
||||
|
||||
@@ -142,7 +142,7 @@ Uvicorn will expect the proxy to access Uvicorn at `http://127.0.0.1:8000/app`,
|
||||
|
||||
## About proxies with a stripped path prefix
|
||||
|
||||
Have in mind that a proxy with stripped path prefix is only one of the ways to configure it.
|
||||
Keep in mind that a proxy with stripped path prefix is only one of the ways to configure it.
|
||||
|
||||
Probably in many cases the default will be that the proxy doesn't have a stripped path prefix.
|
||||
|
||||
|
||||
@@ -101,7 +101,7 @@ But as you passed the `HTMLResponse` in the `response_class` too, **FastAPI** wi
|
||||
|
||||
Here are some of the available responses.
|
||||
|
||||
Have in mind that you can use `Response` to return anything else, or even create a custom sub-class.
|
||||
Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class.
|
||||
|
||||
!!! note "Technical Details"
|
||||
You could also use `from starlette.responses import HTMLResponse`.
|
||||
|
||||
@@ -21,7 +21,7 @@ And of course, it supports the same:
|
||||
This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic.
|
||||
|
||||
!!! info
|
||||
Have in mind that dataclasses can't do everything Pydantic models can do.
|
||||
Keep in mind that dataclasses can't do everything Pydantic models can do.
|
||||
|
||||
So, you might still need to use Pydantic models.
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ The `lifespan` parameter of the `FastAPI` app takes an **async context manager**
|
||||
## Alternative Events (deprecated)
|
||||
|
||||
!!! warning
|
||||
The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above.
|
||||
The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both.
|
||||
|
||||
You can probably skip this part.
|
||||
|
||||
@@ -159,4 +159,4 @@ Underneath, in the ASGI technical specification, this is part of the <a href="ht
|
||||
|
||||
## Sub Applications
|
||||
|
||||
🚨 Have in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}.
|
||||
🚨 Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}.
|
||||
|
||||
@@ -163,7 +163,7 @@ For example, in this application we don't use FastAPI's integrated functionality
|
||||
```
|
||||
|
||||
!!! info
|
||||
In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_schema_json()`.
|
||||
In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`.
|
||||
|
||||
Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML.
|
||||
|
||||
|
||||
@@ -30,4 +30,4 @@ And if you declared a `response_model`, it will still be used to filter and conv
|
||||
|
||||
**FastAPI** will use that *temporal* response to extract the status code (also cookies and headers), and will put them in the final response that contains the value you returned, filtered by any `response_model`.
|
||||
|
||||
You can also declare the `Response` parameter in dependencies, and set the status code in them. But have in mind that the last one to be set will win.
|
||||
You can also declare the `Response` parameter in dependencies, and set the status code in them. But keep in mind that the last one to be set will win.
|
||||
|
||||
@@ -31,7 +31,7 @@ Then set Cookies in it, and then return it:
|
||||
```
|
||||
|
||||
!!! tip
|
||||
Have in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
|
||||
Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly.
|
||||
|
||||
So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`.
|
||||
|
||||
|
||||
@@ -37,6 +37,6 @@ Create a response as described in [Return a Response Directly](response-directly
|
||||
|
||||
## Custom Headers
|
||||
|
||||
Have in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>.
|
||||
Keep in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>.
|
||||
|
||||
But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations (read more in [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), using the parameter `expose_headers` documented in <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>.
|
||||
|
||||
@@ -79,7 +79,7 @@ First, let's quickly see the parts that change from the examples in the main **T
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 152"
|
||||
```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -88,7 +88,7 @@ First, let's quickly see the parts that change from the examples in the main **T
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -97,7 +97,7 @@ First, let's quickly see the parts that change from the examples in the main **T
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153"
|
||||
```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -199,7 +199,7 @@ And we return the scopes as part of the JWT token.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="152"
|
||||
```Python hl_lines="154"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -208,7 +208,7 @@ And we return the scopes as part of the JWT token.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="153"
|
||||
```Python hl_lines="155"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -217,7 +217,7 @@ And we return the scopes as part of the JWT token.
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="153"
|
||||
```Python hl_lines="155"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
@@ -265,7 +265,7 @@ In this case, it requires the scope `me` (it could require more than one scope).
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="3 138 165"
|
||||
```Python hl_lines="3 138 167"
|
||||
{!> ../../../docs_src/security/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
@@ -274,7 +274,7 @@ In this case, it requires the scope `me` (it could require more than one scope).
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="4 139 166"
|
||||
```Python hl_lines="4 139 168"
|
||||
{!> ../../../docs_src/security/tutorial005_py39.py!}
|
||||
```
|
||||
|
||||
@@ -283,7 +283,7 @@ In this case, it requires the scope `me` (it could require more than one scope).
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="4 139 166"
|
||||
```Python hl_lines="4 139 168"
|
||||
{!> ../../../docs_src/security/tutorial005.py!}
|
||||
```
|
||||
|
||||
|
||||
@@ -46,21 +46,61 @@ $ pip install jinja2
|
||||
|
||||
## Writing templates
|
||||
|
||||
Then you can write a template at `templates/item.html` with:
|
||||
Then you can write a template at `templates/item.html` with, for example:
|
||||
|
||||
```jinja hl_lines="7"
|
||||
{!../../../docs_src/templates/templates/item.html!}
|
||||
```
|
||||
|
||||
It will show the `id` taken from the "context" `dict` you passed:
|
||||
### Template Context Values
|
||||
|
||||
In the HTML that contains:
|
||||
|
||||
{% raw %}
|
||||
|
||||
```jinja
|
||||
Item ID: {{ id }}
|
||||
```
|
||||
|
||||
{% endraw %}
|
||||
|
||||
...it will show the `id` taken from the "context" `dict` you passed:
|
||||
|
||||
```Python
|
||||
{"request": request, "id": id}
|
||||
{"id": id}
|
||||
```
|
||||
|
||||
For example, with an ID of `42`, this would render:
|
||||
|
||||
```html
|
||||
Item ID: 42
|
||||
```
|
||||
|
||||
### Template `url_for` Arguments
|
||||
|
||||
You can also use `url_for()` inside of the template, it takes as arguments the same arguments that would be used by your *path operation function*.
|
||||
|
||||
So, the section with:
|
||||
|
||||
{% raw %}
|
||||
|
||||
```jinja
|
||||
<a href="{{ url_for('read_item', id=id) }}">
|
||||
```
|
||||
|
||||
{% endraw %}
|
||||
|
||||
...will generate a link to the same URL that would be handled by the *path operation function* `read_item(id=id)`.
|
||||
|
||||
For example, with an ID of `42`, this would render:
|
||||
|
||||
```html
|
||||
<a href="/items/42">
|
||||
```
|
||||
|
||||
## Templates and static files
|
||||
|
||||
You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted.
|
||||
You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`.
|
||||
|
||||
```jinja hl_lines="4"
|
||||
{!../../../docs_src/templates/templates/item.html!}
|
||||
|
||||
@@ -212,7 +212,7 @@ Client #1596980209979 left the chat
|
||||
!!! tip
|
||||
The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections.
|
||||
|
||||
But have in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process.
|
||||
But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process.
|
||||
|
||||
If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check <a href="https://github.com/encode/broadcaster" class="external-link" target="_blank">encode/broadcaster</a>.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
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). (*)
|
||||
|
||||
But when checking benchmarks and comparisons you should have the following in mind.
|
||||
But when checking benchmarks and comparisons you should keep the following in mind.
|
||||
|
||||
## Benchmarks and speed
|
||||
|
||||
|
||||
@@ -4,11 +4,11 @@ First, you might want to see the basic ways to [help FastAPI and get help](help-
|
||||
|
||||
## Developing
|
||||
|
||||
If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment.
|
||||
If you already cloned the <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">fastapi repository</a> and you want to deep dive in the code, here are some guidelines to set up your environment.
|
||||
|
||||
### Virtual environment with `venv`
|
||||
|
||||
You can create a virtual environment in a directory using Python's `venv` module:
|
||||
You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is):
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -18,7 +18,7 @@ $ python -m venv env
|
||||
|
||||
</div>
|
||||
|
||||
That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment.
|
||||
That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment.
|
||||
|
||||
### Activate the environment
|
||||
|
||||
@@ -84,7 +84,7 @@ To check it worked, use:
|
||||
|
||||
If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉
|
||||
|
||||
Make sure you have the latest pip version on your virtual environment to avoid errors on the next steps:
|
||||
Make sure you have the latest pip version on your local environment to avoid errors on the next steps:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@@ -101,7 +101,7 @@ $ python -m pip install --upgrade pip
|
||||
|
||||
This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally.
|
||||
|
||||
### pip
|
||||
### Install requirements using pip
|
||||
|
||||
After activating the environment as described above:
|
||||
|
||||
@@ -117,20 +117,20 @@ $ pip install -r requirements.txt
|
||||
|
||||
It will install all the dependencies and your local FastAPI in your local environment.
|
||||
|
||||
#### Using your local FastAPI
|
||||
### Using your local FastAPI
|
||||
|
||||
If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code.
|
||||
If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your cloned local FastAPI source code.
|
||||
|
||||
And if you update that local FastAPI source code when you run that Python file again, it will use the fresh version of FastAPI you just edited.
|
||||
|
||||
That way, you don't have to "install" your local version to be able to test every change.
|
||||
|
||||
!!! note "Technical Details"
|
||||
This only happens when you install using this included `requirements.txt` instead of installing `pip install fastapi` directly.
|
||||
This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly.
|
||||
|
||||
That is because inside of the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option.
|
||||
That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option.
|
||||
|
||||
### Format
|
||||
### Format the code
|
||||
|
||||
There is a script that you can run that will format and clean all your code:
|
||||
|
||||
@@ -227,15 +227,13 @@ And those Python files are included/injected in the documentation when generatin
|
||||
|
||||
Most of the tests actually run against the example source files in the documentation.
|
||||
|
||||
This helps making sure that:
|
||||
This helps to make sure that:
|
||||
|
||||
* The documentation is up to date.
|
||||
* The documentation is up-to-date.
|
||||
* The documentation examples can be run as is.
|
||||
* Most of the features are covered by the documentation, ensured by test coverage.
|
||||
|
||||
|
||||
|
||||
### Apps and docs at the same time
|
||||
#### Apps and docs at the same time
|
||||
|
||||
If you run the examples with, e.g.:
|
||||
|
||||
@@ -259,7 +257,9 @@ Here are the steps to help with translations.
|
||||
|
||||
#### Tips and guidelines
|
||||
|
||||
* Check the currently <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">existing pull requests</a> for your language and add reviews requesting changes or approving them.
|
||||
* Check the currently <a href="https://github.com/tiangolo/fastapi/pulls" class="external-link" target="_blank">existing pull requests</a> for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is <a href="https://github.com/tiangolo/fastapi/pulls?q=is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3Aawaiting-review" class="external-link" target="_blank">`lang-es`</a>.
|
||||
|
||||
* Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging.
|
||||
|
||||
!!! tip
|
||||
You can <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request" class="external-link" target="_blank">add comments with change suggestions</a> to existing pull requests.
|
||||
@@ -268,19 +268,9 @@ Here are the steps to help with translations.
|
||||
|
||||
* Check if there's a <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussion</a> to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion.
|
||||
|
||||
* Add a single pull request per page translated. That will make it much easier for others to review it.
|
||||
* If you translate pages, add a single pull request per page translated. That will make it much easier for others to review it.
|
||||
|
||||
For the languages I don't speak, I'll wait for several others to review the translation before merging.
|
||||
|
||||
* You can also check if there are translations for your language and add a review to them, that will help me know that the translation is correct and I can merge it.
|
||||
* You could check in the <a href="https://github.com/tiangolo/fastapi/discussions/categories/translations" class="external-link" target="_blank">GitHub Discussions</a> for your language.
|
||||
* Or you can filter the existing PRs by the ones with the label for your language, for example, for Spanish, the label is <a href="https://github.com/tiangolo/fastapi/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc+label%3Alang-es+label%3A%22awaiting+review%22" class="external-link" target="_blank">`lang-es`</a>.
|
||||
|
||||
* Use the same Python examples and only translate the text in the docs. You don't have to change anything for this to work.
|
||||
|
||||
* Use the same images, file names, and links. You don't have to change anything for it to work.
|
||||
|
||||
* To check the 2-letter code for the language you want to translate you can use the table <a href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes" class="external-link" target="_blank">List of ISO 639-1 codes</a>.
|
||||
* To check the 2-letter code for the language you want to translate, you can use the table <a href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes" class="external-link" target="_blank">List of ISO 639-1 codes</a>.
|
||||
|
||||
#### Existing language
|
||||
|
||||
@@ -323,7 +313,7 @@ $ python ./scripts/docs.py live es
|
||||
|
||||
Now you can go to <a href="http://127.0.0.1:8008" class="external-link" target="_blank">http://127.0.0.1:8008</a> and see your changes live.
|
||||
|
||||
You will see that every language has all the pages. But some pages are not translated and have a notification about the missing translation.
|
||||
You will see that every language has all the pages. But some pages are not translated and have an info box at the top, about the missing translation.
|
||||
|
||||
Now let's say that you want to add a translation for the section [Features](features.md){.internal-link target=_blank}.
|
||||
|
||||
@@ -342,7 +332,7 @@ docs/es/docs/features.md
|
||||
!!! tip
|
||||
Notice that the only change in the path and file name is the language code, from `en` to `es`.
|
||||
|
||||
If you go to your browser you will see that now the docs show your new section. 🎉
|
||||
If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉
|
||||
|
||||
Now you can translate it all and see how it looks as you save the file.
|
||||
|
||||
@@ -386,7 +376,7 @@ You can make the first pull request with those two files, `docs/ht/mkdocs.yml` a
|
||||
|
||||
#### Preview the result
|
||||
|
||||
You can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`).
|
||||
As already mentioned above, you can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`).
|
||||
|
||||
Once you are done, you can also test it all as it would look online, including all the other languages.
|
||||
|
||||
@@ -423,6 +413,25 @@ Serving at: http://127.0.0.1:8008
|
||||
|
||||
</div>
|
||||
|
||||
#### Translation specific tips and guidelines
|
||||
|
||||
* Translate only the Markdown documents (`.md`). Do not translate the code examples at `./docs_src`.
|
||||
|
||||
* In code blocks within the Markdown document, translate comments (`# a comment`), but leave the rest unchanged.
|
||||
|
||||
* Do not change anything enclosed in "``" (inline code).
|
||||
|
||||
* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged.
|
||||
|
||||
* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box.
|
||||
|
||||
* Do not change the paths in links to images, code files, Markdown documents.
|
||||
|
||||
* However, when a Markdown document is translated, the `#hash-parts` in links to its headings may change. Update these links if possible.
|
||||
* Search for such links in the translated document using the regex `#[^# ]`.
|
||||
* Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files".
|
||||
* When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents.
|
||||
|
||||
## Tests
|
||||
|
||||
There is a script that you can run locally to test all the code and generate coverage reports in HTML:
|
||||
|
||||
@@ -258,7 +258,7 @@ And you will have to make sure that it's a single process running those previous
|
||||
Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle.
|
||||
|
||||
!!! tip
|
||||
Also, have in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application.
|
||||
Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application.
|
||||
|
||||
In that case, you wouldn't have to worry about any of this. 🤷
|
||||
|
||||
@@ -297,7 +297,7 @@ You can use simple tools like `htop` to see the CPU and RAM used in your server
|
||||
|
||||
## Recap
|
||||
|
||||
You have been reading here some of the main concepts that you would probably need to have in mind when deciding how to deploy your application:
|
||||
You have been reading here some of the main concepts that you would probably need to keep in mind when deciding how to deploy your application:
|
||||
|
||||
* Security - HTTPS
|
||||
* Running on startup
|
||||
|
||||
@@ -9,7 +9,7 @@ But it is way more complex than that.
|
||||
|
||||
To **learn the basics of HTTPS**, from a consumer perspective, check <a href="https://howhttps.works/" class="external-link" target="_blank">https://howhttps.works/</a>.
|
||||
|
||||
Now, from a **developer's perspective**, here are several things to have in mind while thinking about HTTPS:
|
||||
Now, from a **developer's perspective**, here are several things to keep in mind while thinking about HTTPS:
|
||||
|
||||
* For HTTPS, **the server** needs to **have "certificates"** generated by a **third party**.
|
||||
* Those certificates are actually **acquired** from the third party, not "generated".
|
||||
|
||||
@@ -16,6 +16,6 @@ There are several ways to do it depending on your specific use case and the tool
|
||||
|
||||
You could **deploy a server** yourself using a combination of tools, you could use a **cloud service** that does part of the work for you, or other possible options.
|
||||
|
||||
I will show you some of the main concepts you should probably have in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application).
|
||||
I will show you some of the main concepts you should probably keep in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application).
|
||||
|
||||
You will see more details to have in mind and some of the techniques to do it in the next sections. ✨
|
||||
You will see more details to keep in mind and some of the techniques to do it in the next sections. ✨
|
||||
|
||||
@@ -10,11 +10,11 @@ There are 3 main alternatives:
|
||||
|
||||
## Server Machine and Server Program
|
||||
|
||||
There's a small detail about names to have in mind. 💡
|
||||
There's a small detail about names to keep in mind. 💡
|
||||
|
||||
The word "**server**" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn).
|
||||
|
||||
Just have that in mind when you read "server" in general, it could refer to one of those two things.
|
||||
Just keep in mind that when you read "server" in general, it could refer to one of those two things.
|
||||
|
||||
When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs.
|
||||
|
||||
|
||||
@@ -106,7 +106,7 @@ In many cases they will only copy a fragment of the code, but that's not enough
|
||||
|
||||
* You can ask them to provide a <a href="https://stackoverflow.com/help/minimal-reproducible-example" class="external-link" target="_blank">minimal, reproducible, example</a>, that you can **copy-paste** and run locally to see the same error or behavior they are seeing, or to understand their use case better.
|
||||
|
||||
* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just have in mind that this might take a lot of time and it might be better to ask them to clarify the problem first.
|
||||
* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just keep in mind that this might take a lot of time and it might be better to ask them to clarify the problem first.
|
||||
|
||||
### Suggest solutions
|
||||
|
||||
@@ -148,7 +148,7 @@ Again, please try your best to be kind. 🤗
|
||||
|
||||
---
|
||||
|
||||
Here's what to have in mind and how to review a pull request:
|
||||
Here's what to keep in mind and how to review a pull request:
|
||||
|
||||
### Understand the problem
|
||||
|
||||
@@ -233,7 +233,7 @@ Join the 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" targ
|
||||
|
||||
### Don't use the chat for questions
|
||||
|
||||
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.
|
||||
Keep 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.
|
||||
|
||||
In GitHub, the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the chat systems. 😅
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Async SQL (Relational) Databases with Encode/Databases
|
||||
# ~~Async SQL (Relational) Databases with Encode/Databases~~ (deprecated)
|
||||
|
||||
!!! info
|
||||
These docs are about to be updated. 🎉
|
||||
@@ -7,6 +7,9 @@
|
||||
|
||||
The new docs will include Pydantic v2 and will use <a href="https://sqlmodel.tiangolo.com/" class="external-link" target="_blank">SQLModel</a> once it is updated to use Pydantic v2 as well.
|
||||
|
||||
!!! warning "Deprecated"
|
||||
This tutorial is deprecated and will be removed in a future version.
|
||||
|
||||
You can also use <a href="https://github.com/encode/databases" class="external-link" target="_blank">`encode/databases`</a> with **FastAPI** to connect to databases using `async` and `await`.
|
||||
|
||||
It is compatible with:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# NoSQL (Distributed / Big Data) Databases with Couchbase
|
||||
# ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated)
|
||||
|
||||
!!! info
|
||||
These docs are about to be updated. 🎉
|
||||
@@ -7,6 +7,9 @@
|
||||
|
||||
The new docs will hopefully use Pydantic v2 and will use <a href="https://art049.github.io/odmantic/" class="external-link" target="_blank">ODMantic</a> with MongoDB.
|
||||
|
||||
!!! warning "Deprecated"
|
||||
This tutorial is deprecated and will be removed in a future version.
|
||||
|
||||
**FastAPI** can also be integrated with any <abbr title="Distributed database (Big Data), also 'Not Only SQL'">NoSQL</abbr>.
|
||||
|
||||
Here we'll see an example using **<a href="https://www.couchbase.com/" class="external-link" target="_blank">Couchbase</a>**, a <abbr title="Document here refers to a JSON object (a dict), with keys and values, and those values can also be other JSON objects, arrays (lists), numbers, strings, booleans, etc.">document</abbr> based NoSQL database.
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
# SQL (Relational) Databases with Peewee
|
||||
# ~~SQL (Relational) Databases with Peewee~~ (deprecated)
|
||||
|
||||
!!! warning "Deprecated"
|
||||
This tutorial is deprecated and will be removed in a future version.
|
||||
|
||||
!!! warning
|
||||
If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough.
|
||||
@@ -75,7 +78,7 @@ Let's first check all the normal Peewee code, create a Peewee database:
|
||||
```
|
||||
|
||||
!!! tip
|
||||
Have in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class.
|
||||
Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class.
|
||||
|
||||
#### Note
|
||||
|
||||
@@ -493,7 +496,7 @@ This means that, with Peewee's current implementation, multiple tasks could be u
|
||||
|
||||
Python 3.7 has <a href="https://docs.python.org/3/library/contextvars.html" class="external-link" target="_blank">`contextvars`</a> that can create a local variable very similar to `threading.local`, but also supporting these async features.
|
||||
|
||||
There are several things to have in mind.
|
||||
There are several things to keep in mind.
|
||||
|
||||
The `ContextVar` has to be created at the top of the module, like:
|
||||
|
||||
|
||||
@@ -7,6 +7,124 @@ hide:
|
||||
|
||||
## Latest Changes
|
||||
|
||||
* ✏️ Fix Pydantic method name in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#10826](https://github.com/tiangolo/fastapi/pull/10826) by [@ahmedabdou14](https://github.com/ahmedabdou14).
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Include HTTP 205 in status codes with no body. PR [#10969](https://github.com/tiangolo/fastapi/pull/10969) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Refactors
|
||||
|
||||
* ✅ Refactor tests for duplicate operation ID generation for compatibility with other tools running the FastAPI test suite. PR [#10876](https://github.com/tiangolo/fastapi/pull/10876) by [@emmettbutler](https://github.com/emmettbutler).
|
||||
* ♻️ Simplify string format with f-strings in `fastapi/utils.py`. PR [#10576](https://github.com/tiangolo/fastapi/pull/10576) by [@eukub](https://github.com/eukub).
|
||||
* 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek).
|
||||
* ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm).
|
||||
|
||||
### Docs
|
||||
|
||||
* 📝 Add External Link: Tips on migrating from Flask to FastAPI and vice-versa. PR [#11029](https://github.com/tiangolo/fastapi/pull/11029) by [@jtemporal](https://github.com/jtemporal).
|
||||
* 📝 Deprecate old tutorials: Peewee, Couchbase, encode/databases. PR [#10979](https://github.com/tiangolo/fastapi/pull/10979) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✏️ Fix typo in `fastapi/security/oauth2.py`. PR [#10972](https://github.com/tiangolo/fastapi/pull/10972) by [@RafalSkolasinski](https://github.com/RafalSkolasinski).
|
||||
* 📝 Update `HTTPException` details in `docs/en/docs/tutorial/handling-errors.md`. PR [#5418](https://github.com/tiangolo/fastapi/pull/5418) by [@papb](https://github.com/papb).
|
||||
* ✏️ A few tweaks in `docs/de/docs/tutorial/first-steps.md`. PR [#10959](https://github.com/tiangolo/fastapi/pull/10959) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* ✏️ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* ✏️ Fix typos for Spanish documentation. PR [#10957](https://github.com/tiangolo/fastapi/pull/10957) by [@jlopezlira](https://github.com/jlopezlira).
|
||||
* 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo).
|
||||
* ✏️ Fix broken link in `docs/tutorial/sql-databases.md` in several languages. PR [#10716](https://github.com/tiangolo/fastapi/pull/10716) by [@theoohoho](https://github.com/theoohoho).
|
||||
* ✏️ Remove broken links from `external_links.yml`. PR [#10943](https://github.com/tiangolo/fastapi/pull/10943) by [@Torabek](https://github.com/Torabek).
|
||||
* 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin).
|
||||
* 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski).
|
||||
* ✏️ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb).
|
||||
* 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia).
|
||||
* 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse).
|
||||
* 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat).
|
||||
* 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov).
|
||||
* 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious).
|
||||
* 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia).
|
||||
* 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
|
||||
### Translations
|
||||
|
||||
* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/schema-extra-example.md`. PR [#4065](https://github.com/tiangolo/fastapi/pull/4065) by [@luccasmmg](https://github.com/luccasmmg).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/history-design-future.md`. PR [#11012](https://github.com/tiangolo/fastapi/pull/11012) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/resources/index.md`. PR [#11020](https://github.com/tiangolo/fastapi/pull/11020) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/how-to/index.md`. PR [#11021](https://github.com/tiangolo/fastapi/pull/11021) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add German translation for `docs/de/docs/tutorial/query-params.md`. PR [#10293](https://github.com/tiangolo/fastapi/pull/10293) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* 🌐 Add German translation for `docs/de/docs/benchmarks.md`. PR [#10866](https://github.com/tiangolo/fastapi/pull/10866) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/learn/index.md`. PR [#11014](https://github.com/tiangolo/fastapi/pull/11014) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Persian translation for `docs/fa/docs/tutorial/security/index.md`. PR [#9945](https://github.com/tiangolo/fastapi/pull/9945) by [@mojtabapaso](https://github.com/mojtabapaso).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/help/index.md`. PR [#11013](https://github.com/tiangolo/fastapi/pull/11013) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/about/index.md`. PR [#11006](https://github.com/tiangolo/fastapi/pull/11006) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Update Turkish translation for `docs/tr/docs/benchmarks.md`. PR [#11005](https://github.com/tiangolo/fastapi/pull/11005) by [@hasansezertasan](https://github.com/hasansezertasan).
|
||||
* 🌐 Add Italian translation for `docs/it/docs/index.md`. PR [#5233](https://github.com/tiangolo/fastapi/pull/5233) by [@matteospanio](https://github.com/matteospanio).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/help/index.md`. PR [#10983](https://github.com/tiangolo/fastapi/pull/10983) by [@KaniKim](https://github.com/KaniKim).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/features.md`. PR [#10976](https://github.com/tiangolo/fastapi/pull/10976) by [@KaniKim](https://github.com/KaniKim).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/get-current-user.md`. PR [#5737](https://github.com/tiangolo/fastapi/pull/5737) by [@KdHyeon0661](https://github.com/KdHyeon0661).
|
||||
* 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/first-steps.md`. PR [#10541](https://github.com/tiangolo/fastapi/pull/10541) by [@AlertRED](https://github.com/AlertRED).
|
||||
* 🌐 Add Russian translation for `docs/ru/docs/tutorial/handling-errors.md`. PR [#10375](https://github.com/tiangolo/fastapi/pull/10375) by [@AlertRED](https://github.com/AlertRED).
|
||||
* 🌐 Add Russian translation for `docs/ru/docs/tutorial/encoder.md`. PR [#10374](https://github.com/tiangolo/fastapi/pull/10374) by [@AlertRED](https://github.com/AlertRED).
|
||||
* 🌐 Add Russian translation for `docs/ru/docs/tutorial/body-updates.md`. PR [#10373](https://github.com/tiangolo/fastapi/pull/10373) by [@AlertRED](https://github.com/AlertRED).
|
||||
* 🌐 Russian translation: updated `fastapi-people.md`.. PR [#10255](https://github.com/tiangolo/fastapi/pull/10255) by [@NiKuma0](https://github.com/NiKuma0).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/security/index.md`. PR [#5798](https://github.com/tiangolo/fastapi/pull/5798) by [@3w36zj6](https://github.com/3w36zj6).
|
||||
* 🌐 Add German translation for `docs/de/docs/advanced/generate-clients.md`. PR [#10725](https://github.com/tiangolo/fastapi/pull/10725) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* 🌐 Add German translation for `docs/de/docs/advanced/openapi-webhooks.md`. PR [#10712](https://github.com/tiangolo/fastapi/pull/10712) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* 🌐 Add German translation for `docs/de/docs/advanced/custom-response.md`. PR [#10624](https://github.com/tiangolo/fastapi/pull/10624) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* 🌐 Add German translation for `docs/de/docs/advanced/additional-status-codes.md`. PR [#10617](https://github.com/tiangolo/fastapi/pull/10617) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* 🌐 Add German translation for `docs/de/docs/tutorial/middleware.md`. PR [#10391](https://github.com/tiangolo/fastapi/pull/10391) by [@JohannesJungbluth](https://github.com/JohannesJungbluth).
|
||||
* 🌐 Add German translation for introduction documents. PR [#10497](https://github.com/tiangolo/fastapi/pull/10497) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/encoder.md`. PR [#1955](https://github.com/tiangolo/fastapi/pull/1955) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-data-types.md`. PR [#1932](https://github.com/tiangolo/fastapi/pull/1932) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/async.md`. PR [#5191](https://github.com/tiangolo/fastapi/pull/5191) by [@BilalAlpaslan](https://github.com/BilalAlpaslan).
|
||||
* 🌐 Add Turkish translation for `docs/tr/docs/project-generation.md`. PR [#5192](https://github.com/tiangolo/fastapi/pull/5192) by [@BilalAlpaslan](https://github.com/BilalAlpaslan).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/deployment/docker.md`. PR [#5657](https://github.com/tiangolo/fastapi/pull/5657) by [@nearnear](https://github.com/nearnear).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/deployment/server-workers.md`. PR [#4935](https://github.com/tiangolo/fastapi/pull/4935) by [@jujumilk3](https://github.com/jujumilk3).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/deployment/index.md`. PR [#4561](https://github.com/tiangolo/fastapi/pull/4561) by [@jujumilk3](https://github.com/jujumilk3).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/tutorial/path-operation-configuration.md`. PR [#3639](https://github.com/tiangolo/fastapi/pull/3639) by [@jungsu-kwon](https://github.com/jungsu-kwon).
|
||||
* 🌐 Modify the description of `zh` - Traditional Chinese. PR [#10889](https://github.com/tiangolo/fastapi/pull/10889) by [@cherinyy](https://github.com/cherinyy).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/tutorial/static-files.md`. PR [#2957](https://github.com/tiangolo/fastapi/pull/2957) by [@jeesang7](https://github.com/jeesang7).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/tutorial/response-model.md`. PR [#2766](https://github.com/tiangolo/fastapi/pull/2766) by [@hard-coders](https://github.com/hard-coders).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/tutorial/body-multiple-params.md`. PR [#2461](https://github.com/tiangolo/fastapi/pull/2461) by [@PandaHun](https://github.com/PandaHun).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/tutorial/query-params-str-validations.md`. PR [#2415](https://github.com/tiangolo/fastapi/pull/2415) by [@hard-coders](https://github.com/hard-coders).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/python-types.md`. PR [#2267](https://github.com/tiangolo/fastapi/pull/2267) by [@jrim](https://github.com/jrim).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/tutorial/body-nested-models.md`. PR [#2506](https://github.com/tiangolo/fastapi/pull/2506) by [@hard-coders](https://github.com/hard-coders).
|
||||
* 🌐 Add Korean translation for `docs/ko/docs/learn/index.md`. PR [#10977](https://github.com/tiangolo/fastapi/pull/10977) by [@KaniKim](https://github.com/KaniKim).
|
||||
* 🌐 Initialize translations for Traditional Chinese. PR [#10505](https://github.com/tiangolo/fastapi/pull/10505) by [@hsuanchi](https://github.com/hsuanchi).
|
||||
* ✏️ Tweak the german translation of `docs/de/docs/tutorial/index.md`. PR [#10962](https://github.com/tiangolo/fastapi/pull/10962) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* ✏️ Fix typo error in `docs/ko/docs/tutorial/path-params.md`. PR [#10758](https://github.com/tiangolo/fastapi/pull/10758) by [@2chanhaeng](https://github.com/2chanhaeng).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#1961](https://github.com/tiangolo/fastapi/pull/1961) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#1960](https://github.com/tiangolo/fastapi/pull/1960) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/sub-dependencies.md`. PR [#1959](https://github.com/tiangolo/fastapi/pull/1959) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/background-tasks.md`. PR [#2668](https://github.com/tiangolo/fastapi/pull/2668) by [@tokusumi](https://github.com/tokusumi).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/dependencies/index.md` and `docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#1958](https://github.com/tiangolo/fastapi/pull/1958) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-model.md`. PR [#1938](https://github.com/tiangolo/fastapi/pull/1938) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-multiple-params.md`. PR [#1903](https://github.com/tiangolo/fastapi/pull/1903) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc).
|
||||
* 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21).
|
||||
* 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann).
|
||||
* ✏️ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB).
|
||||
* ✏️ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl).
|
||||
* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED).
|
||||
|
||||
### Internal
|
||||
|
||||
* 🔧 Add Italian to `mkdocs.yml`. PR [#11016](https://github.com/tiangolo/fastapi/pull/11016) by [@alejsdev](https://github.com/alejsdev).
|
||||
* 🔨 Verify `mkdocs.yml` languages in CI, update `docs.py`. PR [#11009](https://github.com/tiangolo/fastapi/pull/11009) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Update config in `label-approved.yml` to accept translations with 1 reviewer. PR [#11007](https://github.com/tiangolo/fastapi/pull/11007) by [@alejsdev](https://github.com/alejsdev).
|
||||
* 👷 Add changes-requested handling in GitHub Action issue manager. PR [#10971](https://github.com/tiangolo/fastapi/pull/10971) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Group dependencies on dependabot updates. PR [#10952](https://github.com/tiangolo/fastapi/pull/10952) by [@Kludex](https://github.com/Kludex).
|
||||
* ⬆ Bump actions/setup-python from 4 to 5. PR [#10764](https://github.com/tiangolo/fastapi/pull/10764) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.109.0
|
||||
|
||||
### Features
|
||||
@@ -3374,7 +3492,7 @@ Note: all the previous parameters are still there, so it's still possible to dec
|
||||
|
||||
* Add OAuth2 redirect page for Swagger UI. This allows having delegated authentication in the Swagger UI docs. For this to work, you need to add `{your_origin}/docs/oauth2-redirect` to the allowed callbacks in your OAuth2 provider (in Auth0, Facebook, Google, etc).
|
||||
* For example, during development, it could be `http://localhost:8000/docs/oauth2-redirect`.
|
||||
* Have in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`.
|
||||
* Keep in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`.
|
||||
* This is only to allow delegated authentication in the API docs with Swagger UI.
|
||||
* PR [#198](https://github.com/tiangolo/fastapi/pull/198) by [@steinitzu](https://github.com/steinitzu).
|
||||
|
||||
|
||||
@@ -79,7 +79,7 @@ You can create the *path operations* for that module using `APIRouter`.
|
||||
|
||||
You import it and create an "instance" the same way you would with the class `FastAPI`:
|
||||
|
||||
```Python hl_lines="1 3"
|
||||
```Python hl_lines="1 3" title="app/routers/users.py"
|
||||
{!../../../docs_src/bigger_applications/app/routers/users.py!}
|
||||
```
|
||||
|
||||
@@ -89,7 +89,7 @@ And then you use it to declare your *path operations*.
|
||||
|
||||
Use it the same way you would use the `FastAPI` class:
|
||||
|
||||
```Python hl_lines="6 11 16"
|
||||
```Python hl_lines="6 11 16" title="app/routers/users.py"
|
||||
{!../../../docs_src/bigger_applications/app/routers/users.py!}
|
||||
```
|
||||
|
||||
@@ -114,13 +114,13 @@ We will now use a simple dependency to read a custom `X-Token` header:
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
```Python hl_lines="3 6-8"
|
||||
```Python hl_lines="3 6-8" title="app/dependencies.py"
|
||||
{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!}
|
||||
```
|
||||
|
||||
=== "Python 3.8+"
|
||||
|
||||
```Python hl_lines="1 5-7"
|
||||
```Python hl_lines="1 5-7" title="app/dependencies.py"
|
||||
{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!}
|
||||
```
|
||||
|
||||
@@ -129,7 +129,7 @@ We will now use a simple dependency to read a custom `X-Token` header:
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="1 4-6"
|
||||
```Python hl_lines="1 4-6" title="app/dependencies.py"
|
||||
{!> ../../../docs_src/bigger_applications/app/dependencies.py!}
|
||||
```
|
||||
|
||||
@@ -160,7 +160,7 @@ We know all the *path operations* in this module have the same:
|
||||
|
||||
So, instead of adding all that to each *path operation*, we can add it to the `APIRouter`.
|
||||
|
||||
```Python hl_lines="5-10 16 21"
|
||||
```Python hl_lines="5-10 16 21" title="app/routers/items.py"
|
||||
{!../../../docs_src/bigger_applications/app/routers/items.py!}
|
||||
```
|
||||
|
||||
@@ -212,7 +212,7 @@ And we need to get the dependency function from the module `app.dependencies`, t
|
||||
|
||||
So we use a relative import with `..` for the dependencies:
|
||||
|
||||
```Python hl_lines="3"
|
||||
```Python hl_lines="3" title="app/routers/items.py"
|
||||
{!../../../docs_src/bigger_applications/app/routers/items.py!}
|
||||
```
|
||||
|
||||
@@ -282,7 +282,7 @@ We are not adding the prefix `/items` nor the `tags=["items"]` to each *path ope
|
||||
|
||||
But we can still add _more_ `tags` that will be applied to a specific *path operation*, and also some extra `responses` specific to that *path operation*:
|
||||
|
||||
```Python hl_lines="30-31"
|
||||
```Python hl_lines="30-31" title="app/routers/items.py"
|
||||
{!../../../docs_src/bigger_applications/app/routers/items.py!}
|
||||
```
|
||||
|
||||
@@ -307,7 +307,7 @@ You import and create a `FastAPI` class as normally.
|
||||
|
||||
And we can even declare [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank} that will be combined with the dependencies for each `APIRouter`:
|
||||
|
||||
```Python hl_lines="1 3 7"
|
||||
```Python hl_lines="1 3 7" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
@@ -315,7 +315,7 @@ And we can even declare [global dependencies](dependencies/global-dependencies.m
|
||||
|
||||
Now we import the other submodules that have `APIRouter`s:
|
||||
|
||||
```Python hl_lines="5"
|
||||
```Python hl_lines="4-5" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
@@ -377,7 +377,7 @@ The `router` from `users` would overwrite the one from `items` and we wouldn't b
|
||||
|
||||
So, to be able to use both of them in the same file, we import the submodules directly:
|
||||
|
||||
```Python hl_lines="5"
|
||||
```Python hl_lines="5" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
@@ -385,7 +385,7 @@ So, to be able to use both of them in the same file, we import the submodules di
|
||||
|
||||
Now, let's include the `router`s from the submodules `users` and `items`:
|
||||
|
||||
```Python hl_lines="10-11"
|
||||
```Python hl_lines="10-11" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
@@ -418,7 +418,7 @@ It contains an `APIRouter` with some admin *path operations* that your organizat
|
||||
|
||||
For this example it will be super simple. But let's say that because it is shared with other projects in the organization, we cannot modify it and add a `prefix`, `dependencies`, `tags`, etc. directly to the `APIRouter`:
|
||||
|
||||
```Python hl_lines="3"
|
||||
```Python hl_lines="3" title="app/internal/admin.py"
|
||||
{!../../../docs_src/bigger_applications/app/internal/admin.py!}
|
||||
```
|
||||
|
||||
@@ -426,7 +426,7 @@ But we still want to set a custom `prefix` when including the `APIRouter` so tha
|
||||
|
||||
We can declare all that without having to modify the original `APIRouter` by passing those parameters to `app.include_router()`:
|
||||
|
||||
```Python hl_lines="14-17"
|
||||
```Python hl_lines="14-17" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
@@ -449,7 +449,7 @@ We can also add *path operations* directly to the `FastAPI` app.
|
||||
|
||||
Here we do it... just to show that we can 🤷:
|
||||
|
||||
```Python hl_lines="21-23"
|
||||
```Python hl_lines="21-23" title="app/main.py"
|
||||
{!../../../docs_src/bigger_applications/app/main.py!}
|
||||
```
|
||||
|
||||
|
||||
@@ -361,7 +361,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo
|
||||
```
|
||||
|
||||
!!! tip
|
||||
Have in mind that JSON only supports `str` as keys.
|
||||
Keep in mind that JSON only supports `str` as keys.
|
||||
|
||||
But Pydantic has automatic data conversion.
|
||||
|
||||
|
||||
@@ -234,9 +234,7 @@ You will receive a response telling you that the data is invalid containing the
|
||||
|
||||
And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class.
|
||||
|
||||
The only difference, is that **FastAPI**'s `HTTPException` allows you to add headers to be included in the response.
|
||||
|
||||
This is needed/used internally for OAuth 2.0 and some security utilities.
|
||||
The only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it.
|
||||
|
||||
So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code.
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ The middleware function receives:
|
||||
```
|
||||
|
||||
!!! tip
|
||||
Have in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>.
|
||||
Keep in mind that custom proprietary headers can be added <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">using the 'X-' prefix</a>.
|
||||
|
||||
But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>.
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ So, you can declare your function as:
|
||||
{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!}
|
||||
```
|
||||
|
||||
But have in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`.
|
||||
But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`.
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
@@ -166,7 +166,7 @@ Python won't do anything with that `*`, but it will know that all the following
|
||||
|
||||
### Better with `Annotated`
|
||||
|
||||
Have in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
|
||||
Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`.
|
||||
|
||||
=== "Python 3.9+"
|
||||
|
||||
|
||||
@@ -173,7 +173,7 @@ q: str | None = None
|
||||
But it declares it explicitly as being a query parameter.
|
||||
|
||||
!!! info
|
||||
Have in mind that the most important part to make a parameter optional is the part:
|
||||
Keep in mind that the most important part to make a parameter optional is the part:
|
||||
|
||||
```Python
|
||||
= None
|
||||
@@ -199,7 +199,7 @@ This will validate the data, show a clear error when the data is not valid, and
|
||||
|
||||
### `Query` as the default value or in `Annotated`
|
||||
|
||||
Have in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`.
|
||||
Keep in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`.
|
||||
|
||||
Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent.
|
||||
|
||||
@@ -659,7 +659,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho
|
||||
```
|
||||
|
||||
!!! note
|
||||
Have in mind that in this case, FastAPI won't check the contents of the list.
|
||||
Keep in mind that in this case, FastAPI won't check the contents of the list.
|
||||
|
||||
For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't.
|
||||
|
||||
@@ -670,7 +670,7 @@ You can add more information about the parameter.
|
||||
That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools.
|
||||
|
||||
!!! note
|
||||
Have in mind that different tools might have different levels of OpenAPI support.
|
||||
Keep in mind that different tools might have different levels of OpenAPI support.
|
||||
|
||||
Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development.
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ The files will be uploaded as "form data".
|
||||
|
||||
If you declare the type of your *path operation function* parameter as `bytes`, **FastAPI** will read the file for you and you will receive the contents as `bytes`.
|
||||
|
||||
Have in mind that this means that the whole contents will be stored in memory. This will work well for small files.
|
||||
Keep in mind that this means that the whole contents will be stored in memory. This will work well for small files.
|
||||
|
||||
But there are several cases in which you might benefit from using `UploadFile`.
|
||||
|
||||
|
||||
@@ -227,7 +227,7 @@ Just use any kind of model, any kind of class, any kind of database that you nee
|
||||
|
||||
## Code size
|
||||
|
||||
This example might seem verbose. Have in mind that we are mixing security, data models, utility functions and *path operations* in the same file.
|
||||
This example might seem verbose. Keep in mind that we are mixing security, data models, utility functions and *path operations* in the same file.
|
||||
|
||||
But here's the key point.
|
||||
|
||||
|
||||
@@ -285,7 +285,7 @@ Create a real JWT access token and return it
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="114-127"
|
||||
```Python hl_lines="114-129"
|
||||
{!> ../../../docs_src/security/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
@@ -294,7 +294,7 @@ Create a real JWT access token and return it
|
||||
!!! tip
|
||||
Prefer to use the `Annotated` version if possible.
|
||||
|
||||
```Python hl_lines="115-128"
|
||||
```Python hl_lines="115-130"
|
||||
{!> ../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
@@ -318,7 +318,7 @@ In those cases, several of those entities could have the same ID, let's say `foo
|
||||
|
||||
So, to avoid ID collisions, when creating the JWT token for the user, you could prefix the value of the `sub` key, e.g. with `username:`. So, in this example, the value of `sub` could have been: `username:johndoe`.
|
||||
|
||||
The important thing to have in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string.
|
||||
The important thing to keep in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string.
|
||||
|
||||
## Check it
|
||||
|
||||
|
||||
@@ -301,7 +301,7 @@ while Pydantic *models* declare the types using `:`, the new type annotation syn
|
||||
name: str
|
||||
```
|
||||
|
||||
Have it in mind, so you don't get confused when using `=` and `:` with them.
|
||||
Keep these in mind, so you don't get confused when using `=` and `:` with them.
|
||||
|
||||
### Create Pydantic *models* / schemas for reading / returning
|
||||
|
||||
@@ -513,7 +513,7 @@ And you would also use Alembic for "migrations" (that's its main job).
|
||||
|
||||
A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc.
|
||||
|
||||
You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/alembic/" class="external-link" target="_blank">the `alembic` directory in the source code</a>.
|
||||
You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic" class="external-link" target="_blank">the `alembic` directory in the source code</a>.
|
||||
|
||||
### Create a dependency
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ You can serve static files automatically from a directory using `StaticFiles`.
|
||||
|
||||
This is different from using an `APIRouter` as a mounted application is completely independent. The OpenAPI and docs from your main application won't include anything from the mounted application, etc.
|
||||
|
||||
You can read more about this in the **Advanced User Guide**.
|
||||
You can read more about this in the [Advanced User Guide](../advanced/index.md){.internal-link target=_blank}.
|
||||
|
||||
## Details
|
||||
|
||||
|
||||
@@ -174,9 +174,6 @@ nav:
|
||||
- How To - Recipes:
|
||||
- how-to/index.md
|
||||
- how-to/general.md
|
||||
- how-to/sql-databases-peewee.md
|
||||
- how-to/async-sql-encode-databases.md
|
||||
- how-to/nosql-databases-couchbase.md
|
||||
- how-to/graphql.md
|
||||
- how-to/custom-request-and-route.md
|
||||
- how-to/conditional-openapi.md
|
||||
@@ -184,6 +181,9 @@ nav:
|
||||
- how-to/separate-openapi-schemas.md
|
||||
- how-to/custom-docs-ui-assets.md
|
||||
- how-to/configure-swagger-ui.md
|
||||
- how-to/sql-databases-peewee.md
|
||||
- how-to/async-sql-encode-databases.md
|
||||
- how-to/nosql-databases-couchbase.md
|
||||
- Reference (Code API):
|
||||
- reference/index.md
|
||||
- reference/fastapi.md
|
||||
@@ -242,6 +242,7 @@ markdown_extensions:
|
||||
format: !!python/name:pymdownx.superfences.fence_code_format ''
|
||||
pymdownx.tabbed:
|
||||
alternate_style: true
|
||||
pymdownx.tilde: null
|
||||
attr_list: null
|
||||
md_in_html: null
|
||||
extra:
|
||||
@@ -266,6 +267,8 @@ extra:
|
||||
alternate:
|
||||
- link: /
|
||||
name: en - English
|
||||
- link: /bn/
|
||||
name: bn - বাংলা
|
||||
- link: /de/
|
||||
name: de - Deutsch
|
||||
- link: /es/
|
||||
@@ -280,6 +283,8 @@ extra:
|
||||
name: hu - magyar
|
||||
- link: /id/
|
||||
name: id - Bahasa Indonesia
|
||||
- link: /it/
|
||||
name: it - italiano
|
||||
- link: /ja/
|
||||
name: ja - 日本語
|
||||
- link: /ko/
|
||||
@@ -301,7 +306,9 @@ extra:
|
||||
- link: /yo/
|
||||
name: yo - Yorùbá
|
||||
- link: /zh/
|
||||
name: zh - 汉语
|
||||
name: zh - 简体中文
|
||||
- link: /zh-hant/
|
||||
name: zh-hant - 繁體中文
|
||||
- link: /em/
|
||||
name: 😉
|
||||
extra_css:
|
||||
|
||||
@@ -23,7 +23,7 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte
|
||||
|
||||
No será serializado con el modelo, etc.
|
||||
|
||||
Asegurate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`).
|
||||
Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`).
|
||||
|
||||
!!! note "Detalles Técnicos"
|
||||
También podrías utilizar `from starlette.responses import JSONResponse`.
|
||||
|
||||
@@ -21,7 +21,7 @@ Y cuando devuelves una `Response`, **FastAPI** la pasará directamente.
|
||||
|
||||
No hará ninguna conversión de datos con modelos Pydantic, no convertirá el contenido a ningún tipo, etc.
|
||||
|
||||
Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquer declaración de datos o validación, etc.
|
||||
Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquier declaración de datos o validación, etc.
|
||||
|
||||
## Usando el `jsonable_encoder` en una `Response`
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
### Documentación automática
|
||||
|
||||
Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluídas por defecto, porque el framework está basado en OpenAPI.
|
||||
Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluidas por defecto, porque el framework está basado en OpenAPI.
|
||||
|
||||
* <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank"><strong>Swagger UI</strong></a>, con exploración interactiva, llama y prueba tu API directamente desde tu navegador.
|
||||
|
||||
@@ -25,7 +25,7 @@ Documentación interactiva de la API e interfaces web de exploración. Hay múlt
|
||||
|
||||
### Simplemente Python moderno
|
||||
|
||||
Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintáxis nueva, solo Python moderno.
|
||||
Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintaxis nueva, solo Python moderno.
|
||||
|
||||
Si necesitas un repaso de 2 minutos de cómo usar los tipos de Python (así no uses FastAPI) prueba el tutorial corto: [Python Types](python-types.md){.internal-link target=_blank}.
|
||||
|
||||
@@ -72,9 +72,9 @@ my_second_user: User = User(**second_user_data)
|
||||
|
||||
El framework fue diseñado en su totalidad para ser fácil e intuitivo de usar. Todas las decisiones fueron probadas en múltiples editores antes de comenzar el desarrollo para asegurar la mejor experiencia de desarrollo.
|
||||
|
||||
En la última encuesta a desarrolladores de Python fue claro que <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">la característica más usada es el "autocompletado"</a>.
|
||||
En la última encuesta a desarrolladores de Python fue claro que <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">la característica más usada es el "auto-completado"</a>.
|
||||
|
||||
El framework **FastAPI** está creado para satisfacer eso. El autocompletado funciona en todas partes.
|
||||
El framework **FastAPI** está creado para satisfacer eso. El auto-completado funciona en todas partes.
|
||||
|
||||
No vas a tener que volver a la documentación seguido.
|
||||
|
||||
@@ -140,13 +140,13 @@ FastAPI incluye un sistema de <abbr title='En español: Inyección de Dependenci
|
||||
* Todas las dependencias pueden requerir datos de los requests y aumentar las restricciones del *path operation* y la documentación automática.
|
||||
* **Validación automática** inclusive para parámetros del *path operation* definidos en las dependencias.
|
||||
* Soporte para sistemas complejos de autenticación de usuarios, **conexiones con bases de datos**, etc.
|
||||
* **Sin comprometerse** con bases de datos, frontends, etc. Pero permitiendo integración fácil con todos ellos.
|
||||
* **Sin comprometerse** con bases de datos, frontend, etc. Pero permitiendo integración fácil con todos ellos.
|
||||
|
||||
### "Plug-ins" ilimitados
|
||||
|
||||
O dicho de otra manera, no hay necesidad para "plug-ins". Importa y usa el código que necesites.
|
||||
|
||||
Cualquier integración está diseñada para que sea tan sencilla de usar (con dependencias) que puedas crear un "plug-in" para tu aplicación en dos líneas de código usando la misma estructura y sintáxis que usaste para tus *path operations*.
|
||||
Cualquier integración está diseñada para que sea tan sencilla de usar (con dependencias) que puedas crear un "plug-in" para tu aplicación en dos líneas de código usando la misma estructura y sintaxis que usaste para tus *path operations*.
|
||||
|
||||
### Probado
|
||||
|
||||
@@ -181,7 +181,7 @@ Esto incluye a librerías externas basadas en Pydantic como <abbr title="Object-
|
||||
|
||||
Esto también significa que en muchos casos puedes pasar el mismo objeto que obtuviste de un request **directamente a la base de datos**, dado que todo es validado automáticamente.
|
||||
|
||||
Lo mismo aplica para el sentido contrario. En muchos casos puedes pasarle el objeto que obtienes de la base de datos **directamente al cliente**.
|
||||
Lo mismo aplica para el sentido contrario. En muchos casos puedes pasar el objeto que obtienes de la base de datos **directamente al cliente**.
|
||||
|
||||
Con **FastAPI** obtienes todas las características de **Pydantic** (dado que FastAPI está basado en Pydantic para todo el manejo de datos):
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ Sus características principales son:
|
||||
* **Robusto**: Crea código listo para producción con documentación automática interactiva.
|
||||
* **Basado en estándares**: Basado y totalmente compatible con los estándares abiertos para APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (conocido previamente como Swagger) y <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
|
||||
|
||||
<small>* Esta estimación está basada en pruebas con un equipo de desarrollo interno contruyendo aplicaciones listas para producción.</small>
|
||||
<small>* Esta estimación está basada en pruebas con un equipo de desarrollo interno construyendo aplicaciones listas para producción.</small>
|
||||
|
||||
## Sponsors
|
||||
|
||||
@@ -295,11 +295,11 @@ Ahora ve a <a href="http://127.0.0.1:8000/docs" class="external-link" target="_b
|
||||
|
||||

|
||||
|
||||
* Haz clíck en el botón de "Try it out" que te permite llenar los parámetros e interactuar directamente con la API:
|
||||
* Haz click en el botón de "Try it out" que te permite llenar los parámetros e interactuar directamente con la API:
|
||||
|
||||

|
||||
|
||||
* Luego haz clíck en el botón de "Execute". La interfaz de usuario se comunicará con tu API, enviará los parámetros y recibirá los resultados para mostrarlos en pantalla:
|
||||
* Luego haz click en el botón de "Execute". La interfaz de usuario se comunicará con tu API, enviará los parámetros y recibirá los resultados para mostrarlos en pantalla:
|
||||
|
||||

|
||||
|
||||
@@ -317,7 +317,7 @@ En resumen, declaras los tipos de parámetros, body, etc. **una vez** como pará
|
||||
|
||||
Lo haces con tipos modernos estándar de Python.
|
||||
|
||||
No tienes que aprender una sintáxis nueva, los métodos o clases de una library específica, etc.
|
||||
No tienes que aprender una sintaxis nueva, los métodos o clases de una library específica, etc.
|
||||
|
||||
Solo **Python 3.8+** estándar.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Python 3.6+** tiene soporte para <abbr title="en español, anotaciones de tipo. En inglés también se conocen como: type annotations">"type hints"</abbr> opcionales.
|
||||
|
||||
Estos **type hints** son una nueva sintáxis, desde Python 3.6+, que permite declarar el <abbr title="por ejemplo: str, int, float, bool">tipo</abbr> de una variable.
|
||||
Estos **type hints** son una nueva sintaxis, desde Python 3.6+, que permite declarar el <abbr title="por ejemplo: str, int, float, bool">tipo</abbr> de una variable.
|
||||
|
||||
Usando las declaraciones de tipos para tus variables, los editores y otras herramientas pueden proveerte un soporte mejor.
|
||||
|
||||
@@ -33,7 +33,7 @@ La función hace lo siguiente:
|
||||
|
||||
* Toma un `first_name` y un `last_name`.
|
||||
* Convierte la primera letra de cada uno en una letra mayúscula con `title()`.
|
||||
* Las <abbr title="las junta como si fuesen una. Con el contenido de una después de la otra. En inlgés: concatenate.">concatena</abbr> con un espacio en la mitad.
|
||||
* Las <abbr title="las junta como si fuesen una. Con el contenido de una después de la otra. En inglés: concatenate.">concatena</abbr> con un espacio en la mitad.
|
||||
|
||||
```Python hl_lines="2"
|
||||
{!../../../docs_src/python_types/tutorial001.py!}
|
||||
@@ -51,9 +51,9 @@ Pero, luego tienes que llamar "ese método que convierte la primera letra en una
|
||||
|
||||
Era `upper`? O era `uppercase`? `first_uppercase`? `capitalize`?
|
||||
|
||||
Luego lo intentas con el viejo amigo de los programadores, el autocompletado del editor.
|
||||
Luego lo intentas con el viejo amigo de los programadores, el auto-completado del editor.
|
||||
|
||||
Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el autocompletado.
|
||||
Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el auto-completado.
|
||||
|
||||
Tristemente, no obtienes nada útil:
|
||||
|
||||
@@ -97,7 +97,7 @@ Añadir los type hints normalmente no cambia lo que sucedería si ellos no estuv
|
||||
|
||||
Pero ahora imagina que nuevamente estás creando la función, pero con los type hints.
|
||||
|
||||
En el mismo punto intentas iniciar el autocompletado con `Ctrl+Space` y ves:
|
||||
En el mismo punto intentas iniciar el auto-completado con `Ctrl+Space` y ves:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/python-types/image02.png">
|
||||
|
||||
@@ -113,7 +113,7 @@ Mira esta función que ya tiene type hints:
|
||||
{!../../../docs_src/python_types/tutorial003.py!}
|
||||
```
|
||||
|
||||
Como el editor conoce el tipo de las variables no solo obtienes autocompletado, si no que también obtienes chequeo de errores:
|
||||
Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/python-types/image04.png">
|
||||
|
||||
@@ -162,7 +162,7 @@ De `typing`, importa `List` (con una `L` mayúscula):
|
||||
{!../../../docs_src/python_types/tutorial006.py!}
|
||||
```
|
||||
|
||||
Declara la variable con la misma sintáxis de los dos puntos (`:`).
|
||||
Declara la variable con la misma sintaxis de los dos puntos (`:`).
|
||||
|
||||
Pon `List` como el tipo.
|
||||
|
||||
@@ -176,7 +176,7 @@ Esto significa: la variable `items` es una `list` y cada uno de los ítems en es
|
||||
|
||||
Con esta declaración tu editor puede proveerte soporte inclusive mientras está procesando ítems de la lista.
|
||||
|
||||
Sin tipos el autocompletado en este tipo de estructura es casi imposible de lograr:
|
||||
Sin tipos el auto-completado en este tipo de estructura es casi imposible de lograr:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/python-types/image05.png">
|
||||
|
||||
|
||||
@@ -303,7 +303,7 @@ En este caso es una función `async`.
|
||||
|
||||
---
|
||||
|
||||
También podrías definirla como una función normal, en vez de `async def`:
|
||||
También podrías definirla como una función estándar en lugar de `async def`:
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!../../../docs_src/first_steps/tutorial003.py!}
|
||||
|
||||
@@ -28,7 +28,7 @@ $ uvicorn main:app --reload
|
||||
|
||||
Se **RECOMIENDA** que escribas o copies el código, lo edites y lo ejecutes localmente.
|
||||
|
||||
Usarlo en tu editor de código es lo que realmente te muestra los beneficios de FastAPI, al ver la poca cantidad de código que tienes que escribir, todas las verificaciones de tipo, autocompletado, etc.
|
||||
Usarlo en tu editor de código es lo que realmente te muestra los beneficios de FastAPI, al ver la poca cantidad de código que tienes que escribir, todas las verificaciones de tipo, auto-completado, etc.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ Puedes declarar el tipo de un parámetro de path en la función usando las anota
|
||||
En este caso, `item_id` es declarado como un `int`.
|
||||
|
||||
!!! check "Revisa"
|
||||
Esto te dará soporte en el editor dentro de tu función, con chequeos de errores, autocompletado, etc.
|
||||
Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc.
|
||||
|
||||
## <abbr title="también conocido en inglés como: serialization, parsing, marshalling">Conversión</abbr> de datos
|
||||
|
||||
@@ -135,7 +135,7 @@ Luego crea atributos de clase con valores fijos, que serán los valores disponib
|
||||
Las <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">Enumerations (o enums) están disponibles en Python</a> desde la versión 3.4.
|
||||
|
||||
!!! tip "Consejo"
|
||||
Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de <abbr title="Tecnicamente, arquitecturas de modelos de Deep Learning">modelos</abbr> de Machine Learning.
|
||||
Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de <abbr title="Técnicamente, arquitecturas de modelos de Deep Learning">modelos</abbr> de Machine Learning.
|
||||
|
||||
### Declara un *parámetro de path*
|
||||
|
||||
@@ -234,7 +234,7 @@ Entonces lo puedes usar con:
|
||||
|
||||
Con **FastAPI**, usando declaraciones de tipo de Python intuitivas y estándares, obtienes:
|
||||
|
||||
* Soporte en el editor: chequeos de errores, auto-completado, etc.
|
||||
* Soporte en el editor: chequeo de errores, auto-completado, etc.
|
||||
* "<abbr title="convertir el string que viene de un HTTP request a datos de Python">Parsing</abbr>" de datos
|
||||
* Validación de datos
|
||||
* Anotación de la API y documentación automática
|
||||
|
||||
100
docs/fa/docs/tutorial/security/index.md
Normal file
100
docs/fa/docs/tutorial/security/index.md
Normal file
@@ -0,0 +1,100 @@
|
||||
# امنیت
|
||||
|
||||
روشهای مختلفی برای مدیریت امنیت، تأیید هویت و اعتبارسنجی وجود دارد.
|
||||
|
||||
عموماً این یک موضوع پیچیده و "سخت" است.
|
||||
|
||||
در بسیاری از فریم ورک ها و سیستمها، فقط مدیریت امنیت و تأیید هویت نیاز به تلاش و کد نویسی زیادی دارد (در بسیاری از موارد میتواند 50% یا بیشتر کل کد نوشته شده باشد).
|
||||
|
||||
|
||||
فریم ورک **FastAPI** ابزارهای متعددی را در اختیار شما قرار می دهد تا به راحتی، با سرعت، به صورت استاندارد و بدون نیاز به مطالعه و یادگیری همه جزئیات امنیت، در مدیریت **امنیت** به شما کمک کند.
|
||||
|
||||
اما قبل از آن، بیایید برخی از مفاهیم کوچک را بررسی کنیم.
|
||||
|
||||
## عجله دارید؟
|
||||
|
||||
اگر به هیچ یک از این اصطلاحات اهمیت نمی دهید و فقط نیاز به افزودن امنیت با تأیید هویت بر اساس نام کاربری و رمز عبور دارید، *همین الان* به فصل های بعدی بروید.
|
||||
|
||||
## پروتکل استاندارد OAuth2
|
||||
|
||||
پروتکل استاندارد OAuth2 یک مشخصه است که چندین روش برای مدیریت تأیید هویت و اعتبار سنجی تعریف می کند.
|
||||
|
||||
این مشخصه بسیار گسترده است و چندین حالت استفاده پیچیده را پوشش می دهد.
|
||||
|
||||
در آن روش هایی برای تأیید هویت با استفاده از "برنامه های شخص ثالث" وجود دارد.
|
||||
|
||||
این همان چیزی است که تمامی سیستم های با "ورود با فیسبوک، گوگل، توییتر، گیت هاب" در پایین آن را استفاده می کنند.
|
||||
|
||||
### پروتکل استاندارد OAuth 1
|
||||
|
||||
پروتکل استاندارد OAuth1 نیز وجود داشت که با OAuth2 خیلی متفاوت است و پیچیدگی بیشتری داشت، زیرا شامل مشخصات مستقیم در مورد رمزگذاری ارتباط بود.
|
||||
|
||||
در حال حاضر OAuth1 بسیار محبوب یا استفاده شده نیست.
|
||||
|
||||
پروتکل استاندارد OAuth2 روش رمزگذاری ارتباط را مشخص نمی کند، بلکه انتظار دارد که برنامه شما با HTTPS سرویس دهی شود.
|
||||
|
||||
!!! نکته
|
||||
در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید.
|
||||
|
||||
## استاندارد OpenID Connect
|
||||
|
||||
استاندارد OpenID Connect، مشخصهای دیگر است که بر پایه **OAuth2** ساخته شده است.
|
||||
|
||||
این مشخصه، به گسترش OAuth2 میپردازد و برخی مواردی که در OAuth2 نسبتاً تردید برانگیز هستند را مشخص میکند تا سعی شود آن را با سایر سیستمها قابل ارتباط کند.
|
||||
|
||||
به عنوان مثال، ورود به سیستم گوگل از OpenID Connect استفاده میکند (که در زیر از OAuth2 استفاده میکند).
|
||||
|
||||
اما ورود به سیستم فیسبوک، از OpenID Connect پشتیبانی نمیکند. به جای آن، نسخه خودش از OAuth2 را دارد.
|
||||
|
||||
### استاندارد OpenID (نه "OpenID Connect" )
|
||||
|
||||
همچنین مشخصه "OpenID" نیز وجود داشت که سعی در حل مسائل مشابه OpenID Connect داشت، اما بر پایه OAuth2 ساخته نشده بود.
|
||||
|
||||
بنابراین، یک سیستم جداگانه بود.
|
||||
|
||||
اکنون این مشخصه کمتر استفاده میشود و محبوبیت زیادی ندارد.
|
||||
|
||||
## استاندارد OpenAPI
|
||||
|
||||
استاندارد OpenAPI (قبلاً با نام Swagger شناخته میشد) یک open specification برای ساخت APIs (که در حال حاضر جزئی از بنیاد لینوکس میباشد) است.
|
||||
|
||||
فریم ورک **FastAPI** بر اساس **OpenAPI** است.
|
||||
|
||||
این خاصیت، امکان دارد تا چندین رابط مستندات تعاملی خودکار(automatic interactive documentation interfaces)، تولید کد و غیره وجود داشته باشد.
|
||||
|
||||
مشخصه OpenAPI روشی برای تعریف چندین "schemes" دارد.
|
||||
|
||||
با استفاده از آنها، شما میتوانید از همه این ابزارهای مبتنی بر استاندارد استفاده کنید، از جمله این سیستمهای مستندات تعاملی(interactive documentation systems).
|
||||
|
||||
استاندارد OpenAPI شیوههای امنیتی زیر را تعریف میکند:
|
||||
|
||||
* شیوه `apiKey`: یک کلید اختصاصی برای برنامه که میتواند از موارد زیر استفاده شود:
|
||||
* پارامتر جستجو.
|
||||
* هدر.
|
||||
* کوکی.
|
||||
* شیوه `http`: سیستمهای استاندارد احراز هویت HTTP، از جمله:
|
||||
* مقدار `bearer`: یک هدر `Authorization` با مقدار `Bearer` به همراه یک توکن. این از OAuth2 به ارث برده شده است.
|
||||
* احراز هویت پایه HTTP.
|
||||
* ویژگی HTTP Digest و غیره.
|
||||
* شیوه `oauth2`: تمام روشهای OAuth2 برای مدیریت امنیت (به نام "flows").
|
||||
* چندین از این flows برای ساخت یک ارائهدهنده احراز هویت OAuth 2.0 مناسب هستند (مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره):
|
||||
* ویژگی `implicit`
|
||||
* ویژگی `clientCredentials`
|
||||
* ویژگی `authorizationCode`
|
||||
* اما یک "flow" خاص وجود دارد که میتواند به طور کامل برای مدیریت احراز هویت در همان برنامه به کار رود:
|
||||
* بررسی `password`: چند فصل بعدی به مثالهای این مورد خواهیم پرداخت.
|
||||
* شیوه `openIdConnect`: یک روش برای تعریف نحوه کشف دادههای احراز هویت OAuth2 به صورت خودکار.
|
||||
* کشف خودکار این موضوع را که در مشخصه OpenID Connect تعریف شده است، مشخص میکند.
|
||||
|
||||
!!! نکته
|
||||
ادغام سایر ارائهدهندگان احراز هویت/اجازهدهی مانند گوگل، فیسبوک، توییتر، گیتهاب و غیره نیز امکانپذیر و نسبتاً آسان است.
|
||||
|
||||
مشکل پیچیدهترین مسئله، ساخت یک ارائهدهنده احراز هویت/اجازهدهی مانند آنها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما میدهد و همه کارهای سنگین را برای شما انجام میدهد.
|
||||
|
||||
## ابزارهای **FastAPI**
|
||||
|
||||
فریم ورک FastAPI ابزارهایی برای هر یک از این شیوههای امنیتی در ماژول`fastapi.security` فراهم میکند که استفاده از این مکانیزمهای امنیتی را سادهتر میکند.
|
||||
|
||||
در فصلهای بعدی، شما یاد خواهید گرفت که چگونه با استفاده از این ابزارهای ارائه شده توسط **FastAPI**، امنیت را به API خود اضافه کنید.
|
||||
|
||||
همچنین، خواهید دید که چگونه به صورت خودکار در سیستم مستندات تعاملی ادغام میشود.
|
||||
464
docs/it/docs/index.md
Normal file
464
docs/it/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, alte prestazioni, facile da imparare, rapido da implementare, pronto per il rilascio in produzione</em>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://travis-ci.com/tiangolo/fastapi" target="_blank">
|
||||
<img src="https://travis-ci.com/tiangolo/fastapi.svg?branch=master" alt="Build Status">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/tiangolo/fastapi" target="_blank">
|
||||
<img src="https://img.shields.io/codecov/c/github/tiangolo/fastapi" alt="Coverage">
|
||||
</a>
|
||||
<a href="https://pypi.org/project/fastapi" target="_blank">
|
||||
<img src="https://badge.fury.io/py/fastapi.svg" alt="Package version">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
**Documentazione**: <a href="https://fastapi.tiangolo.com" target="_blank">https://fastapi.tiangolo.com</a>
|
||||
|
||||
**Codice Sorgente**: <a href="https://github.com/tiangolo/fastapi" target="_blank">https://github.com/tiangolo/fastapi</a>
|
||||
|
||||
---
|
||||
|
||||
FastAPI è un web framework moderno e veloce (a prestazioni elevate) che serve a creare API con Python 3.6+ basato sulle annotazioni di tipo di Python.
|
||||
|
||||
Le sue caratteristiche principali sono:
|
||||
|
||||
* **Velocità**: Prestazioni molto elevate, alla pari di **NodeJS** e **Go** (grazie a Starlette e Pydantic). [Uno dei framework Python più veloci in circolazione](#performance).
|
||||
* **Veloce da programmare**: Velocizza il lavoro consentendo il rilascio di nuove funzionalità tra il 200% e il 300% più rapidamente. *
|
||||
* **Meno bug**: Riduce di circa il 40% gli errori che commettono gli sviluppatori durante la scrittura del codice. *
|
||||
* **Intuitivo**: Grande supporto per gli editor di testo con <abbr title="anche conosciuto come auto-completamento, autocompletion, IntelliSense">autocompletamento</abbr> in ogni dove. In questo modo si può dedicare meno tempo al debugging.
|
||||
* **Facile**: Progettato per essere facile da usare e imparare. Si riduce il tempo da dedicare alla lettura della documentazione.
|
||||
* **Sintentico**: Minimizza la duplicazione di codice. Molteplici funzionalità, ognuna con la propria dichiarazione dei parametri. Meno errori.
|
||||
* **Robusto**: Crea codice pronto per la produzione con documentazione automatica interattiva.
|
||||
* **Basato sugli standard**: Basato su (e completamente compatibile con) gli open standard per le API: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> (precedentemente Swagger) e <a href="https://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
|
||||
|
||||
<small>* Stima basata sull'esito di test eseguiti su codice sorgente di applicazioni rilasciate in produzione da un team interno di sviluppatori.</small>
|
||||
|
||||
## Sponsor
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
{% if sponsors %}
|
||||
{% for sponsor in sponsors.gold -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
|
||||
{% endfor -%}
|
||||
{%- for sponsor in sponsors.silver -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
<a href="https://fastapi.tiangolo.com/fastapi-people/#sponsors" class="external-link" target="_blank">Altri sponsor</a>
|
||||
|
||||
## Recensioni
|
||||
|
||||
"_[...] 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, e 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**, la FastAPI delle 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>
|
||||
|
||||
Se stai sviluppando un'app <abbr title="Command Line Interface (interfaccia della riga di comando)">CLI</abbr> da usare nel terminale invece che una web API, ti consigliamo <a href="https://typer.tiangolo.com/" class="external-link" target="_blank">**Typer**</a>.
|
||||
|
||||
**Typer** è il fratello minore di FastAPI. Ed è stato ideato per essere la **FastAPI delle CLI**. ⌨️ 🚀
|
||||
|
||||
## Requisiti
|
||||
|
||||
Python 3.6+
|
||||
|
||||
FastAPI è basata su importanti librerie:
|
||||
|
||||
* <a href="https://www.starlette.io/" class="external-link" target="_blank">Starlette</a> per le parti web.
|
||||
* <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> per le parti dei dati.
|
||||
|
||||
## Installazione
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install fastapi
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
Per il rilascio in produzione, sarà necessario un server ASGI come <a href="http://www.uvicorn.org" class="external-link" target="_blank">Uvicorn</a> oppure <a href="https://gitlab.com/pgjones/hypercorn" class="external-link" target="_blank">Hypercorn</a>.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install uvicorn[standard]
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Esempio
|
||||
|
||||
### Crea un file
|
||||
|
||||
* Crea un file `main.py` con:
|
||||
|
||||
```Python
|
||||
from fastapi import FastAPI
|
||||
from typing import Optional
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
return {"Hello": "World"}
|
||||
|
||||
|
||||
@app.get("/items/{item_id}")
|
||||
def read_item(item_id: int, q: str = Optional[None]):
|
||||
return {"item_id": item_id, "q": q}
|
||||
```
|
||||
|
||||
<details markdown="1">
|
||||
<summary>Oppure usa <code>async def</code>...</summary>
|
||||
|
||||
Se il tuo codice usa `async` / `await`, allora usa `async def`:
|
||||
|
||||
```Python hl_lines="7 12"
|
||||
from fastapi import FastAPI
|
||||
from typing import Optional
|
||||
|
||||
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}
|
||||
```
|
||||
|
||||
**Nota**:
|
||||
|
||||
e vuoi approfondire, consulta la sezione _"In a hurry?"_ su <a href="https://fastapi.tiangolo.com/async/#in-a-hurry" target="_blank">`async` e `await` nella documentazione</a>.
|
||||
|
||||
</details>
|
||||
|
||||
### Esegui il server
|
||||
|
||||
Puoi far partire il server così:
|
||||
|
||||
<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>Informazioni sul comando <code>uvicorn main:app --reload</code>...</summary>
|
||||
|
||||
Vediamo il comando `uvicorn main:app` in dettaglio:
|
||||
|
||||
* `main`: il file `main.py` (il "modulo" Python).
|
||||
* `app`: l'oggetto creato dentro `main.py` con la riga di codice `app = FastAPI()`.
|
||||
* `--reload`: ricarica il server se vengono rilevati cambiamenti del codice. Usalo solo durante la fase di sviluppo.
|
||||
|
||||
</details>
|
||||
|
||||
### Testa l'API
|
||||
|
||||
Apri il browser all'indirizzo <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>.
|
||||
|
||||
Vedrai la seguente risposta JSON:
|
||||
|
||||
```JSON
|
||||
{"item_id": 5, "q": "somequery"}
|
||||
```
|
||||
|
||||
Hai appena creato un'API che:
|
||||
|
||||
* Riceve richieste HTTP sui _paths_ `/` and `/items/{item_id}`.
|
||||
* Entrambi i _paths_ accettano`GET` <em>operations</em> (conosciuti anche come <abbr title="metodi HTTP">HTTP _methods_</abbr>).
|
||||
* Il _path_ `/items/{item_id}` ha un _path parameter_ `item_id` che deve essere un `int`.
|
||||
* Il _path_ `/items/{item_id}` ha una `str` _query parameter_ `q`.
|
||||
|
||||
### Documentazione interattiva dell'API
|
||||
|
||||
Adesso vai all'indirizzo <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
|
||||
Vedrai la documentazione interattiva dell'API (offerta da <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>):
|
||||
|
||||

|
||||
|
||||
### Documentazione interattiva alternativa
|
||||
|
||||
Adesso accedi all'url <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
|
||||
Vedrai la documentazione interattiva dell'API (offerta da <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>):
|
||||
|
||||

|
||||
|
||||
## Esempio più avanzato
|
||||
|
||||
Adesso modifica il file `main.py` per ricevere un _body_ da una richiesta `PUT`.
|
||||
|
||||
Dichiara il _body_ usando le annotazioni di tipo standard di Python, grazie a Pydantic.
|
||||
|
||||
```Python hl_lines="2 7-10 23-25"
|
||||
from fastapi import FastAPI
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
name: str
|
||||
price: float
|
||||
is_offer: bool = Optional[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}
|
||||
```
|
||||
|
||||
Il server dovrebbe ricaricarsi in automatico (perché hai specificato `--reload` al comando `uvicorn` lanciato precedentemente).
|
||||
|
||||
### Aggiornamento della documentazione interattiva
|
||||
|
||||
Adesso vai su <a href="http://127.0.0.1:8000/docs" class="external-link" target="_blank">http://127.0.0.1:8000/docs</a>.
|
||||
|
||||
* La documentazione interattiva dell'API verrà automaticamente aggiornata, includendo il nuovo _body_:
|
||||
|
||||

|
||||
|
||||
* Fai click sul pulsante "Try it out", che ti permette di inserire i parametri per interagire direttamente con l'API:
|
||||
|
||||

|
||||
|
||||
* Successivamente, premi sul pulsante "Execute". L'interfaccia utente comunicherà con la tua API, invierà i parametri, riceverà i risultati della richiesta, e li mostrerà sullo schermo:
|
||||
|
||||

|
||||
|
||||
### Aggiornamento della documentazione alternativa
|
||||
|
||||
Ora vai su <a href="http://127.0.0.1:8000/redoc" class="external-link" target="_blank">http://127.0.0.1:8000/redoc</a>.
|
||||
|
||||
* Anche la documentazione alternativa dell'API mostrerà il nuovo parametro della query e il _body_:
|
||||
|
||||

|
||||
|
||||
### Riepilogo
|
||||
|
||||
Ricapitolando, è sufficiente dichiarare **una sola volta** i tipi dei parametri, del body, ecc. come parametri di funzioni.
|
||||
|
||||
Questo con le annotazioni per i tipi standard di Python.
|
||||
|
||||
Non c'è bisogno di imparare una nuova sintassi, metodi o classi specifici a una libreria, ecc.
|
||||
|
||||
È normalissimo **Python 3.6+**.
|
||||
|
||||
Per esempio, per un `int`:
|
||||
|
||||
```Python
|
||||
item_id: int
|
||||
```
|
||||
|
||||
o per un modello `Item` più complesso:
|
||||
|
||||
```Python
|
||||
item: Item
|
||||
```
|
||||
|
||||
...e con quella singola dichiarazione hai in cambio:
|
||||
|
||||
* Supporto per gli editor di testo, incluso:
|
||||
* Autocompletamento.
|
||||
* Controllo sulle annotazioni di tipo.
|
||||
* Validazione dei dati:
|
||||
* Errori chiari e automatici quando i dati sono invalidi.
|
||||
* Validazione anche per gli oggetti JSON più complessi.
|
||||
* <abbr title="anche noto come: serializzazione, parsing, marshalling">Conversione</abbr> dei dati di input: da risorse esterne a dati e tipi di Python. È possibile leggere da:
|
||||
* JSON.
|
||||
* Path parameters.
|
||||
* Query parameters.
|
||||
* Cookies.
|
||||
* Headers.
|
||||
* Form.
|
||||
* File.
|
||||
* <abbr title="detta anche: serialization, parsing, marshalling">Conversione</abbr> dei dati di output: converte dati e tipi di Python a dati per la rete (come JSON):
|
||||
* Converte i tipi di Python (`str`, `int`, `float`, `bool`, `list`, ecc).
|
||||
* Oggetti `datetime`.
|
||||
* Oggetti `UUID`.
|
||||
* Modelli del database.
|
||||
* ...e molto di più.
|
||||
* Generazione di una documentazione dell'API interattiva, con scelta dell'interfaccia grafica:
|
||||
* Swagger UI.
|
||||
* ReDoc.
|
||||
|
||||
---
|
||||
|
||||
Tornando al precedente esempio, **FastAPI**:
|
||||
|
||||
* Validerà che esiste un `item_id` nel percorso delle richieste `GET` e `PUT`.
|
||||
* Validerà che `item_id` sia di tipo `int` per le richieste `GET` e `PUT`.
|
||||
* Se non lo è, il client vedrà un errore chiaro e utile.
|
||||
* Controllerà se ci sia un parametro opzionale chiamato `q` (per esempio `http://127.0.0.1:8000/items/foo?q=somequery`) per le richieste `GET`.
|
||||
* Siccome il parametro `q` è dichiarato con `= None`, è opzionale.
|
||||
* Senza il `None` sarebbe stato obbligatorio (come per il body della richiesta `PUT`).
|
||||
* Per le richieste `PUT` su `/items/{item_id}`, leggerà il body come JSON, questo comprende:
|
||||
* verifica che la richiesta abbia un attributo obbligatorio `name` e che sia di tipo `str`.
|
||||
* verifica che la richiesta abbia un attributo obbligatorio `price` e che sia di tipo `float`.
|
||||
* verifica che la richiesta abbia un attributo opzionale `is_offer` e che sia di tipo `bool`, se presente.
|
||||
* Tutto questo funzionerebbe anche con oggetti JSON più complessi.
|
||||
* Convertirà *da* e *a* JSON automaticamente.
|
||||
* Documenterà tutto con OpenAPI, che può essere usato per:
|
||||
* Sistemi di documentazione interattivi.
|
||||
* Sistemi di generazione di codice dal lato client, per molti linguaggi.
|
||||
* Fornirà 2 interfacce di documentazione dell'API interattive.
|
||||
|
||||
---
|
||||
|
||||
Questa è solo la punta dell'iceberg, ma dovresti avere già un'idea di come il tutto funzioni.
|
||||
|
||||
Prova a cambiare questa riga di codice:
|
||||
|
||||
```Python
|
||||
return {"item_name": item.name, "item_id": item_id}
|
||||
```
|
||||
|
||||
...da:
|
||||
|
||||
```Python
|
||||
... "item_name": item.name ...
|
||||
```
|
||||
|
||||
...a:
|
||||
|
||||
```Python
|
||||
... "item_price": item.price ...
|
||||
```
|
||||
|
||||
...e osserva come il tuo editor di testo autocompleterà gli attributi e sarà in grado di riconoscere i loro tipi:
|
||||
|
||||

|
||||
|
||||
Per un esempio più completo che mostra più funzionalità del framework, consulta <a href="https://fastapi.tiangolo.com/tutorial/">Tutorial - Guida Utente</a>.
|
||||
|
||||
**Spoiler alert**: il tutorial - Guida Utente include:
|
||||
|
||||
* Dichiarazione di **parameters** da altri posti diversi come: **headers**, **cookies**, **form fields** e **files**.
|
||||
* Come stabilire **vincoli di validazione** come `maximum_length` o `regex`.
|
||||
* Un sistema di **<abbr title="detto anche components, resources, providers, services, injectables">Dependency Injection</abbr>** facile da usare e molto potente.
|
||||
e potente.
|
||||
* Sicurezza e autenticazione, incluso il supporto per **OAuth2** con **token JWT** e autenticazione **HTTP Basic**.
|
||||
* Tecniche più avanzate (ma ugualmente semplici) per dichiarare **modelli JSON altamente nidificati** (grazie a Pydantic).
|
||||
* E altre funzionalità (grazie a Starlette) come:
|
||||
* **WebSockets**
|
||||
* **GraphQL**
|
||||
* test molto facili basati su `requests` e `pytest`
|
||||
* **CORS**
|
||||
* **Cookie Sessions**
|
||||
* ...e altro ancora.
|
||||
|
||||
## Prestazioni
|
||||
|
||||
Benchmark indipendenti di TechEmpower mostrano che **FastAPI** basato su Uvicorn è <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">uno dei framework Python più veloci in circolazione</a>, solamente dietro a Starlette e Uvicorn (usate internamente da FastAPI). (*)
|
||||
|
||||
Per approfondire, consulta la sezione <a href="https://fastapi.tiangolo.com/benchmarks/" class="internal-link" target="_blank">Benchmarks</a>.
|
||||
|
||||
## Dipendenze opzionali
|
||||
|
||||
Usate da Pydantic:
|
||||
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - per un <abbr title="convertire la stringa che proviene da una richiesta HTTP in dati Python">"parsing"</abbr> di JSON più veloce.
|
||||
* <a href="https://github.com/JoshData/python-email-validator" target="_blank"><code>email_validator</code></a> - per la validazione di email.
|
||||
|
||||
Usate da Starlette:
|
||||
|
||||
* <a href="http://docs.python-requests.org" target="_blank"><code>requests</code></a> - Richiesto se vuoi usare il `TestClient`.
|
||||
* <a href="https://github.com/Tinche/aiofiles" target="_blank"><code>aiofiles</code></a> - Richiesto se vuoi usare `FileResponse` o `StaticFiles`.
|
||||
* <a href="http://jinja.pocoo.org" target="_blank"><code>jinja2</code></a> - Richiesto se vuoi usare la configurazione template di default.
|
||||
* <a href="https://andrew-d.github.io/python-multipart/" target="_blank"><code>python-multipart</code></a> - Richiesto se vuoi supportare il <abbr title="convertire la stringa che proviene da una richiesta HTTP in dati Python">"parsing"</abbr> con `request.form()`.
|
||||
* <a href="https://pythonhosted.org/itsdangerous/" target="_blank"><code>itsdangerous</code></a> - Richiesto per usare `SessionMiddleware`.
|
||||
* <a href="https://pyyaml.org/wiki/PyYAMLDocumentation" target="_blank"><code>pyyaml</code></a> - Richiesto per il supporto dello `SchemaGenerator` di Starlette (probabilmente non ti serve con FastAPI).
|
||||
* <a href="https://graphene-python.org/" target="_blank"><code>graphene</code></a> - Richiesto per il supporto di `GraphQLApp`.
|
||||
* <a href="https://github.com/esnme/ultrajson" target="_blank"><code>ujson</code></a> - Richiesto se vuoi usare `UJSONResponse`.
|
||||
|
||||
Usate da FastAPI / Starlette:
|
||||
|
||||
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - per il server che carica e serve la tua applicazione.
|
||||
* <a href="https://github.com/ijl/orjson" target="_blank"><code>orjson</code></a> - ichiesto se vuoi usare `ORJSONResponse`.
|
||||
|
||||
Puoi installarle tutte con `pip install fastapi[all]`.
|
||||
|
||||
## Licenza
|
||||
|
||||
Questo progetto è concesso in licenza in base ai termini della licenza MIT.
|
||||
1
docs/it/mkdocs.yml
Normal file
1
docs/it/mkdocs.yml
Normal file
@@ -0,0 +1 @@
|
||||
INHERIT: ../en/mkdocs.yml
|
||||
315
docs/ja/docs/python-types.md
Normal file
315
docs/ja/docs/python-types.md
Normal file
@@ -0,0 +1,315 @@
|
||||
# Pythonの型の紹介
|
||||
|
||||
**Python 3.6以降** では「型ヒント」オプションがサポートされています。
|
||||
|
||||
これらの **"型ヒント"** は変数の<abbr title="例: str, int, float, bool">型</abbr>を宣言することができる新しい構文です。(Python 3.6以降)
|
||||
|
||||
変数に型を宣言することでエディターやツールがより良いサポートを提供することができます。
|
||||
|
||||
ここではPythonの型ヒントについての **クイックチュートリアル/リフレッシュ** で、**FastAPI**でそれらを使用するために必要な最低限のことだけをカバーしています。...実際には本当に少ないです。
|
||||
|
||||
**FastAPI** はすべてこれらの型ヒントに基づいており、多くの強みと利点を与えてくれます。
|
||||
|
||||
しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。
|
||||
|
||||
!!! note "備考"
|
||||
もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。
|
||||
|
||||
## 動機
|
||||
|
||||
簡単な例から始めてみましょう:
|
||||
|
||||
```Python
|
||||
{!../../../docs_src/python_types/tutorial001.py!}
|
||||
```
|
||||
|
||||
このプログラムを実行すると以下が出力されます:
|
||||
|
||||
```
|
||||
John Doe
|
||||
```
|
||||
|
||||
この関数は以下のようなことを行います:
|
||||
|
||||
* `first_name`と`last_name`を取得します。
|
||||
* `title()`を用いて、それぞれの最初の文字を大文字に変換します。
|
||||
* 真ん中にスペースを入れて<abbr title="次から次へと中身を入れて一つにまとめる">連結</abbr>します。
|
||||
|
||||
```Python hl_lines="2"
|
||||
{!../../../docs_src/python_types/tutorial001.py!}
|
||||
```
|
||||
|
||||
### 編集
|
||||
|
||||
これはとても簡単なプログラムです。
|
||||
|
||||
しかし、今、あなたがそれを一から書いていたと想像してみてください。
|
||||
|
||||
パラメータの準備ができていたら、そのとき、関数の定義を始めていたことでしょう...
|
||||
|
||||
しかし、そうすると「最初の文字を大文字に変換するあのメソッド」を呼び出す必要があります。
|
||||
|
||||
それは`upper`でしたか?`uppercase`でしたか?それとも`first_uppercase`?または`capitalize`?
|
||||
|
||||
そして、古くからプログラマーの友人であるエディタで自動補完を試してみます。
|
||||
|
||||
関数の最初のパラメータ`first_name`を入力し、ドット(`.`)を入力してから、`Ctrl+Space`を押すと補完が実行されます。
|
||||
|
||||
しかし、悲しいことに、これはなんの役にも立ちません:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/python-types/image01.png">
|
||||
|
||||
### 型の追加
|
||||
|
||||
先ほどのコードから一行変更してみましょう。
|
||||
|
||||
以下の関数のパラメータ部分を:
|
||||
|
||||
```Python
|
||||
first_name, last_name
|
||||
```
|
||||
|
||||
以下へ変更します:
|
||||
|
||||
```Python
|
||||
first_name: str, last_name: str
|
||||
```
|
||||
|
||||
これだけです。
|
||||
|
||||
それが「型ヒント」です:
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!../../../docs_src/python_types/tutorial002.py!}
|
||||
```
|
||||
|
||||
これは、以下のようにデフォルト値を宣言するのと同じではありません:
|
||||
|
||||
```Python
|
||||
first_name="john", last_name="doe"
|
||||
```
|
||||
|
||||
それとは別物です。
|
||||
|
||||
イコール(`=`)ではなく、コロン(`:`)を使用します。
|
||||
|
||||
そして、通常、型ヒントを追加しても、それらがない状態と起こることは何も変わりません。
|
||||
|
||||
しかし今、あなたが再びその関数を作成している最中に、型ヒントを使っていると想像してみて下さい。
|
||||
|
||||
同じタイミングで`Ctrl+Space`で自動補完を実行すると、以下のようになります:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/python-types/image02.png">
|
||||
|
||||
これであれば、あなたは「ベルを鳴らす」一つを見つけるまで、オプションを見て、スクロールすることができます:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/python-types/image03.png">
|
||||
|
||||
## より強い動機
|
||||
|
||||
この関数を見てください。すでに型ヒントを持っています:
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!../../../docs_src/python_types/tutorial003.py!}
|
||||
```
|
||||
|
||||
エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/python-types/image04.png">
|
||||
|
||||
これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります:
|
||||
|
||||
```Python hl_lines="2"
|
||||
{!../../../docs_src/python_types/tutorial004.py!}
|
||||
```
|
||||
|
||||
## 型の宣言
|
||||
|
||||
関数のパラメータとして、型ヒントを宣言している主な場所を確認しました。
|
||||
|
||||
これは **FastAPI** で使用する主な場所でもあります。
|
||||
|
||||
### 単純な型
|
||||
|
||||
`str`だけでなく、Pythonの標準的な型すべてを宣言することができます。
|
||||
|
||||
例えば、以下を使用可能です:
|
||||
|
||||
* `int`
|
||||
* `float`
|
||||
* `bool`
|
||||
* `bytes`
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!../../../docs_src/python_types/tutorial005.py!}
|
||||
```
|
||||
|
||||
### 型パラメータを持つジェネリック型
|
||||
|
||||
データ構造の中には、`dict`、`list`、`set`、そして`tuple`のように他の値を含むことができるものがあります。また内部の値も独自の型を持つことができます。
|
||||
|
||||
これらの型や内部の型を宣言するには、Pythonの標準モジュール`typing`を使用します。
|
||||
|
||||
これらの型ヒントをサポートするために特別に存在しています。
|
||||
|
||||
#### `List`
|
||||
|
||||
例えば、`str`の`list`の変数を定義してみましょう。
|
||||
|
||||
`typing`から`List`をインポートします(大文字の`L`を含む):
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!../../../docs_src/python_types/tutorial006.py!}
|
||||
```
|
||||
|
||||
同じようにコロン(`:`)の構文で変数を宣言します。
|
||||
|
||||
型として、`List`を入力します。
|
||||
|
||||
リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!../../../docs_src/python_types/tutorial006.py!}
|
||||
```
|
||||
|
||||
!!! tip "豆知識"
|
||||
角括弧内の内部の型は「型パラメータ」と呼ばれています。
|
||||
|
||||
この場合、`str`は`List`に渡される型パラメータです。
|
||||
|
||||
つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。
|
||||
|
||||
そうすることで、エディタはリストの項目を処理している間にもサポートを提供できます。
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/python-types/image05.png">
|
||||
|
||||
タイプがなければ、それはほぼ不可能です。
|
||||
|
||||
変数`item`はリスト`items`の要素の一つであることに注意してください。
|
||||
|
||||
それでも、エディタはそれが`str`であることを知っていて、そのためのサポートを提供しています。
|
||||
|
||||
#### `Tuple` と `Set`
|
||||
|
||||
`tuple`と`set`の宣言も同様です:
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!../../../docs_src/python_types/tutorial007.py!}
|
||||
```
|
||||
|
||||
つまり:
|
||||
|
||||
* 変数`items_t`は`int`、`int`、`str`の3つの項目を持つ`tuple`です
|
||||
|
||||
* 変数`items_s`はそれぞれの項目が`bytes`型である`set`です。
|
||||
|
||||
#### `Dict`
|
||||
|
||||
`dict`を宣言するためには、カンマ区切りで2つの型パラメータを渡します。
|
||||
|
||||
最初の型パラメータは`dict`のキーです。
|
||||
|
||||
2番目の型パラメータは`dict`の値です。
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!../../../docs_src/python_types/tutorial008.py!}
|
||||
```
|
||||
|
||||
つまり:
|
||||
|
||||
* 変数`prices`は`dict`であり:
|
||||
* この`dict`のキーは`str`型です。(つまり、各項目の名前)
|
||||
* この`dict`の値は`float`型です。(つまり、各項目の価格)
|
||||
|
||||
#### `Optional`
|
||||
|
||||
また、`Optional`を使用して、変数が`str`のような型を持つことを宣言することもできますが、それは「オプション」であり、`None`にすることもできます。
|
||||
|
||||
```Python hl_lines="1 4"
|
||||
{!../../../docs_src/python_types/tutorial009.py!}
|
||||
```
|
||||
|
||||
ただの`str`の代わりに`Optional[str]`を使用することで、エディタは値が常に`str`であると仮定している場合に実際には`None`である可能性があるエラーを検出するのに役立ちます。
|
||||
|
||||
#### ジェネリック型
|
||||
|
||||
以下のように角括弧で型パラメータを取る型を:
|
||||
|
||||
* `List`
|
||||
* `Tuple`
|
||||
* `Set`
|
||||
* `Dict`
|
||||
* `Optional`
|
||||
* ...など
|
||||
|
||||
**ジェネリック型** または **ジェネリクス** と呼びます。
|
||||
|
||||
### 型としてのクラス
|
||||
|
||||
変数の型としてクラスを宣言することもできます。
|
||||
|
||||
例えば、`Person`クラスという名前のクラスがあるとしましょう:
|
||||
|
||||
```Python hl_lines="1 2 3"
|
||||
{!../../../docs_src/python_types/tutorial010.py!}
|
||||
```
|
||||
|
||||
変数の型を`Person`として宣言することができます:
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!../../../docs_src/python_types/tutorial010.py!}
|
||||
```
|
||||
|
||||
そして、再び、すべてのエディタのサポートを得ることができます:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/python-types/image06.png">
|
||||
|
||||
## Pydanticのモデル
|
||||
|
||||
<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> はデータ検証を行うためのPythonライブラリです。
|
||||
|
||||
データの「形」を属性付きのクラスとして宣言します。
|
||||
|
||||
そして、それぞれの属性は型を持ちます。
|
||||
|
||||
さらに、いくつかの値を持つクラスのインスタンスを作成すると、その値を検証し、適切な型に変換して(もしそうであれば)全てのデータを持つオブジェクトを提供してくれます。
|
||||
|
||||
また、その結果のオブジェクトですべてのエディタのサポートを受けることができます。
|
||||
|
||||
Pydanticの公式ドキュメントから引用:
|
||||
|
||||
```Python
|
||||
{!../../../docs_src/python_types/tutorial011.py!}
|
||||
```
|
||||
|
||||
!!! info "情報"
|
||||
Pydanticについてより学びたい方は<a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">ドキュメントを参照してください</a>.
|
||||
|
||||
**FastAPI** はすべてPydanticをベースにしています。
|
||||
|
||||
すべてのことは[チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で実際に見ることができます。
|
||||
|
||||
## **FastAPI**での型ヒント
|
||||
|
||||
**FastAPI** はこれらの型ヒントを利用していくつかのことを行います。
|
||||
|
||||
**FastAPI** では型ヒントを使って型パラメータを宣言すると以下のものが得られます:
|
||||
|
||||
* **エディタサポート**.
|
||||
* **型チェック**.
|
||||
|
||||
...そして **FastAPI** は同じように宣言をすると、以下のことを行います:
|
||||
|
||||
* **要件の定義**: リクエストパスパラメータ、クエリパラメータ、ヘッダー、ボディ、依存関係などから要件を定義します。
|
||||
* **データの変換**: リクエストのデータを必要な型に変換します。
|
||||
* **データの検証**: リクエストごとに:
|
||||
* データが無効な場合にクライアントに返される **自動エラー** を生成します。
|
||||
* **ドキュメント** OpenAPIを使用したAPI:
|
||||
* 自動的に対話型ドキュメントのユーザーインターフェイスで使用されます。
|
||||
|
||||
すべてが抽象的に聞こえるかもしれません。心配しないでください。 この全ての動作は [チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で見ることができます。
|
||||
|
||||
重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。
|
||||
|
||||
!!! info "情報"
|
||||
すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、<a href="https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html" class="external-link" target="_blank">`mypy`のチートシートを参照してください</a>
|
||||
94
docs/ja/docs/tutorial/background-tasks.md
Normal file
94
docs/ja/docs/tutorial/background-tasks.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# バックグラウンドタスク
|
||||
|
||||
レスポンスを返した *後に* 実行されるバックグラウンドタスクを定義できます。
|
||||
|
||||
これは、リクエスト後に処理を開始する必要があるが、クライアントがレスポンスを受け取る前に処理を終える必要のない操作に役立ちます。
|
||||
|
||||
これには、たとえば次のものが含まれます。
|
||||
|
||||
* 作業実行後のメール通知:
|
||||
* メールサーバーへの接続とメールの送信は「遅い」(数秒) 傾向があるため、すぐにレスポンスを返し、バックグラウンドでメール通知ができます。
|
||||
* データ処理:
|
||||
* たとえば、時間のかかる処理を必要とするファイル受信時には、「受信済み」(HTTP 202) のレスポンスを返し、バックグラウンドで処理できます。
|
||||
|
||||
## `BackgroundTasks` の使用
|
||||
|
||||
まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します:
|
||||
|
||||
```Python hl_lines="1 13"
|
||||
{!../../../docs_src/background_tasks/tutorial001.py!}
|
||||
```
|
||||
|
||||
**FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。
|
||||
|
||||
## タスク関数の作成
|
||||
|
||||
バックグラウンドタスクとして実行される関数を作成します。
|
||||
|
||||
これは、パラメーターを受け取ることができる単なる標準的な関数です。
|
||||
|
||||
これは `async def` または通常の `def` 関数であり、**FastAPI** はこれを正しく処理します。
|
||||
|
||||
ここで、タスク関数はファイル書き込みを実行します (メール送信のシミュレーション)。
|
||||
|
||||
また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。
|
||||
|
||||
```Python hl_lines="6-9"
|
||||
{!../../../docs_src/background_tasks/tutorial001.py!}
|
||||
```
|
||||
|
||||
## バックグラウンドタスクの追加
|
||||
|
||||
*path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!../../../docs_src/background_tasks/tutorial001.py!}
|
||||
```
|
||||
|
||||
`.add_task()` は以下の引数を受け取ります:
|
||||
|
||||
* バックグラウンドで実行されるタスク関数 (`write_notification`)。
|
||||
* タスク関数に順番に渡す必要のある引数の列 (`email`)。
|
||||
* タスク関数に渡す必要のあるキーワード引数 (`message="some notification"`)。
|
||||
|
||||
## 依存性注入
|
||||
|
||||
`BackgroundTasks` の使用は依存性注入システムでも機能し、様々な階層 (*path operations 関数*、依存性 (依存可能性)、サブ依存性など) で `BackgroundTasks` 型のパラメーターを宣言できます。
|
||||
|
||||
**FastAPI** は、それぞれの場合の処理方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。
|
||||
|
||||
```Python hl_lines="13 15 22 25"
|
||||
{!../../../docs_src/background_tasks/tutorial002.py!}
|
||||
```
|
||||
|
||||
この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。
|
||||
|
||||
リクエストにクエリがあった場合、バックグラウンドタスクでログに書き込まれます。
|
||||
|
||||
そして、*path operations 関数* で生成された別のバックグラウンドタスクは、`email` パスパラメータを使用してメッセージを書き込みます。
|
||||
|
||||
## 技術的な詳細
|
||||
|
||||
`BackgroundTasks` クラスは、<a href="https://www.starlette.io/background/" class="external-link" target="_blank">`starlette.background`</a>から直接取得されます。
|
||||
|
||||
これは、FastAPI に直接インポート/インクルードされるため、`fastapi` からインポートできる上に、`starlette.background`から別の `BackgroundTask` (末尾に `s` がない) を誤ってインポートすることを回避できます。
|
||||
|
||||
`BackgroundTasks`のみを使用することで (`BackgroundTask` ではなく)、`Request` オブジェクトを直接使用する場合と同様に、それを *path operations 関数* パラメーターとして使用し、**FastAPI** に残りの処理を任せることができます。
|
||||
|
||||
それでも、FastAPI で `BackgroundTask` を単独で使用することは可能ですが、コード内でオブジェクトを作成し、それを含むStarlette `Response` を返す必要があります。
|
||||
|
||||
詳細については、<a href="https://www.starlette.io/background/" class="external-link" target="_blank">バックグラウンドタスクに関する Starlette の公式ドキュメント</a>を参照して下さい。
|
||||
|
||||
## 警告
|
||||
|
||||
大量のバックグラウンド計算が必要であり、必ずしも同じプロセスで実行する必要がない場合 (たとえば、メモリや変数などを共有する必要がない場合)、<a href="https://www.celeryproject.org/" class="external-link" target="_blank">Celery</a> のようなより大きな他のツールを使用するとメリットがあるかもしれません。
|
||||
|
||||
これらは、より複雑な構成、RabbitMQ や Redis などのメッセージ/ジョブキューマネージャーを必要とする傾向がありますが、複数のプロセス、特に複数のサーバーでバックグラウンドタスクを実行できます。
|
||||
|
||||
例を確認するには、[Project Generators](../project-generation.md){.internal-link target=_blank} を参照してください。これらにはすべて、Celery が構築済みです。
|
||||
|
||||
ただし、同じ **FastAPI** アプリから変数とオブジェクトにアクセスする必要がある場合、または小さなバックグラウンドタスク (電子メール通知の送信など) を実行する必要がある場合は、単に `BackgroundTasks` を使用できます。
|
||||
|
||||
## まとめ
|
||||
|
||||
`BackgroundTasks` をインポートして、*path operations 関数* や依存関係のパラメータに `BackgroundTasks`を使用し、バックグラウンドタスクを追加して下さい。
|
||||
48
docs/ja/docs/tutorial/body-fields.md
Normal file
48
docs/ja/docs/tutorial/body-fields.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# ボディ - フィールド
|
||||
|
||||
`Query`や`Path`、`Body`を使って *path operation関数* のパラメータに追加のバリデーションやメタデータを宣言するのと同じように、Pydanticの`Field`を使ってPydanticモデルの内部でバリデーションやメタデータを宣言することができます。
|
||||
|
||||
## `Field`のインポート
|
||||
|
||||
まず、以下のようにインポートします:
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!../../../docs_src/body_fields/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! warning "注意"
|
||||
`Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。
|
||||
|
||||
## モデルの属性の宣言
|
||||
|
||||
以下のように`Field`をモデルの属性として使用することができます:
|
||||
|
||||
```Python hl_lines="11 12 13 14"
|
||||
{!../../../docs_src/body_fields/tutorial001.py!}
|
||||
```
|
||||
|
||||
`Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。
|
||||
|
||||
!!! note "技術詳細"
|
||||
実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。
|
||||
|
||||
また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。
|
||||
|
||||
`Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。
|
||||
|
||||
`fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。
|
||||
|
||||
!!! tip "豆知識"
|
||||
型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。
|
||||
|
||||
## 追加情報の追加
|
||||
|
||||
追加情報は`Field`や`Query`、`Body`などで宣言することができます。そしてそれは生成されたJSONスキーマに含まれます。
|
||||
|
||||
後に例を用いて宣言を学ぶ際に、追加情報を句悪方法を学べます。
|
||||
|
||||
## まとめ
|
||||
|
||||
Pydanticの`Field`を使用して、モデルの属性に追加のバリデーションやメタデータを宣言することができます。
|
||||
|
||||
追加のキーワード引数を使用して、追加のJSONスキーマのメタデータを渡すこともできます。
|
||||
169
docs/ja/docs/tutorial/body-multiple-params.md
Normal file
169
docs/ja/docs/tutorial/body-multiple-params.md
Normal file
@@ -0,0 +1,169 @@
|
||||
# ボディ - 複数のパラメータ
|
||||
|
||||
これまで`Path`と`Query`をどう使うかを見てきましたが、リクエストボディの宣言のより高度な使い方を見てみましょう。
|
||||
|
||||
## `Path`、`Query`とボディパラメータを混ぜる
|
||||
|
||||
まず、もちろん、`Path`と`Query`とリクエストボディのパラメータの宣言は自由に混ぜることができ、 **FastAPI** は何をするべきかを知っています。
|
||||
|
||||
また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます:
|
||||
|
||||
```Python hl_lines="19 20 21"
|
||||
{!../../../docs_src/body_multiple_params/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "備考"
|
||||
この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。
|
||||
|
||||
## 複数のボディパラメータ
|
||||
|
||||
上述の例では、*path operations*は`item`の属性を持つ以下のようなJSONボディを期待していました:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"name": "Foo",
|
||||
"description": "The pretender",
|
||||
"price": 42.0,
|
||||
"tax": 3.2
|
||||
}
|
||||
```
|
||||
|
||||
しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます:
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!../../../docs_src/body_multiple_params/tutorial002.py!}
|
||||
```
|
||||
|
||||
この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。
|
||||
|
||||
そのため、パラメータ名をボディのキー(フィールド名)として使用し、以下のようなボディを期待しています:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"item": {
|
||||
"name": "Foo",
|
||||
"description": "The pretender",
|
||||
"price": 42.0,
|
||||
"tax": 3.2
|
||||
},
|
||||
"user": {
|
||||
"username": "dave",
|
||||
"full_name": "Dave Grohl"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
!!! note "備考"
|
||||
以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。
|
||||
|
||||
**FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。
|
||||
|
||||
複合データの検証を行い、OpenAPIスキーマや自動ドキュメントのように文書化してくれます。
|
||||
|
||||
## ボディ内の単数値
|
||||
|
||||
クエリとパスパラメータの追加データを定義するための `Query` と `Path` があるのと同じように、 **FastAPI** は同等の `Body` を提供します。
|
||||
|
||||
例えば、前のモデルを拡張して、同じボディに `item` と `user` の他にもう一つのキー `importance` を入れたいと決めることができます。
|
||||
|
||||
単数値なのでそのまま宣言すると、**FastAPI** はそれがクエリパラメータであるとみなします。
|
||||
|
||||
しかし、`Body`を使用して、**FastAPI** に別のボディキーとして扱うように指示することができます:
|
||||
|
||||
|
||||
```Python hl_lines="23"
|
||||
{!../../../docs_src/body_multiple_params/tutorial003.py!}
|
||||
```
|
||||
|
||||
この場合、**FastAPI** は以下のようなボディを期待します:
|
||||
|
||||
|
||||
```JSON
|
||||
{
|
||||
"item": {
|
||||
"name": "Foo",
|
||||
"description": "The pretender",
|
||||
"price": 42.0,
|
||||
"tax": 3.2
|
||||
},
|
||||
"user": {
|
||||
"username": "dave",
|
||||
"full_name": "Dave Grohl"
|
||||
},
|
||||
"importance": 5
|
||||
}
|
||||
```
|
||||
|
||||
繰り返しになりますが、データ型の変換、検証、文書化などを行います。
|
||||
|
||||
## 複数のボディパラメータとクエリ
|
||||
|
||||
もちろん、ボディパラメータに加えて、必要に応じて追加のクエリパラメータを宣言することもできます。
|
||||
|
||||
デフォルトでは、単数値はクエリパラメータとして解釈されるので、明示的に `Query` を追加する必要はありません。
|
||||
|
||||
```Python
|
||||
q: str = None
|
||||
```
|
||||
|
||||
以下において:
|
||||
|
||||
```Python hl_lines="27"
|
||||
{!../../../docs_src/body_multiple_params/tutorial004.py!}
|
||||
```
|
||||
|
||||
!!! info "情報"
|
||||
`Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。
|
||||
|
||||
|
||||
## 単一のボディパラメータの埋め込み
|
||||
|
||||
Pydanticモデル`Item`のボディパラメータ`item`を1つだけ持っているとしましょう。
|
||||
|
||||
デフォルトでは、**FastAPI**はそのボディを直接期待します。
|
||||
|
||||
しかし、追加のボディパラメータを宣言したときのように、キー `item` を持つ JSON とその中のモデルの内容を期待したい場合は、特別な `Body` パラメータ `embed` を使うことができます:
|
||||
|
||||
```Python
|
||||
item: Item = Body(..., embed=True)
|
||||
```
|
||||
|
||||
以下において:
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!../../../docs_src/body_multiple_params/tutorial005.py!}
|
||||
```
|
||||
|
||||
この場合、**FastAPI** は以下のようなボディを期待します:
|
||||
|
||||
```JSON hl_lines="2"
|
||||
{
|
||||
"item": {
|
||||
"name": "Foo",
|
||||
"description": "The pretender",
|
||||
"price": 42.0,
|
||||
"tax": 3.2
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
以下の代わりに:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"name": "Foo",
|
||||
"description": "The pretender",
|
||||
"price": 42.0,
|
||||
"tax": 3.2
|
||||
}
|
||||
```
|
||||
|
||||
## まとめ
|
||||
|
||||
リクエストが単一のボディしか持てない場合でも、*path operation関数*に複数のボディパラメータを追加することができます。
|
||||
|
||||
しかし、**FastAPI** はそれを処理し、関数内の正しいデータを与え、*path operation*内の正しいスキーマを検証し、文書化します。
|
||||
|
||||
また、ボディの一部として受け取る単数値を宣言することもできます。
|
||||
|
||||
また、単一のパラメータしか宣言されていない場合でも、ボディをキーに埋め込むように **FastAPI** に指示することができます。
|
||||
244
docs/ja/docs/tutorial/body-nested-models.md
Normal file
244
docs/ja/docs/tutorial/body-nested-models.md
Normal file
@@ -0,0 +1,244 @@
|
||||
# ボディ - ネストされたモデル
|
||||
|
||||
**FastAPI** を使用すると、深くネストされた任意のモデルを定義、検証、文書化、使用することができます(Pydanticのおかげです)。
|
||||
|
||||
## リストのフィールド
|
||||
|
||||
属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます:
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!../../../docs_src/body_nested_models/tutorial001.py!}
|
||||
```
|
||||
|
||||
これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。
|
||||
|
||||
## タイプパラメータを持つリストのフィールド
|
||||
|
||||
しかし、Pythonには型や「タイプパラメータ」を使ってリストを宣言する方法があります:
|
||||
|
||||
### typingの`List`をインポート
|
||||
|
||||
まず、Pythonの標準の`typing`モジュールから`List`をインポートします:
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!../../../docs_src/body_nested_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
### タイプパラメータを持つ`List`の宣言
|
||||
|
||||
`list`や`dict`、`tuple`のようなタイプパラメータ(内部の型)を持つ型を宣言するには:
|
||||
|
||||
* `typing`モジュールからそれらをインストールします。
|
||||
* 角括弧(`[`と`]`)を使って「タイプパラメータ」として内部の型を渡します:
|
||||
|
||||
```Python
|
||||
from typing import List
|
||||
|
||||
my_list: List[str]
|
||||
```
|
||||
|
||||
型宣言の標準的なPythonの構文はこれだけです。
|
||||
|
||||
内部の型を持つモデルの属性にも同じ標準の構文を使用してください。
|
||||
|
||||
そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます:
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!../../../docs_src/body_nested_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
## セット型
|
||||
|
||||
しかし、よく考えてみると、タグは繰り返すべきではなく、おそらくユニークな文字列になるのではないかと気付いたとします。
|
||||
|
||||
そして、Pythonにはユニークな項目のセットのための特別なデータ型`set`があります。
|
||||
|
||||
そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます:
|
||||
|
||||
```Python hl_lines="1 14"
|
||||
{!../../../docs_src/body_nested_models/tutorial003.py!}
|
||||
```
|
||||
|
||||
これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。
|
||||
|
||||
そして、そのデータを出力すると、たとえソースに重複があったとしても、固有の項目のセットとして出力されます。
|
||||
|
||||
また、それに応じて注釈をつけたり、文書化したりします。
|
||||
|
||||
## ネストされたモデル
|
||||
|
||||
Pydanticモデルの各属性には型があります。
|
||||
|
||||
しかし、その型はそれ自体が別のPydanticモデルである可能性があります。
|
||||
|
||||
そのため、特定の属性名、型、バリデーションを指定して、深くネストしたJSON`object`を宣言することができます。
|
||||
|
||||
すべては、任意のネストにされています。
|
||||
|
||||
### サブモデルの定義
|
||||
|
||||
例えば、`Image`モデルを定義することができます:
|
||||
|
||||
```Python hl_lines="9 10 11"
|
||||
{!../../../docs_src/body_nested_models/tutorial004.py!}
|
||||
```
|
||||
|
||||
### サブモデルを型として使用
|
||||
|
||||
そして、それを属性の型として使用することができます:
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!../../../docs_src/body_nested_models/tutorial004.py!}
|
||||
```
|
||||
|
||||
これは **FastAPI** が以下のようなボディを期待することを意味します:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"name": "Foo",
|
||||
"description": "The pretender",
|
||||
"price": 42.0,
|
||||
"tax": 3.2,
|
||||
"tags": ["rock", "metal", "bar"],
|
||||
"image": {
|
||||
"url": "http://example.com/baz.jpg",
|
||||
"name": "The Foo live"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
繰り返しになりますが、**FastAPI** を使用して、その宣言を行うだけで以下のような恩恵を受けられます:
|
||||
|
||||
* ネストされたモデルでも対応可能なエディタのサポート(補完など)
|
||||
* データ変換
|
||||
* データの検証
|
||||
* 自動文書化
|
||||
|
||||
## 特殊な型とバリデーション
|
||||
|
||||
`str`や`int`、`float`のような通常の単数型の他にも、`str`を継承したより複雑な単数型を使うこともできます。
|
||||
|
||||
すべてのオプションをみるには、<a href="https://pydantic-docs.helpmanual.io/usage/types/" class="external-link" target="_blank">Pydanticのエキゾチック な型</a>のドキュメントを確認してください。次の章でいくつかの例をみることができます。
|
||||
|
||||
例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます:
|
||||
|
||||
```Python hl_lines="4 10"
|
||||
{!../../../docs_src/body_nested_models/tutorial005.py!}
|
||||
```
|
||||
|
||||
文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。
|
||||
|
||||
## サブモデルのリストを持つ属性
|
||||
|
||||
Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます:
|
||||
|
||||
```Python hl_lines="20"
|
||||
{!../../../docs_src/body_nested_models/tutorial006.py!}
|
||||
```
|
||||
|
||||
これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど):
|
||||
|
||||
```JSON hl_lines="11"
|
||||
{
|
||||
"name": "Foo",
|
||||
"description": "The pretender",
|
||||
"price": 42.0,
|
||||
"tax": 3.2,
|
||||
"tags": [
|
||||
"rock",
|
||||
"metal",
|
||||
"bar"
|
||||
],
|
||||
"images": [
|
||||
{
|
||||
"url": "http://example.com/baz.jpg",
|
||||
"name": "The Foo live"
|
||||
},
|
||||
{
|
||||
"url": "http://example.com/dave.jpg",
|
||||
"name": "The Baz"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
!!! info "情報"
|
||||
`images`キーが画像オブジェクトのリストを持つようになったことに注目してください。
|
||||
|
||||
## 深くネストされたモデル
|
||||
|
||||
深くネストされた任意のモデルを定義することができます:
|
||||
|
||||
```Python hl_lines="9 14 20 23 27"
|
||||
{!../../../docs_src/body_nested_models/tutorial007.py!}
|
||||
```
|
||||
|
||||
!!! info "情報"
|
||||
`Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。
|
||||
|
||||
## 純粋なリストのボディ
|
||||
|
||||
期待するJSONボディのトップレベルの値がJSON`array`(Pythonの`list`)であれば、Pydanticモデルと同じように、関数のパラメータで型を宣言することができます:
|
||||
|
||||
```Python
|
||||
images: List[Image]
|
||||
```
|
||||
|
||||
以下のように:
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!../../../docs_src/body_nested_models/tutorial008.py!}
|
||||
```
|
||||
|
||||
## あらゆる場所でのエディタサポート
|
||||
|
||||
エディタのサポートもどこでも受けることができます。
|
||||
|
||||
以下のようにリストの中の項目でも:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/tutorial/body-nested-models/image01.png">
|
||||
|
||||
Pydanticモデルではなく、`dict`を直接使用している場合はこのようなエディタのサポートは得られません。
|
||||
|
||||
しかし、それらについて心配する必要はありません。入力された辞書は自動的に変換され、出力も自動的にJSONに変換されます。
|
||||
|
||||
## 任意の`dict`のボディ
|
||||
|
||||
また、ある型のキーと別の型の値を持つ`dict`としてボディを宣言することもできます。
|
||||
|
||||
有効なフィールド・属性名を事前に知る必要がありません(Pydanticモデルの場合のように)。
|
||||
|
||||
これは、まだ知らないキーを受け取りたいときに便利だと思います。
|
||||
|
||||
---
|
||||
|
||||
他にも、`int`のように他の型のキーを持ちたい場合などに便利です。
|
||||
|
||||
それをここで見ていきましょう。
|
||||
|
||||
この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます:
|
||||
|
||||
```Python hl_lines="15"
|
||||
{!../../../docs_src/body_nested_models/tutorial009.py!}
|
||||
```
|
||||
|
||||
!!! tip "豆知識"
|
||||
JSONはキーとして`str`しかサポートしていないことに注意してください。
|
||||
|
||||
しかしPydanticには自動データ変換機能があります。
|
||||
|
||||
これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。
|
||||
|
||||
そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。
|
||||
|
||||
## まとめ
|
||||
|
||||
**FastAPI** を使用すると、Pydanticモデルが提供する最大限の柔軟性を持ちながら、コードをシンプルに短く、エレガントに保つことができます。
|
||||
|
||||
以下のような利点があります:
|
||||
|
||||
* エディタのサポート(どこでも補完!)
|
||||
* データ変換(別名:構文解析・シリアライズ)
|
||||
* データの検証
|
||||
* スキーマ文書
|
||||
* 自動文書化
|
||||
191
docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md
Normal file
191
docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md
Normal file
@@ -0,0 +1,191 @@
|
||||
# 依存関係としてのクラス
|
||||
|
||||
**依存性注入** システムを深く掘り下げる前に、先ほどの例をアップグレードしてみましょう。
|
||||
|
||||
## 前の例の`dict`
|
||||
|
||||
前の例では、依存関係("dependable")から`dict`を返していました:
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。
|
||||
|
||||
また、エディタは`dict`のキーと値の型を知ることができないため、多くのサポート(補完のような)を提供することができません。
|
||||
|
||||
もっとうまくやれるはずです...。
|
||||
|
||||
## 依存関係を作るもの
|
||||
|
||||
これまでは、依存関係が関数として宣言されているのを見てきました。
|
||||
|
||||
しかし、依存関係を定義する方法はそれだけではありません(その方が一般的かもしれませんが)。
|
||||
|
||||
重要なのは、依存関係が「呼び出し可能」なものであることです。
|
||||
|
||||
Pythonにおける「**呼び出し可能**」とは、Pythonが関数のように「呼び出す」ことができるものを指します。
|
||||
|
||||
そのため、`something`オブジェクト(関数ではないかもしれませんが)を持っていて、それを次のように「呼び出す」(実行する)ことができるとします:
|
||||
|
||||
```Python
|
||||
something()
|
||||
```
|
||||
|
||||
または
|
||||
|
||||
```Python
|
||||
something(some_argument, some_keyword_argument="foo")
|
||||
```
|
||||
|
||||
これを「呼び出し可能」なものと呼びます。
|
||||
|
||||
## 依存関係としてのクラス
|
||||
|
||||
Pythonのクラスのインスタンスを作成する際に、同じ構文を使用していることに気づくかもしれません。
|
||||
|
||||
例えば:
|
||||
|
||||
```Python
|
||||
class Cat:
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
|
||||
|
||||
fluffy = Cat(name="Mr Fluffy")
|
||||
```
|
||||
|
||||
この場合、`fluffy`は`Cat`クラスのインスタンスです。
|
||||
|
||||
そして`fluffy`を作成するために、`Cat`を「呼び出している」ことになります。
|
||||
|
||||
そのため、Pythonのクラスもまた「呼び出し可能」です。
|
||||
|
||||
そして、**FastAPI** では、Pythonのクラスを依存関係として使用することができます。
|
||||
|
||||
FastAPIが実際にチェックしているのは、それが「呼び出し可能」(関数、クラス、その他なんでも)であり、パラメータが定義されているかどうかということです。
|
||||
|
||||
**FastAPI** の依存関係として「呼び出し可能なもの」を渡すと、その「呼び出し可能なもの」のパラメータを解析し、サブ依存関係も含めて、*path operation関数*のパラメータと同じように処理します。
|
||||
|
||||
それは、パラメータが全くない呼び出し可能なものにも適用されます。パラメータのない*path operation関数*と同じように。
|
||||
|
||||
そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します:
|
||||
|
||||
```Python hl_lines="11 12 13 14 15"
|
||||
{!../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください:
|
||||
|
||||
```Python hl_lines="12"
|
||||
{!../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
...以前の`common_parameters`と同じパラメータを持っています:
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。
|
||||
|
||||
どちらの場合も以下を持っています:
|
||||
|
||||
* オプショナルの`q`クエリパラメータ。
|
||||
* `skip`クエリパラメータ、デフォルトは`0`。
|
||||
* `limit`クエリパラメータ、デフォルトは`100`。
|
||||
|
||||
どちらの場合も、データは変換され、検証され、OpenAPIスキーマなどで文書化されます。
|
||||
|
||||
## 使用
|
||||
|
||||
これで、このクラスを使用して依存関係を宣言することができます。
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!../../../docs_src/dependencies/tutorial002.py!}
|
||||
```
|
||||
|
||||
**FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。
|
||||
|
||||
## 型注釈と`Depends`
|
||||
|
||||
上のコードでは`CommonQueryParams`を2回書いていることに注目してください:
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
以下にある最後の`CommonQueryParams`:
|
||||
|
||||
```Python
|
||||
... = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
...は、**FastAPI** が依存関係を知るために実際に使用するものです。
|
||||
|
||||
そこからFastAPIが宣言されたパラメータを抽出し、それが実際にFastAPIが呼び出すものです。
|
||||
|
||||
---
|
||||
|
||||
この場合、以下にある最初の`CommonQueryParams`:
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams ...
|
||||
```
|
||||
|
||||
...は **FastAPI** に対して特別な意味をもちません。FastAPIはデータ変換や検証などには使用しません(それらのためには`= Depends(CommonQueryParams)`を使用しています)。
|
||||
|
||||
実際には以下のように書けばいいだけです:
|
||||
|
||||
```Python
|
||||
commons = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
以下にあるように:
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!../../../docs_src/dependencies/tutorial003.py!}
|
||||
```
|
||||
|
||||
しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/tutorial/dependencies/image02.png">
|
||||
|
||||
## ショートカット
|
||||
|
||||
しかし、ここでは`CommonQueryParams`を2回書くというコードの繰り返しが発生していることがわかります:
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
依存関係が、クラス自体のインスタンスを作成するために**FastAPI**が「呼び出す」*特定の*クラスである場合、**FastAPI** はこれらのケースのショートカットを提供しています。
|
||||
|
||||
それらの具体的なケースについては以下のようにします:
|
||||
|
||||
以下のように書く代わりに:
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends(CommonQueryParams)
|
||||
```
|
||||
|
||||
...以下のように書きます:
|
||||
|
||||
```Python
|
||||
commons: CommonQueryParams = Depends()
|
||||
```
|
||||
|
||||
パラメータの型として依存関係を宣言し、`Depends()`の中でパラメータを指定せず、`Depends()`をその関数のパラメータの「デフォルト」値(`=`のあとの値)として使用することで、`Depends(CommonQueryParams)`の中でクラス全体を*もう一度*書かなくてもよくなります。
|
||||
|
||||
同じ例では以下のようになります:
|
||||
|
||||
```Python hl_lines="19"
|
||||
{!../../../docs_src/dependencies/tutorial004.py!}
|
||||
```
|
||||
|
||||
...そして **FastAPI** は何をすべきか知っています。
|
||||
|
||||
!!! tip "豆知識"
|
||||
役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。
|
||||
|
||||
それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。
|
||||
@@ -0,0 +1,62 @@
|
||||
# path operationデコレータの依存関係
|
||||
|
||||
場合によっては*path operation関数*の中で依存関係の戻り値を本当に必要としないこともあります。
|
||||
|
||||
もしくは、依存関係が値を返さない場合もあります。
|
||||
|
||||
しかし、それでも実行・解決する必要があります。
|
||||
|
||||
このような場合、*path operation関数*のパラメータを`Depends`で宣言する代わりに、*path operation decorator*に`dependencies`の`list`を追加することができます。
|
||||
|
||||
## *path operationデコレータ*への`dependencies`の追加
|
||||
|
||||
*path operationデコレータ*はオプショナルの引数`dependencies`を受け取ります。
|
||||
|
||||
それは`Depends()`の`list`であるべきです:
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。
|
||||
|
||||
!!! tip "豆知識"
|
||||
エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。
|
||||
|
||||
`dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。
|
||||
|
||||
また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。
|
||||
|
||||
## 依存関係のエラーと戻り値
|
||||
|
||||
通常使用している依存関係の*関数*と同じものを使用することができます。
|
||||
|
||||
### 依存関係の要件
|
||||
|
||||
これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます:
|
||||
|
||||
```Python hl_lines="6 11"
|
||||
{!../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
### 例外の発生
|
||||
|
||||
これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます:
|
||||
|
||||
```Python hl_lines="8 13"
|
||||
{!../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
### 戻り値
|
||||
|
||||
そして、値を返すことも返さないこともできますが、値は使われません。
|
||||
|
||||
つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます:
|
||||
|
||||
```Python hl_lines="9 14"
|
||||
{!../../../docs_src/dependencies/tutorial006.py!}
|
||||
```
|
||||
|
||||
## *path operations*のグループに対する依存関係
|
||||
|
||||
後で、より大きなアプリケーションの構造([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank})について読む時に、おそらく複数のファイルを使用して、*path operations*のグループに対して単一の`dependencies`パラメータを宣言する方法を学ぶでしょう。
|
||||
225
docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md
Normal file
225
docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md
Normal file
@@ -0,0 +1,225 @@
|
||||
# yieldを持つ依存関係
|
||||
|
||||
FastAPIは、いくつかの<abbr title='時々"exit"、"cleanup"、"teardown"、"close"、"context managers"、 ...のように呼ばれる'>終了後の追加のステップ</abbr>を行う依存関係をサポートしています。
|
||||
|
||||
これを行うには、`return`の代わりに`yield`を使い、その後に追加のステップを書きます。
|
||||
|
||||
!!! tip "豆知識"
|
||||
`yield`は必ず一度だけ使用するようにしてください。
|
||||
|
||||
!!! info "情報"
|
||||
これを動作させるには、**Python 3.7** 以上を使用するか、**Python 3.6** では"backports"をインストールする必要があります:
|
||||
|
||||
```
|
||||
pip install async-exit-stack async-generator
|
||||
```
|
||||
|
||||
これにより<a href="https://github.com/sorcio/async_exit_stack" class="external-link" target="_blank">async-exit-stack</a>と<a href="https://github.com/python-trio/async_generator" class="external-link" target="_blank">async-generator</a>がインストールされます。
|
||||
|
||||
!!! note "技術詳細"
|
||||
以下と一緒に使用できる関数なら何でも有効です:
|
||||
|
||||
* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a>または
|
||||
* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
|
||||
|
||||
これらは **FastAPI** の依存関係として使用するのに有効です。
|
||||
|
||||
実際、FastAPIは内部的にこれら2つのデコレータを使用しています。
|
||||
|
||||
## `yield`を持つデータベースの依存関係
|
||||
|
||||
例えば、これを使ってデータベースセッションを作成し、終了後にそれを閉じることができます。
|
||||
|
||||
レスポンスを送信する前に`yield`文を含む前のコードのみが実行されます。
|
||||
|
||||
```Python hl_lines="2 3 4"
|
||||
{!../../../docs_src/dependencies/tutorial007.py!}
|
||||
```
|
||||
|
||||
生成された値は、*path operations*や他の依存関係に注入されるものです:
|
||||
|
||||
```Python hl_lines="4"
|
||||
{!../../../docs_src/dependencies/tutorial007.py!}
|
||||
```
|
||||
|
||||
`yield`文に続くコードは、レスポンスが送信された後に実行されます:
|
||||
|
||||
```Python hl_lines="5 6"
|
||||
{!../../../docs_src/dependencies/tutorial007.py!}
|
||||
```
|
||||
|
||||
!!! tip "豆知識"
|
||||
`async`や通常の関数を使用することができます。
|
||||
|
||||
**FastAPI** は、通常の依存関係と同じように、それぞれで正しいことを行います。
|
||||
|
||||
## `yield`と`try`を持つ依存関係
|
||||
|
||||
`yield`を持つ依存関係で`try`ブロックを使用した場合、その依存関係を使用した際に発生した例外を受け取ることになります。
|
||||
|
||||
例えば、途中のどこかの時点で、別の依存関係や*path operation*の中で、データベーストランザクションを「ロールバック」したり、その他のエラーを作成したりするコードがあった場合、依存関係の中で例外を受け取ることになります。
|
||||
|
||||
そのため、依存関係の中にある特定の例外を`except SomeException`で探すことができます。
|
||||
|
||||
同様に、`finally`を用いて例外があったかどうかにかかわらず、終了ステップを確実に実行することができます。
|
||||
|
||||
```Python hl_lines="3 5"
|
||||
{!../../../docs_src/dependencies/tutorial007.py!}
|
||||
```
|
||||
|
||||
## `yield`を持つサブ依存関係
|
||||
|
||||
任意の大きさや形のサブ依存関係やサブ依存関係の「ツリー」を持つことができ、その中で`yield`を使用することができます。
|
||||
|
||||
**FastAPI** は、`yield`を持つ各依存関係の「終了コード」が正しい順番で実行されていることを確認します。
|
||||
|
||||
例えば、`dependency_c`は`dependency_b`と`dependency_b`に依存する`dependency_a`に、依存することができます:
|
||||
|
||||
```Python hl_lines="4 12 20"
|
||||
{!../../../docs_src/dependencies/tutorial008.py!}
|
||||
```
|
||||
|
||||
そして、それらはすべて`yield`を使用することができます。
|
||||
|
||||
この場合、`dependency_c`は終了コードを実行するために、`dependency_b`(ここでは`dep_b`という名前)の値がまだ利用可能である必要があります。
|
||||
|
||||
そして、`dependency_b`は`dependency_a`(ここでは`dep_a`という名前)の値を終了コードで利用できるようにする必要があります。
|
||||
|
||||
```Python hl_lines="16 17 24 25"
|
||||
{!../../../docs_src/dependencies/tutorial008.py!}
|
||||
```
|
||||
|
||||
同様に、`yield`と`return`が混在した依存関係を持つこともできます。
|
||||
|
||||
また、単一の依存関係を持っていて、`yield`などの他の依存関係をいくつか必要とすることもできます。
|
||||
|
||||
依存関係の組み合わせは自由です。
|
||||
|
||||
**FastAPI** は、全てが正しい順序で実行されていることを確認します。
|
||||
|
||||
!!! note "技術詳細"
|
||||
これはPythonの<a href="https://docs.python.org/3/library/contextlib.html" class="external-link" target="_blank">Context Managers</a>のおかげで動作します。
|
||||
|
||||
**FastAPI** はこれを実現するために内部的に使用しています。
|
||||
|
||||
## `yield`と`HTTPException`を持つ依存関係
|
||||
|
||||
`yield`と例外をキャッチする`try`ブロックを持つことができる依存関係を使用することができることがわかりました。
|
||||
|
||||
`yield`の後の終了コードで`HTTPException`などを発生させたくなるかもしれません。しかし**それはうまくいきません**
|
||||
|
||||
`yield`を持つ依存関係の終了コードは[例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}の*後に*実行されます。依存関係によって投げられた例外を終了コード(`yield`の後)でキャッチするものはなにもありません。
|
||||
|
||||
つまり、`yield`の後に`HTTPException`を発生させた場合、`HTTTPException`をキャッチしてHTTP 400のレスポンスを返すデフォルトの(あるいは任意のカスタムの)例外ハンドラは、その例外をキャッチすることができなくなります。
|
||||
|
||||
これは、依存関係に設定されているもの(例えば、DBセッション)を、例えば、バックグラウンドタスクで使用できるようにするものです。
|
||||
|
||||
バックグラウンドタスクはレスポンスが送信された*後*に実行されます。そのため、*すでに送信されている*レスポンスを変更する方法すらないので、`HTTPException`を発生させる方法はありません。
|
||||
|
||||
しかし、バックグラウンドタスクがDBエラーを発生させた場合、少なくとも`yield`で依存関係のセッションをロールバックしたり、きれいに閉じたりすることができ、エラーをログに記録したり、リモートのトラッキングシステムに報告したりすることができます。
|
||||
|
||||
例外が発生する可能性があるコードがある場合は、最も普通の「Python流」なことをして、コードのその部分に`try`ブロックを追加してください。
|
||||
|
||||
レスポンスを返したり、レスポンスを変更したり、`HTTPException`を発生させたりする*前に*処理したいカスタム例外がある場合は、[カスタム例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}を作成してください。
|
||||
|
||||
!!! tip "豆知識"
|
||||
`HTTPException`を含む例外は、`yield`の*前*でも発生させることができます。ただし、後ではできません。
|
||||
|
||||
実行の順序は多かれ少なかれ以下の図のようになります。時間は上から下へと流れていきます。そして、各列はコードを相互作用させたり、実行したりしている部分の一つです。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
|
||||
participant client as Client
|
||||
participant handler as Exception handler
|
||||
participant dep as Dep with yield
|
||||
participant operation as Path Operation
|
||||
participant tasks as Background tasks
|
||||
|
||||
Note over client,tasks: Can raise exception for dependency, handled after response is sent
|
||||
Note over client,operation: Can raise HTTPException and can change the response
|
||||
client ->> dep: Start request
|
||||
Note over dep: Run code up to yield
|
||||
opt raise
|
||||
dep -->> handler: Raise HTTPException
|
||||
handler -->> client: HTTP error response
|
||||
dep -->> dep: Raise other exception
|
||||
end
|
||||
dep ->> operation: Run dependency, e.g. DB session
|
||||
opt raise
|
||||
operation -->> handler: Raise HTTPException
|
||||
handler -->> client: HTTP error response
|
||||
operation -->> dep: Raise other exception
|
||||
end
|
||||
operation ->> client: Return response to client
|
||||
Note over client,operation: Response is already sent, can't change it anymore
|
||||
opt Tasks
|
||||
operation -->> tasks: Send background tasks
|
||||
end
|
||||
opt Raise other exception
|
||||
tasks -->> dep: Raise other exception
|
||||
end
|
||||
Note over dep: After yield
|
||||
opt Handle other exception
|
||||
dep -->> dep: Handle exception, can't change response. E.g. close DB session.
|
||||
end
|
||||
```
|
||||
|
||||
!!! info "情報"
|
||||
**1つのレスポンス** だけがクライアントに送信されます。それはエラーレスポンスの一つかもしれませんし、*path operation*からのレスポンスかもしれません。
|
||||
|
||||
いずれかのレスポンスが送信された後、他のレスポンスを送信することはできません。
|
||||
|
||||
!!! tip "豆知識"
|
||||
この図は`HTTPException`を示していますが、[カスタム例外ハンドラ](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}を作成することで、他の例外を発生させることもできます。そして、その例外は依存関係の終了コードではなく、そのカスタム例外ハンドラによって処理されます。
|
||||
|
||||
しかし例外ハンドラで処理されない例外を発生させた場合は、依存関係の終了コードで処理されます。
|
||||
|
||||
## コンテキストマネージャ
|
||||
|
||||
### 「コンテキストマネージャ」とは
|
||||
|
||||
「コンテキストマネージャ」とは、`with`文の中で使用できるPythonオブジェクトのことです。
|
||||
|
||||
例えば、<a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files" class="external-link" target="_blank">ファイルを読み込むには`with`を使用することができます</a>:
|
||||
|
||||
```Python
|
||||
with open("./somefile.txt") as f:
|
||||
contents = f.read()
|
||||
print(contents)
|
||||
```
|
||||
|
||||
その後の`open("./somefile.txt")`は「コンテキストマネージャ」と呼ばれるオブジェクトを作成します。
|
||||
|
||||
`with`ブロックが終了すると、例外があったとしてもファイルを確かに閉じます。
|
||||
|
||||
`yield`を依存関係を作成すると、**FastAPI** は内部的にそれをコンテキストマネージャに変換し、他の関連ツールと組み合わせます。
|
||||
|
||||
### `yield`を持つ依存関係でのコンテキストマネージャの使用
|
||||
|
||||
!!! warning "注意"
|
||||
これは多かれ少なかれ、「高度な」発想です。
|
||||
|
||||
**FastAPI** を使い始めたばかりの方は、とりあえずスキップした方がよいかもしれません。
|
||||
|
||||
Pythonでは、<a href="https://docs.python.org/3/reference/datamodel.html#context-managers" class="external-link" target="_blank">以下の2つのメソッドを持つクラスを作成する: `__enter__()`と`__exit__()`</a>ことでコンテキストマネージャを作成することができます。
|
||||
|
||||
また、依存関数の中で`with`や`async with`文を使用することによって`yield`を持つ **FastAPI** の依存関係の中でそれらを使用することができます:
|
||||
|
||||
```Python hl_lines="1 2 3 4 5 6 7 8 9 13"
|
||||
{!../../../docs_src/dependencies/tutorial010.py!}
|
||||
```
|
||||
|
||||
!!! tip "豆知識"
|
||||
コンテキストマネージャを作成するもう一つの方法はwithです:
|
||||
|
||||
* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" class="external-link" target="_blank">`@contextlib.contextmanager`</a> または
|
||||
* <a href="https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager" class="external-link" target="_blank">`@contextlib.asynccontextmanager`</a>
|
||||
|
||||
これらを使って、関数を単一の`yield`でデコレートすることができます。
|
||||
|
||||
これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。
|
||||
|
||||
しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。
|
||||
|
||||
FastAPIが内部的にやってくれます。
|
||||
209
docs/ja/docs/tutorial/dependencies/index.md
Normal file
209
docs/ja/docs/tutorial/dependencies/index.md
Normal file
@@ -0,0 +1,209 @@
|
||||
# 依存関係 - 最初のステップ
|
||||
|
||||
** FastAPI** は非常に強力でありながら直感的な **<abbr title="コンポーネント、リソース、プロバイダ、サービス、インジェクタブルとしても知られている">依存性注入</abbr>** システムを持っています。
|
||||
|
||||
それは非常にシンプルに使用できるように設計されており、開発者が他のコンポーネント **FastAPI** と統合するのが非常に簡単になるように設計されています。
|
||||
|
||||
## 「依存性注入」とは
|
||||
|
||||
**「依存性注入」** とは、プログラミングにおいて、コード(この場合は、*path operation関数*)が動作したり使用したりするために必要なもの(「依存関係」)を宣言する方法があることを意味します:
|
||||
|
||||
そして、そのシステム(この場合は、**FastAPI**)は、必要な依存関係をコードに提供するために必要なことは何でも行います(依存関係を「注入」します)。
|
||||
|
||||
これは以下のようなことが必要な時にとても便利です:
|
||||
|
||||
* ロジックを共有している。(同じコードロジックを何度も繰り返している)。
|
||||
* データベース接続を共有する。
|
||||
* セキュリティ、認証、ロール要件などを強制する。
|
||||
* そのほかにも多くのこと...
|
||||
|
||||
これらすべてを、コードの繰り返しを最小限に抑えながら行います。
|
||||
|
||||
## 最初のステップ
|
||||
|
||||
非常にシンプルな例を見てみましょう。あまりにもシンプルなので、今のところはあまり参考にならないでしょう。
|
||||
|
||||
しかし、この方法では **依存性注入** システムがどのように機能するかに焦点を当てることができます。
|
||||
|
||||
### 依存関係の作成
|
||||
|
||||
まずは依存関係に注目してみましょう。
|
||||
|
||||
以下のように、*path operation関数*と同じパラメータを全て取ることができる関数にすぎません:
|
||||
|
||||
```Python hl_lines="8 9"
|
||||
{!../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
これだけです。
|
||||
|
||||
**2行**。
|
||||
|
||||
そして、それはすべての*path operation関数*が持っているのと同じ形と構造を持っています。
|
||||
|
||||
「デコレータ」を含まない(`@app.get("/some-path")`を含まない)*path operation関数*と考えることもできます。
|
||||
|
||||
そして何でも返すことができます。
|
||||
|
||||
この場合、この依存関係は以下を期待しています:
|
||||
|
||||
* オプショナルのクエリパラメータ`q`は`str`です。
|
||||
* オプショナルのクエリパラメータ`skip`は`int`で、デフォルトは`0`です。
|
||||
* オプショナルのクエリパラメータ`limit`は`int`で、デフォルトは`100`です。
|
||||
|
||||
そして、これらの値を含む`dict`を返します。
|
||||
|
||||
### `Depends`のインポート
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
### "dependant"での依存関係の宣言
|
||||
|
||||
*path operation関数*のパラメータに`Body`や`Query`などを使用するのと同じように、新しいパラメータに`Depends`を使用することができます:
|
||||
|
||||
```Python hl_lines="13 18"
|
||||
{!../../../docs_src/dependencies/tutorial001.py!}
|
||||
```
|
||||
|
||||
関数のパラメータに`Depends`を使用するのは`Body`や`Query`などと同じですが、`Depends`の動作は少し異なります。
|
||||
|
||||
`Depends`は1つのパラメータしか与えられません。
|
||||
|
||||
このパラメータは関数のようなものである必要があります。
|
||||
|
||||
そして、その関数は、*path operation関数*が行うのと同じ方法でパラメータを取ります。
|
||||
|
||||
!!! tip "豆知識"
|
||||
次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。
|
||||
|
||||
新しいリクエストが到着するたびに、**FastAPI** が以下のような処理を行います:
|
||||
|
||||
* 依存関係("dependable")関数を正しいパラメータで呼び出します。
|
||||
* 関数の結果を取得します。
|
||||
* *path operation関数*のパラメータにその結果を代入してください。
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
|
||||
common_parameters(["common_parameters"])
|
||||
read_items["/items/"]
|
||||
read_users["/users/"]
|
||||
|
||||
common_parameters --> read_items
|
||||
common_parameters --> read_users
|
||||
```
|
||||
|
||||
この方法では、共有されるコードを一度書き、**FastAPI** が*path operations*のための呼び出しを行います。
|
||||
|
||||
!!! check "確認"
|
||||
特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。
|
||||
|
||||
`Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。
|
||||
|
||||
## `async`にするかどうか
|
||||
|
||||
依存関係は **FastAPI**(*path operation関数*と同じ)からも呼び出されるため、関数を定義する際にも同じルールが適用されます。
|
||||
|
||||
`async def`や通常の`def`を使用することができます。
|
||||
|
||||
また、通常の`def`*path operation関数*の中に`async def`を入れて依存関係を宣言したり、`async def`*path operation関数*の中に`def`を入れて依存関係を宣言したりすることなどができます。
|
||||
|
||||
それは重要ではありません。**FastAPI** は何をすべきかを知っています。
|
||||
|
||||
!!! note "備考"
|
||||
わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。
|
||||
|
||||
## OpenAPIとの統合
|
||||
|
||||
依存関係(およびサブ依存関係)のすべてのリクエスト宣言、検証、および要件は、同じOpenAPIスキーマに統合されます。
|
||||
|
||||
つまり、対話型ドキュメントにはこれらの依存関係から得られる全ての情報も含まれているということです:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/img/tutorial/dependencies/image01.png">
|
||||
|
||||
## 簡単な使い方
|
||||
|
||||
見てみると、*path*と*operation*が一致した時に*path operation関数*が宣言されていて、**FastAPI** が正しいパラメータで関数を呼び出してリクエストからデータを抽出する処理をしています。
|
||||
|
||||
実は、すべての(あるいはほとんどの)Webフレームワークは、このように動作します。
|
||||
|
||||
これらの関数を直接呼び出すことはありません。これらの関数はフレームワーク(この場合は、**FastAPI**)によって呼び出されます。
|
||||
|
||||
依存性注入システムでは、**FastAPI** に*path operation*もまた、*path operation関数*の前に実行されるべき他の何かに「依存」していることを伝えることができ、**FastAPI** がそれを実行し、結果を「注入」することを引き受けます。
|
||||
|
||||
他にも、「依存性注入」と同じような考えの一般的な用語があります:
|
||||
|
||||
* リソース
|
||||
* プロバイダ
|
||||
* サービス
|
||||
* インジェクタブル
|
||||
* コンポーネント
|
||||
|
||||
## **FastAPI** プラグイン
|
||||
|
||||
統合や「プラグイン」は **依存性注入** システムを使って構築することができます。しかし、実際には、**「プラグイン」を作成する必要はありません**。依存関係を使用することで、無限の数の統合やインタラクションを宣言することができ、それが**path operation関数*で利用可能になるからです。
|
||||
|
||||
依存関係は非常にシンプルで直感的な方法で作成することができ、必要なPythonパッケージをインポートするだけで、*文字通り*数行のコードでAPI関数と統合することができます。
|
||||
|
||||
次の章では、リレーショナルデータベースやNoSQLデータベース、セキュリティなどについて、その例を見ていきます。
|
||||
|
||||
## **FastAPI** 互換性
|
||||
|
||||
依存性注入システムがシンプルなので、**FastAPI** は以下のようなものと互換性があります:
|
||||
|
||||
* すべてのリレーショナルデータベース
|
||||
* NoSQLデータベース
|
||||
* 外部パッケージ
|
||||
* 外部API
|
||||
* 認証・認可システム
|
||||
* API利用状況監視システム
|
||||
* レスポンスデータ注入システム
|
||||
* など。
|
||||
|
||||
## シンプルでパワフル
|
||||
|
||||
階層依存性注入システムは、定義や使用方法が非常にシンプルであるにもかかわらず、非常に強力なものとなっています。
|
||||
|
||||
依存関係事態を定義する依存関係を定義することができます。
|
||||
|
||||
最終的には、依存関係の階層ツリーが構築され、**依存性注入**システムが、これらの依存関係(およびそのサブ依存関係)をすべて解決し、各ステップで結果を提供(注入)します。
|
||||
|
||||
例えば、4つのAPIエンドポイント(*path operations*)があるとします:
|
||||
|
||||
* `/items/public/`
|
||||
* `/items/private/`
|
||||
* `/users/{user_id}/activate`
|
||||
* `/items/pro/`
|
||||
|
||||
そして、依存関係とサブ依存関係だけで、それぞれに異なるパーミッション要件を追加することができます:
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
|
||||
current_user(["current_user"])
|
||||
active_user(["active_user"])
|
||||
admin_user(["admin_user"])
|
||||
paying_user(["paying_user"])
|
||||
|
||||
public["/items/public/"]
|
||||
private["/items/private/"]
|
||||
activate_user["/users/{user_id}/activate"]
|
||||
pro_items["/items/pro/"]
|
||||
|
||||
current_user --> active_user
|
||||
active_user --> admin_user
|
||||
active_user --> paying_user
|
||||
|
||||
current_user --> public
|
||||
active_user --> private
|
||||
admin_user --> activate_user
|
||||
paying_user --> pro_items
|
||||
```
|
||||
|
||||
## **OpenAPI** との統合
|
||||
|
||||
これら全ての依存関係は、要件を宣言すると同時に、*path operations*にパラメータやバリデーションを追加します。
|
||||
|
||||
**FastAPI** はそれをすべてOpenAPIスキーマに追加して、対話型のドキュメントシステムに表示されるようにします。
|
||||
86
docs/ja/docs/tutorial/dependencies/sub-dependencies.md
Normal file
86
docs/ja/docs/tutorial/dependencies/sub-dependencies.md
Normal file
@@ -0,0 +1,86 @@
|
||||
# サブ依存関係
|
||||
|
||||
**サブ依存関係** を持つ依存関係を作成することができます。
|
||||
|
||||
それらは必要なだけ **深く** することができます。
|
||||
|
||||
**FastAPI** はそれらを解決してくれます。
|
||||
|
||||
### 最初の依存関係「依存可能なもの」
|
||||
|
||||
以下のような最初の依存関係(「依存可能なもの」)を作成することができます:
|
||||
|
||||
```Python hl_lines="8 9"
|
||||
{!../../../docs_src/dependencies/tutorial005.py!}
|
||||
```
|
||||
|
||||
これはオプショナルのクエリパラメータ`q`を`str`として宣言し、それを返すだけです。
|
||||
|
||||
これは非常にシンプルです(あまり便利ではありません)が、サブ依存関係がどのように機能するかに焦点を当てるのに役立ちます。
|
||||
|
||||
### 第二の依存関係 「依存可能なもの」と「依存」
|
||||
|
||||
そして、別の依存関数(「依存可能なもの」)を作成して、同時にそれ自身の依存関係を宣言することができます(つまりそれ自身も「依存」です):
|
||||
|
||||
```Python hl_lines="13"
|
||||
{!../../../docs_src/dependencies/tutorial005.py!}
|
||||
```
|
||||
|
||||
宣言されたパラメータに注目してみましょう:
|
||||
|
||||
* この関数は依存関係(「依存可能なもの」)そのものであるにもかかわらず、別の依存関係を宣言しています(何か他のものに「依存」しています)。
|
||||
* これは`query_extractor`に依存しており、それが返す値をパラメータ`q`に代入します。
|
||||
* また、オプショナルの`last_query`クッキーを`str`として宣言します。
|
||||
* ユーザーがクエリ`q`を提供しなかった場合、クッキーに保存していた最後に使用したクエリを使用します。
|
||||
|
||||
### 依存関係の使用
|
||||
|
||||
以下のように依存関係を使用することができます:
|
||||
|
||||
```Python hl_lines="21"
|
||||
{!../../../docs_src/dependencies/tutorial005.py!}
|
||||
```
|
||||
|
||||
!!! info "情報"
|
||||
*path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。
|
||||
|
||||
しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
|
||||
query_extractor(["query_extractor"])
|
||||
query_or_cookie_extractor(["query_or_cookie_extractor"])
|
||||
|
||||
read_query["/items/"]
|
||||
|
||||
query_extractor --> query_or_cookie_extractor --> read_query
|
||||
```
|
||||
|
||||
## 同じ依存関係の複数回の使用
|
||||
|
||||
依存関係の1つが同じ*path operation*に対して複数回宣言されている場合、例えば、複数の依存関係が共通のサブ依存関係を持っている場合、**FastAPI** はリクエストごとに1回だけそのサブ依存関係を呼び出します。
|
||||
|
||||
そして、返された値を<abbr title="計算された値・生成された値を保存するユーティリティまたはシステム、再計算する代わりに再利用するためのもの">「キャッシュ」</abbr>に保存し、同じリクエストに対して依存関係を何度も呼び出す代わりに、特定のリクエストでそれを必要とする全ての「依存関係」に渡すことになります。
|
||||
|
||||
高度なシナリオでは、「キャッシュされた」値を使うのではなく、同じリクエストの各ステップ(おそらく複数回)で依存関係を呼び出す必要があることがわかっている場合、`Depens`を使用する際に、`use_cache=False`というパラメータを設定することができます。
|
||||
|
||||
```Python hl_lines="1"
|
||||
async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)):
|
||||
return {"fresh_value": fresh_value}
|
||||
```
|
||||
|
||||
## まとめ
|
||||
|
||||
ここで使われている派手な言葉は別にして、**依存性注入** システムは非常にシンプルです。
|
||||
|
||||
*path operation関数*と同じように見えるただの関数です。
|
||||
|
||||
しかし、それでも非常に強力で、任意の深くネストされた依存関係「グラフ」(ツリー)を宣言することができます。
|
||||
|
||||
!!! tip "豆知識"
|
||||
これらの単純な例では、全てが役に立つとは言えないかもしれません。
|
||||
|
||||
しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。
|
||||
|
||||
そして、あなたを救うコードの量もみることになるでしょう。
|
||||
34
docs/ja/docs/tutorial/encoder.md
Normal file
34
docs/ja/docs/tutorial/encoder.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# JSON互換エンコーダ
|
||||
|
||||
データ型(Pydanticモデルのような)をJSONと互換性のあるもの(`dict`や`list`など)に変更する必要がある場合があります。
|
||||
|
||||
例えば、データベースに保存する必要がある場合です。
|
||||
|
||||
そのために、**FastAPI** は`jsonable_encoder()`関数を提供しています。
|
||||
|
||||
## `jsonable_encoder`の使用
|
||||
|
||||
JSON互換のデータのみを受信するデータベース`fase_db`があるとしましょう。
|
||||
|
||||
例えば、`datetime`オブジェクトはJSONと互換性がないので、このデーターベースには受け取られません。
|
||||
|
||||
そのため、`datetime`オブジェクトは<a href="https://en.wikipedia.org/wiki/ISO_8601" class="external-link" target="_blank">ISO形式</a>のデータを含む`str`に変換されなければなりません。
|
||||
|
||||
同様に、このデータベースはPydanticモデル(属性を持つオブジェクト)を受け取らず、`dict`だけを受け取ります。
|
||||
|
||||
そのために`jsonable_encoder`を使用することができます。
|
||||
|
||||
Pydanticモデルのようなオブジェクトを受け取り、JSON互換版を返します:
|
||||
|
||||
```Python hl_lines="5 22"
|
||||
{!../../../docs_src/encoder/tutorial001.py!}
|
||||
```
|
||||
|
||||
この例では、Pydanticモデルを`dict`に、`datetime`を`str`に変換します。
|
||||
|
||||
呼び出した結果は、Pythonの標準の<a href="https://docs.python.org/3/library/json.html#json.dumps" class="external-link" target="_blank">`json.dumps()`</a>でエンコードできるものです。
|
||||
|
||||
これはJSON形式のデータを含む大きな`str`を(文字列として)返しません。JSONと互換性のある値とサブの値を持つPython標準のデータ構造(例:`dict`)を返します。
|
||||
|
||||
!!! note "備考"
|
||||
`jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。
|
||||
66
docs/ja/docs/tutorial/extra-data-types.md
Normal file
66
docs/ja/docs/tutorial/extra-data-types.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# 追加データ型
|
||||
|
||||
今までは、以下のような一般的なデータ型を使用してきました:
|
||||
|
||||
* `int`
|
||||
* `float`
|
||||
* `str`
|
||||
* `bool`
|
||||
|
||||
しかし、より複雑なデータ型を使用することもできます。
|
||||
|
||||
そして、今まで見てきたのと同じ機能を持つことになります:
|
||||
|
||||
* 素晴らしいエディタのサポート
|
||||
* 受信したリクエストからのデータ変換
|
||||
* レスポンスデータのデータ変換
|
||||
* データの検証
|
||||
* 自動注釈と文書化
|
||||
|
||||
## 他のデータ型
|
||||
|
||||
ここでは、使用できる追加のデータ型のいくつかを紹介します:
|
||||
|
||||
* `UUID`:
|
||||
* 多くのデータベースやシステムで共通のIDとして使用される、標準的な「ユニバーサルにユニークな識別子」です。
|
||||
* リクエストとレスポンスでは`str`として表現されます。
|
||||
* `datetime.datetime`:
|
||||
* Pythonの`datetime.datetime`です。
|
||||
* リクエストとレスポンスはISO 8601形式の`str`で表現されます: `2008-09-15T15:53:00+05:00`
|
||||
* `datetime.date`:
|
||||
* Pythonの`datetime.date`です。
|
||||
* リクエストとレスポンスはISO 8601形式の`str`で表現されます: `2008-09-15`
|
||||
* `datetime.time`:
|
||||
* Pythonの`datetime.time`.
|
||||
* リクエストとレスポンスはISO 8601形式の`str`で表現されます: `14:23:55.003`
|
||||
* `datetime.timedelta`:
|
||||
* Pythonの`datetime.timedelta`です。
|
||||
* リクエストとレスポンスでは合計秒数の`float`で表現されます。
|
||||
* Pydanticでは「ISO 8601 time diff encoding」として表現することも可能です。<a href="https://pydantic-docs.helpmanual.io/#json-serialisation" class="external-link" target="_blank">詳細はドキュメントを参照してください</a>。
|
||||
* `frozenset`:
|
||||
* リクエストとレスポンスでは`set`と同じように扱われます:
|
||||
* リクエストでは、リストが読み込まれ、重複を排除して`set`に変換されます。
|
||||
* レスポンスでは`set`が`list`に変換されます。
|
||||
* 生成されたスキーマは`set`の値が一意であることを指定します(JSON Schemaの`uniqueItems`を使用します)。
|
||||
* `bytes`:
|
||||
* Pythonの標準的な`bytes`です。
|
||||
* リクエストとレスポンスでは`str`として扱われます。
|
||||
* 生成されたスキーマは`str`で`binary`の「フォーマット」持つことを指定します。
|
||||
* `Decimal`:
|
||||
* Pythonの標準的な`Decimal`です。
|
||||
* リクエストやレスポンスでは`float`と同じように扱います。
|
||||
|
||||
* Pydanticの全ての有効な型はこちらで確認できます: <a href="https://pydantic-docs.helpmanual.io/usage/types" class="external-link" target="_blank">Pydantic data types</a>。
|
||||
## 例
|
||||
|
||||
ここでは、上記の型のいくつかを使用したパラメータを持つ*path operation*の例を示します。
|
||||
|
||||
```Python hl_lines="1 2 12-16"
|
||||
{!../../../docs_src/extra_data_types/tutorial001.py!}
|
||||
```
|
||||
|
||||
関数内のパラメータは自然なデータ型を持っていることに注意してください。そして、以下のように通常の日付操作を行うことができます:
|
||||
|
||||
```Python hl_lines="18 19"
|
||||
{!../../../docs_src/extra_data_types/tutorial001.py!}
|
||||
```
|
||||
195
docs/ja/docs/tutorial/extra-models.md
Normal file
195
docs/ja/docs/tutorial/extra-models.md
Normal file
@@ -0,0 +1,195 @@
|
||||
# モデル - より詳しく
|
||||
|
||||
先ほどの例に続き、複数の関連モデルを持つことが一般的です。
|
||||
|
||||
これはユーザーモデルの場合は特にそうです。なぜなら:
|
||||
|
||||
* **入力モデル** にはパスワードが必要です。
|
||||
* **出力モデル**はパスワードをもつべきではありません。
|
||||
* **データベースモデル**はおそらくハッシュ化されたパスワードが必要になるでしょう。
|
||||
|
||||
!!! danger "危険"
|
||||
ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。
|
||||
|
||||
知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。
|
||||
|
||||
## 複数のモデル
|
||||
|
||||
ここでは、パスワードフィールドをもつモデルがどのように見えるのか、また、どこで使われるのか、大まかなイメージを紹介します:
|
||||
|
||||
```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41"
|
||||
{!../../../docs_src/extra_models/tutorial001.py!}
|
||||
```
|
||||
|
||||
### `**user_in.dict()`について
|
||||
|
||||
#### Pydanticの`.dict()`
|
||||
|
||||
`user_in`は`UserIn`クラスのPydanticモデルです。
|
||||
|
||||
Pydanticモデルには、モデルのデータを含む`dict`を返す`.dict()`メソッドがあります。
|
||||
|
||||
そこで、以下のようなPydanticオブジェクト`user_in`を作成すると:
|
||||
|
||||
```Python
|
||||
user_in = UserIn(username="john", password="secret", email="john.doe@example.com")
|
||||
```
|
||||
|
||||
そして呼び出すと:
|
||||
|
||||
```Python
|
||||
user_dict = user_in.dict()
|
||||
```
|
||||
|
||||
これで変数`user_dict`のデータを持つ`dict`ができました。(これはPydanticモデルのオブジェクトの代わりに`dict`です)。
|
||||
|
||||
そして呼び出すと:
|
||||
|
||||
```Python
|
||||
print(user_dict)
|
||||
```
|
||||
|
||||
以下のようなPythonの`dict`を得ることができます:
|
||||
|
||||
```Python
|
||||
{
|
||||
'username': 'john',
|
||||
'password': 'secret',
|
||||
'email': 'john.doe@example.com',
|
||||
'full_name': None,
|
||||
}
|
||||
```
|
||||
|
||||
#### `dict`の展開
|
||||
|
||||
`user_dict`のような`dict`を受け取り、それを`**user_dict`を持つ関数(またはクラス)に渡すと、Pythonはそれを「展開」します。これは`user_dict`のキーと値を直接キー・バリューの引数として渡します。
|
||||
|
||||
そこで上述の`user_dict`の続きを以下のように書くと:
|
||||
|
||||
```Python
|
||||
UserInDB(**user_dict)
|
||||
```
|
||||
|
||||
以下と同等の結果になります:
|
||||
|
||||
```Python
|
||||
UserInDB(
|
||||
username="john",
|
||||
password="secret",
|
||||
email="john.doe@example.com",
|
||||
full_name=None,
|
||||
)
|
||||
```
|
||||
|
||||
もっと正確に言えば、`user_dict`を将来的にどんな内容であっても直接使用することになります:
|
||||
|
||||
```Python
|
||||
UserInDB(
|
||||
username = user_dict["username"],
|
||||
password = user_dict["password"],
|
||||
email = user_dict["email"],
|
||||
full_name = user_dict["full_name"],
|
||||
)
|
||||
```
|
||||
|
||||
#### 別のモデルからつくるPydanticモデル
|
||||
|
||||
上述の例では`user_in.dict()`から`user_dict`をこのコードのように取得していますが:
|
||||
|
||||
```Python
|
||||
user_dict = user_in.dict()
|
||||
UserInDB(**user_dict)
|
||||
```
|
||||
|
||||
これは以下と同等です:
|
||||
|
||||
```Python
|
||||
UserInDB(**user_in.dict())
|
||||
```
|
||||
|
||||
...なぜなら`user_in.dict()`は`dict`であり、`**`を付与して`UserInDB`を渡してPythonに「展開」させているからです。
|
||||
|
||||
そこで、別のPydanticモデルのデータからPydanticモデルを取得します。
|
||||
|
||||
#### `dict`の展開と追加引数
|
||||
|
||||
そして、追加のキーワード引数`hashed_password=hashed_password`を以下のように追加すると:
|
||||
|
||||
```Python
|
||||
UserInDB(**user_in.dict(), hashed_password=hashed_password)
|
||||
```
|
||||
|
||||
...以下のようになります:
|
||||
|
||||
```Python
|
||||
UserInDB(
|
||||
username = user_dict["username"],
|
||||
password = user_dict["password"],
|
||||
email = user_dict["email"],
|
||||
full_name = user_dict["full_name"],
|
||||
hashed_password = hashed_password,
|
||||
)
|
||||
```
|
||||
|
||||
!!! warning "注意"
|
||||
サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。
|
||||
|
||||
## 重複の削減
|
||||
|
||||
コードの重複を減らすことは、**FastAPI**の中核的なアイデアの1つです。
|
||||
|
||||
コードの重複が増えると、バグやセキュリティの問題、コードの非同期化問題(ある場所では更新しても他の場所では更新されない場合)などが発生する可能性が高くなります。
|
||||
|
||||
そして、これらのモデルは全てのデータを共有し、属性名や型を重複させています。
|
||||
|
||||
もっと良い方法があります。
|
||||
|
||||
他のモデルのベースとなる`UserBase`モデルを宣言することができます。そして、そのモデルの属性(型宣言、検証など)を継承するサブクラスを作ることができます。
|
||||
|
||||
データの変換、検証、文書化などはすべて通常通りに動作します。
|
||||
|
||||
このようにして、モデル間の違いだけを宣言することができます:
|
||||
|
||||
```Python hl_lines="9 15 16 19 20 23 24"
|
||||
{!../../../docs_src/extra_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
## `Union`または`anyOf`
|
||||
|
||||
レスポンスを2つの型の`Union`として宣言することができます。
|
||||
|
||||
OpenAPIでは`anyOf`で定義されます。
|
||||
|
||||
そのためには、標準的なPythonの型ヒント<a href="https://docs.python.org/3/library/typing.html#typing.Union" class="external-link" target="_blank">`typing.Union`</a>を使用します:
|
||||
|
||||
```Python hl_lines="1 14 15 18 19 20 33"
|
||||
{!../../../docs_src/extra_models/tutorial003.py!}
|
||||
```
|
||||
|
||||
## モデルのリスト
|
||||
|
||||
同じように、オブジェクトのリストのレスポンスを宣言することができます。
|
||||
|
||||
そのためには、標準のPythonの`typing.List`を使用する:
|
||||
|
||||
```Python hl_lines="1 20"
|
||||
{!../../../docs_src/extra_models/tutorial004.py!}
|
||||
```
|
||||
|
||||
## 任意の`dict`を持つレスポンス
|
||||
|
||||
また、Pydanticモデルを使用せずに、キーと値の型だけを定義した任意の`dict`を使ってレスポンスを宣言することもできます。
|
||||
|
||||
これは、有効なフィールド・属性名(Pydanticモデルに必要なもの)を事前に知らない場合に便利です。
|
||||
|
||||
この場合、`typing.Dict`を使用することができます:
|
||||
|
||||
```Python hl_lines="1 8"
|
||||
{!../../../docs_src/extra_models/tutorial005.py!}
|
||||
```
|
||||
|
||||
## まとめ
|
||||
|
||||
複数のPydanticモデルを使用し、ケースごとに自由に継承します。
|
||||
|
||||
エンティティが異なる「状態」を持たなければならない場合は、エンティティごとに単一のデータモデルを持つ必要はありません。`password` や `password_hash` やパスワードなしなどのいくつかの「状態」をもつユーザー「エンティティ」の場合の様にすれば良いです。
|
||||
265
docs/ja/docs/tutorial/handling-errors.md
Normal file
265
docs/ja/docs/tutorial/handling-errors.md
Normal file
@@ -0,0 +1,265 @@
|
||||
# エラーハンドリング
|
||||
|
||||
APIを使用しているクライアントにエラーを通知する必要がある状況はたくさんあります。
|
||||
|
||||
このクライアントは、フロントエンドを持つブラウザ、誰かのコード、IoTデバイスなどが考えられます。
|
||||
|
||||
クライアントに以下のようなことを伝える必要があるかもしれません:
|
||||
|
||||
* クライアントにはその操作のための十分な権限がありません。
|
||||
* クライアントはそのリソースにアクセスできません。
|
||||
* クライアントがアクセスしようとしていた項目が存在しません。
|
||||
* など
|
||||
|
||||
これらの場合、通常は **400**(400から499)の範囲内の **HTTPステータスコード** を返すことになります。
|
||||
|
||||
これは200のHTTPステータスコード(200から299)に似ています。これらの「200」ステータスコードは、何らかの形でリクエスト「成功」であったことを意味します。
|
||||
|
||||
400の範囲にあるステータスコードは、クライアントからのエラーがあったことを意味します。
|
||||
|
||||
**"404 Not Found"** のエラー(およびジョーク)を覚えていますか?
|
||||
|
||||
## `HTTPException`の使用
|
||||
|
||||
HTTPレスポンスをエラーでクライアントに返すには、`HTTPException`を使用します。
|
||||
|
||||
### `HTTPException`のインポート
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!../../../docs_src/handling_errors/tutorial001.py!}
|
||||
```
|
||||
|
||||
### コード内での`HTTPException`の発生
|
||||
|
||||
`HTTPException`は通常のPythonの例外であり、APIに関連するデータを追加したものです。
|
||||
|
||||
Pythonの例外なので、`return`ではなく、`raise`です。
|
||||
|
||||
これはまた、*path operation関数*の内部で呼び出しているユーティリティ関数の内部から`HTTPException`を発生させた場合、*path operation関数*の残りのコードは実行されず、そのリクエストを直ちに終了させ、`HTTPException`からのHTTPエラーをクライアントに送信することを意味します。
|
||||
|
||||
値を返す`return`よりも例外を発生させることの利点は、「依存関係とセキュリティ」のセクションでより明確になります。
|
||||
|
||||
この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます:
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!../../../docs_src/handling_errors/tutorial001.py!}
|
||||
```
|
||||
|
||||
### レスポンス結果
|
||||
|
||||
クライアントが`http://example.com/items/foo`(`item_id` `"foo"`)をリクエストすると、HTTPステータスコードが200で、以下のJSONレスポンスが返されます:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"item": "The Foo Wrestlers"
|
||||
}
|
||||
```
|
||||
|
||||
しかし、クライアントが`http://example.com/items/bar`(存在しない`item_id` `"bar"`)をリクエストした場合、HTTPステータスコード404("not found"エラー)と以下のJSONレスポンスが返されます:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"detail": "Item not found"
|
||||
}
|
||||
```
|
||||
|
||||
!!! tip "豆知識"
|
||||
`HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。
|
||||
|
||||
`dist`や`list`などを渡すことができます。
|
||||
|
||||
これらは **FastAPI** によって自動的に処理され、JSONに変換されます。
|
||||
|
||||
## カスタムヘッダーの追加
|
||||
|
||||
例えば、いくつかのタイプのセキュリティのために、HTTPエラーにカスタムヘッダを追加できると便利な状況がいくつかあります。
|
||||
|
||||
おそらくコードの中で直接使用する必要はないでしょう。
|
||||
|
||||
しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます:
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!../../../docs_src/handling_errors/tutorial002.py!}
|
||||
```
|
||||
|
||||
## カスタム例外ハンドラのインストール
|
||||
|
||||
カスタム例外ハンドラは<a href="https://www.starlette.io/exceptions/" class="external-link" target="_blank">Starletteと同じ例外ユーティリティ</a>を使用して追加することができます。
|
||||
|
||||
あなた(または使用しているライブラリ)が`raise`するかもしれないカスタム例外`UnicornException`があるとしましょう。
|
||||
|
||||
そして、この例外をFastAPIでグローバルに処理したいと思います。
|
||||
|
||||
カスタム例外ハンドラを`@app.exception_handler()`で追加することができます:
|
||||
|
||||
```Python hl_lines="5 6 7 13 14 15 16 17 18 24"
|
||||
{!../../../docs_src/handling_errors/tutorial003.py!}
|
||||
```
|
||||
|
||||
ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。
|
||||
|
||||
しかし、これは`unicorn_exception_handler`で処理されます。
|
||||
|
||||
そのため、HTTPステータスコードが`418`で、JSONの内容が以下のような明確なエラーを受け取ることになります:
|
||||
|
||||
```JSON
|
||||
{"message": "Oops! yolo did something. There goes a rainbow..."}
|
||||
```
|
||||
|
||||
!!! note "技術詳細"
|
||||
また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。
|
||||
|
||||
**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。
|
||||
|
||||
## デフォルトの例外ハンドラのオーバーライド
|
||||
|
||||
**FastAPI** にはいくつかのデフォルトの例外ハンドラがあります。
|
||||
|
||||
これらのハンドラは、`HTTPException`を`raise`させた場合や、リクエストに無効なデータが含まれている場合にデフォルトのJSONレスポンスを返す役割を担っています。
|
||||
|
||||
これらの例外ハンドラを独自のものでオーバーライドすることができます。
|
||||
|
||||
### リクエスト検証の例外のオーバーライド
|
||||
|
||||
リクエストに無効なデータが含まれている場合、**FastAPI** は内部的に`RequestValidationError`を発生させます。
|
||||
|
||||
また、そのためのデフォルトの例外ハンドラも含まれています。
|
||||
|
||||
これをオーバーライドするには`RequestValidationError`をインポートして`@app.exception_handler(RequestValidationError)`と一緒に使用して例外ハンドラをデコレートします。
|
||||
|
||||
この例外ハンドラは`Requset`と例外を受け取ります。
|
||||
|
||||
```Python hl_lines="2 14 15 16"
|
||||
{!../../../docs_src/handling_errors/tutorial004.py!}
|
||||
```
|
||||
|
||||
これで、`/items/foo`にアクセスすると、デフォルトのJSONエラーの代わりに以下が返されます:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"detail": [
|
||||
{
|
||||
"loc": [
|
||||
"path",
|
||||
"item_id"
|
||||
],
|
||||
"msg": "value is not a valid integer",
|
||||
"type": "type_error.integer"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
以下のようなテキスト版を取得します:
|
||||
|
||||
```
|
||||
1 validation error
|
||||
path -> item_id
|
||||
value is not a valid integer (type=type_error.integer)
|
||||
```
|
||||
|
||||
#### `RequestValidationError`と`ValidationError`
|
||||
|
||||
!!! warning "注意"
|
||||
これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。
|
||||
|
||||
`RequestValidationError`はPydanticの<a href="https://pydantic-docs.helpmanual.io/#error-handling" class="external-link" target="_blank">`ValidationError`</a>のサブクラスです。
|
||||
|
||||
**FastAPI** は`response_model`でPydanticモデルを使用していて、データにエラーがあった場合、ログにエラーが表示されるようにこれを使用しています。
|
||||
|
||||
しかし、クライアントやユーザーはそれを見ることはありません。その代わりに、クライアントはHTTPステータスコード`500`の「Internal Server Error」を受け取ります。
|
||||
|
||||
*レスポンス*やコードのどこか(クライアントの*リクエスト*ではなく)にPydanticの`ValidationError`がある場合、それは実際にはコードのバグなのでこのようにすべきです。
|
||||
|
||||
また、あなたがそれを修正している間は、セキュリティの脆弱性が露呈する場合があるため、クライアントやユーザーがエラーに関する内部情報にアクセスできないようにしてください。
|
||||
|
||||
### エラーハンドラ`HTTPException`のオーバーライド
|
||||
|
||||
同様に、`HTTPException`ハンドラをオーバーライドすることもできます。
|
||||
|
||||
例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます:
|
||||
|
||||
```Python hl_lines="3 4 9 10 11 22"
|
||||
{!../../../docs_src/handling_errors/tutorial004.py!}
|
||||
```
|
||||
|
||||
!!! note "技術詳細"
|
||||
また、`from starlette.responses import PlainTextResponse`を使用することもできます。
|
||||
|
||||
**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。
|
||||
|
||||
### `RequestValidationError`のボディの使用
|
||||
|
||||
`RequestValidationError`には無効なデータを含む`body`が含まれています。
|
||||
|
||||
アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。
|
||||
|
||||
```Python hl_lines="14"
|
||||
{!../../../docs_src/handling_errors/tutorial005.py!}
|
||||
```
|
||||
|
||||
ここで、以下のような無効な項目を送信してみてください:
|
||||
|
||||
```JSON
|
||||
{
|
||||
"title": "towel",
|
||||
"size": "XL"
|
||||
}
|
||||
```
|
||||
|
||||
受信したボディを含むデータが無効であることを示すレスポンスが表示されます:
|
||||
|
||||
```JSON hl_lines="12 13 14 15"
|
||||
{
|
||||
"detail": [
|
||||
{
|
||||
"loc": [
|
||||
"body",
|
||||
"size"
|
||||
],
|
||||
"msg": "value is not a valid integer",
|
||||
"type": "type_error.integer"
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
"title": "towel",
|
||||
"size": "XL"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### FastAPIの`HTTPException`とStarletteの`HTTPException`
|
||||
|
||||
**FastAPI**は独自の`HTTPException`を持っています。
|
||||
|
||||
また、 **FastAPI**のエラークラス`HTTPException`はStarletteのエラークラス`HTTPException`を継承しています。
|
||||
|
||||
唯一の違いは、**FastAPI** の`HTTPException`はレスポンスに含まれるヘッダを追加できることです。
|
||||
|
||||
これはOAuth 2.0といくつかのセキュリティユーティリティのために内部的に必要とされ、使用されています。
|
||||
|
||||
そのため、コード内では通常通り **FastAPI** の`HTTPException`を発生させ続けることができます。
|
||||
|
||||
しかし、例外ハンドラを登録する際には、Starletteの`HTTPException`を登録しておく必要があります。
|
||||
|
||||
これにより、Starletteの内部コードやStarletteの拡張機能やプラグインの一部が`HTTPException`を発生させた場合、ハンドラがそれをキャッチして処理することができるようになります。
|
||||
|
||||
以下の例では、同じコード内で両方の`HTTPException`を使用できるようにするために、Starletteの例外の名前を`StarletteHTTPException`に変更しています:
|
||||
|
||||
```Python
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
```
|
||||
|
||||
### **FastAPI** の例外ハンドラの再利用
|
||||
|
||||
また、何らかの方法で例外を使用することもできますが、**FastAPI** から同じデフォルトの例外ハンドラを使用することもできます。
|
||||
|
||||
デフォルトの例外ハンドラを`fastapi.exception_handlers`からインポートして再利用することができます:
|
||||
|
||||
```Python hl_lines="2 3 4 5 15 21"
|
||||
{!../../../docs_src/handling_errors/tutorial006.py!}
|
||||
```
|
||||
|
||||
この例では、非常に表現力のあるメッセージでエラーを`print`しています。
|
||||
|
||||
しかし、例外を使用して、デフォルトの例外ハンドラを再利用することができるということが理解できます。
|
||||
122
docs/ja/docs/tutorial/path-params-numeric-validations.md
Normal file
122
docs/ja/docs/tutorial/path-params-numeric-validations.md
Normal file
@@ -0,0 +1,122 @@
|
||||
# パスパラメータと数値の検証
|
||||
|
||||
クエリパラメータに対して`Query`でより多くのバリデーションとメタデータを宣言できるのと同じように、パスパラメータに対しても`Path`で同じ種類のバリデーションとメタデータを宣言することができます。
|
||||
|
||||
## Pathのインポート
|
||||
|
||||
まず初めに、`fastapi`から`Path`をインポートします:
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
|
||||
```
|
||||
|
||||
## メタデータの宣言
|
||||
|
||||
パラメータは`Query`と同じものを宣言することができます。
|
||||
|
||||
例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします:
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "備考"
|
||||
パスの一部でなければならないので、パスパラメータは常に必須です。
|
||||
|
||||
そのため、`...`を使用して必須と示す必要があります。
|
||||
|
||||
それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。
|
||||
|
||||
## 必要に応じてパラメータを並び替える
|
||||
|
||||
クエリパラメータ`q`を必須の`str`として宣言したいとしましょう。
|
||||
|
||||
また、このパラメータには何も宣言する必要がないので、`Query`を使う必要はありません。
|
||||
|
||||
しかし、パスパラメータ`item_id`のために`Path`を使用する必要があります。
|
||||
|
||||
Pythonは「デフォルト」を持たない値の前に「デフォルト」を持つ値を置くことができません。
|
||||
|
||||
しかし、それらを並び替えることができ、デフォルト値を持たない値(クエリパラメータ`q`)を最初に持つことができます。
|
||||
|
||||
**FastAPI**では関係ありません。パラメータは名前、型、デフォルトの宣言(`Query`、`Path`など)で検出され、順番は気にしません。
|
||||
|
||||
そのため、以下のように関数を宣言することができます:
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
|
||||
```
|
||||
|
||||
## 必要に応じてパラメータを並び替えるトリック
|
||||
|
||||
クエリパラメータ`q`を`Query`やデフォルト値なしで宣言し、パスパラメータ`item_id`を`Path`を用いて宣言し、それらを別の順番に並びたい場合、Pythonには少し特殊な構文が用意されています。
|
||||
|
||||
関数の最初のパラメータとして`*`を渡します。
|
||||
|
||||
Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それは<abbr title="From: K-ey W-ord Arg-uments"><code>kwargs</code></abbr>としても知られています。たとえデフォルト値がなくても。
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
|
||||
```
|
||||
|
||||
## 数値の検証: 以上
|
||||
|
||||
`Query`と`Path`(、そして後述する他のもの)を用いて、文字列の制約を宣言することができますが、数値の制約も同様に宣言できます。
|
||||
|
||||
ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial004.py!}
|
||||
```
|
||||
|
||||
## 数値の検証: より大きいと小なりイコール
|
||||
|
||||
以下も同様です:
|
||||
|
||||
* `gt`: より大きい(`g`reater `t`han)
|
||||
* `le`: 小なりイコール(`l`ess than or `e`qual)
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial005.py!}
|
||||
```
|
||||
|
||||
## 数値の検証: 浮動小数点、 大なり小なり
|
||||
|
||||
数値のバリデーションは`float`の値に対しても有効です。
|
||||
|
||||
ここで重要になってくるのは<abbr title="より大きい"><code>gt</code></abbr>だけでなく<abbr title="以下"><code>ge</code></abbr>も宣言できることです。これと同様に、例えば、値が`1`より小さくても`0`より大きくなければならないことを要求することができます。
|
||||
|
||||
したがって、`0.5`は有効な値ですが、`0.0`や`0`はそうではありません。
|
||||
|
||||
これは<abbr title="未満"><code>lt</code></abbr>も同じです。
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!../../../docs_src/path_params_numeric_validations/tutorial006.py!}
|
||||
```
|
||||
|
||||
## まとめ
|
||||
|
||||
`Query`と`Path`(そしてまだ見たことない他のもの)では、[クエリパラメータと文字列の検証](query-params-str-validations.md){.internal-link target=_blank}と同じようにメタデータと文字列の検証を宣言することができます。
|
||||
|
||||
また、数値のバリデーションを宣言することもできます:
|
||||
|
||||
* `gt`: より大きい(`g`reater `t`han)
|
||||
* `ge`: 以上(`g`reater than or `e`qual)
|
||||
* `lt`: より小さい(`l`ess `t`han)
|
||||
* `le`: 以下(`l`ess than or `e`qual)
|
||||
|
||||
!!! info "情報"
|
||||
`Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません)
|
||||
|
||||
そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。
|
||||
|
||||
!!! note "技術詳細"
|
||||
`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。
|
||||
|
||||
呼び出されると、同じ名前のクラスのインスタンスを返します。
|
||||
|
||||
そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。
|
||||
|
||||
これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。
|
||||
|
||||
この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。
|
||||
208
docs/ja/docs/tutorial/response-model.md
Normal file
208
docs/ja/docs/tutorial/response-model.md
Normal file
@@ -0,0 +1,208 @@
|
||||
# レスポンスモデル
|
||||
|
||||
*path operations* のいずれにおいても、`response_model`パラメータを使用して、レスポンスのモデルを宣言することができます:
|
||||
|
||||
* `@app.get()`
|
||||
* `@app.post()`
|
||||
* `@app.put()`
|
||||
* `@app.delete()`
|
||||
* など。
|
||||
|
||||
```Python hl_lines="17"
|
||||
{!../../../docs_src/response_model/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "備考"
|
||||
`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。
|
||||
|
||||
Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。
|
||||
|
||||
FastAPIは`response_model`を使って以下のことをします:
|
||||
|
||||
* 出力データを型宣言に変換します。
|
||||
* データを検証します。
|
||||
* OpenAPIの *path operation* で、レスポンス用のJSON Schemaを追加します。
|
||||
* 自動ドキュメントシステムで使用されます。
|
||||
|
||||
しかし、最も重要なのは:
|
||||
|
||||
* 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。
|
||||
|
||||
!!! note "技術詳細"
|
||||
レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。
|
||||
|
||||
## 同じ入力データの返却
|
||||
|
||||
ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています:
|
||||
|
||||
```Python hl_lines="9 11"
|
||||
{!../../../docs_src/response_model/tutorial002.py!}
|
||||
```
|
||||
|
||||
そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています:
|
||||
|
||||
```Python hl_lines="17 18"
|
||||
{!../../../docs_src/response_model/tutorial002.py!}
|
||||
```
|
||||
|
||||
これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。
|
||||
|
||||
この場合、ユーザー自身がパスワードを送信しているので問題ないかもしれません。
|
||||
|
||||
しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。
|
||||
|
||||
!!! danger "危険"
|
||||
ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。
|
||||
|
||||
## 出力モデルの追加
|
||||
|
||||
代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます:
|
||||
|
||||
```Python hl_lines="9 11 16"
|
||||
{!../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず:
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません:
|
||||
|
||||
```Python hl_lines="22"
|
||||
{!../../../docs_src/response_model/tutorial003.py!}
|
||||
```
|
||||
|
||||
そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。
|
||||
|
||||
## ドキュメントを見る
|
||||
|
||||
自動ドキュメントを見ると、入力モデルと出力モデルがそれぞれ独自のJSON Schemaを持っていることが確認できます。
|
||||
|
||||
<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: str = None`は`None`がデフォルト値です。
|
||||
* `tax: float = 10.5`は`10.5`がデフォルト値です。
|
||||
* `tags: List[str] = []` は空のリスト(`[]`)がデフォルト値です。
|
||||
|
||||
しかし、実際に保存されていない場合には結果からそれらを省略した方が良いかもしれません。
|
||||
|
||||
例えば、NoSQLデータベースに多くのオプション属性を持つモデルがあるが、デフォルト値でいっぱいの非常に長いJSONレスポンスを送信したくない場合です。
|
||||
|
||||
### `response_model_exclude_unset`パラメータの使用
|
||||
|
||||
*path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます:
|
||||
|
||||
```Python hl_lines="24"
|
||||
{!../../../docs_src/response_model/tutorial004.py!}
|
||||
```
|
||||
|
||||
そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。
|
||||
|
||||
そのため、*path operation*にID`foo`が設定されたitemのリクエストを送ると、レスポンスは以下のようになります(デフォルト値を含まない):
|
||||
|
||||
```JSON
|
||||
{
|
||||
"name": "Foo",
|
||||
"price": 50.2
|
||||
}
|
||||
```
|
||||
|
||||
!!! info "情報"
|
||||
FastAPIはこれをするために、Pydanticモデルの`.dict()`を<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`
|
||||
|
||||
`exclude_defaults`と`exclude_none`については、<a href="https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict" class="external-link" target="_blank">Pydanticのドキュメント</a>で説明されている通りです。
|
||||
|
||||
#### デフォルト値を持つフィールドの値を持つデータ
|
||||
|
||||
しかし、ID`bar`のitemのように、デフォルト値が設定されているモデルのフィールドに値が設定されている場合:
|
||||
|
||||
```Python hl_lines="3 5"
|
||||
{
|
||||
"name": "Bar",
|
||||
"description": "The bartenders",
|
||||
"price": 62,
|
||||
"tax": 20.2
|
||||
}
|
||||
```
|
||||
|
||||
それらはレスポンスに含まれます。
|
||||
|
||||
#### デフォルト値と同じ値を持つデータ
|
||||
|
||||
ID`baz`のitemのようにデフォルト値と同じ値を持つデータの場合:
|
||||
|
||||
```Python hl_lines="3 5 6"
|
||||
{
|
||||
"name": "Baz",
|
||||
"description": None,
|
||||
"price": 50.2,
|
||||
"tax": 10.5,
|
||||
"tags": []
|
||||
}
|
||||
```
|
||||
|
||||
FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`description`や`tax`、`tags`はデフォルト値と同じ値を持っているにもかかわらず、明示的に設定されていることを理解しています。(デフォルトから取得するのではなく)
|
||||
|
||||
そのため、それらはJSONレスポンスに含まれることになります。
|
||||
|
||||
!!! tip "豆知識"
|
||||
デフォルト値は`None`だけでなく、なんでも良いことに注意してください。
|
||||
例えば、リスト(`[]`)や`10.5`の`float`などです。
|
||||
|
||||
### `response_model_include`と`response_model_exclude`
|
||||
|
||||
*path operationデコレータ*として`response_model_include`と`response_model_exclude`も使用することができます。
|
||||
|
||||
属性名を持つ`str`の`set`を受け取り、含める(残りを省略する)か、除外(残りを含む)します。
|
||||
|
||||
これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。
|
||||
|
||||
!!! tip "豆知識"
|
||||
それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。
|
||||
|
||||
これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。
|
||||
|
||||
同様に動作する`response_model_by_alias`にも当てはまります。
|
||||
|
||||
```Python hl_lines="31 37"
|
||||
{!../../../docs_src/response_model/tutorial005.py!}
|
||||
```
|
||||
|
||||
!!! tip "豆知識"
|
||||
`{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。
|
||||
|
||||
これは`set(["name", "description"])`と同等です。
|
||||
|
||||
#### `set`の代わりに`list`を使用する
|
||||
|
||||
もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します:
|
||||
|
||||
```Python hl_lines="31 37"
|
||||
{!../../../docs_src/response_model/tutorial006.py!}
|
||||
```
|
||||
|
||||
## まとめ
|
||||
|
||||
*path operationデコレータの*`response_model`パラメータを使用して、レスポンスモデルを定義し、特にプライベートデータがフィルタリングされていることを保証します。
|
||||
|
||||
明示的に設定された値のみを返すには、`response_model_exclude_unset`を使用します。
|
||||
89
docs/ja/docs/tutorial/response-status-code.md
Normal file
89
docs/ja/docs/tutorial/response-status-code.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# レスポンスステータスコード
|
||||
|
||||
レスポンスモデルを指定するのと同じ方法で、レスポンスに使用されるHTTPステータスコードを以下の*path operations*のいずれかの`status_code`パラメータで宣言することもできます。
|
||||
|
||||
* `@app.get()`
|
||||
* `@app.post()`
|
||||
* `@app.put()`
|
||||
* `@app.delete()`
|
||||
* など。
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!../../../docs_src/response_status_code/tutorial001.py!}
|
||||
```
|
||||
|
||||
!!! note "備考"
|
||||
`status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。
|
||||
|
||||
`status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。
|
||||
|
||||
!!! info "情報"
|
||||
`status_code`は代わりに、Pythonの<a href="https://docs.python.org/3/library/http.html#http.HTTPStatus" class="external-link" target="_blank">`http.HTTPStatus`</a>のように、`IntEnum`を受け取ることもできます。
|
||||
|
||||
これは:
|
||||
|
||||
* レスポンスでステータスコードを返します。
|
||||
* 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`はデフォルトのステータスコードで、すべてが「OK」であったことを意味します。
|
||||
* 別の例としては、`201`(Created)があります。これはデータベースに新しいレコードを作成した後によく使用されます。
|
||||
* 特殊なケースとして、`204`(No Content)があります。このレスポンスはクライアントに返すコンテンツがない場合に使用されます。そしてこのレスポンスはボディを持つことはできません。
|
||||
* **`300`** 以上は「リダイレクト」のためのものです。これらのステータスコードを持つレスポンスは`304`(Not Modified)を除き、ボディを持つことも持たないこともできます。
|
||||
* **`400`** 以上は「クライアントエラー」のレスポンスのためのものです。これらは、おそらく最も多用するであろう2番目のタイプです。
|
||||
* 例えば、`404`は「Not Found」レスポンスです。
|
||||
* クライアントからの一般的なエラーについては、`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** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。
|
||||
|
||||
## デフォルトの変更
|
||||
|
||||
後に、[高度なユーザーガイド](../advanced/response-change-status-code.md){.internal-link target=_blank}で、ここで宣言しているデフォルトとは異なるステータスコードを返す方法を見ていきます。
|
||||
58
docs/ja/docs/tutorial/schema-extra-example.md
Normal file
58
docs/ja/docs/tutorial/schema-extra-example.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# スキーマの追加 - 例
|
||||
|
||||
JSON Schemaに追加する情報を定義することができます。
|
||||
|
||||
一般的なユースケースはこのドキュメントで示されているように`example`を追加することです。
|
||||
|
||||
JSON Schemaの追加情報を宣言する方法はいくつかあります。
|
||||
|
||||
## Pydanticの`schema_extra`
|
||||
|
||||
<a href="https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization" class="external-link" target="_blank">Pydanticのドキュメント: スキーマのカスタマイズ</a>で説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます:
|
||||
|
||||
```Python hl_lines="15 16 17 18 19 20 21 22 23"
|
||||
{!../../../docs_src/schema_extra_example/tutorial001.py!}
|
||||
```
|
||||
|
||||
その追加情報はそのまま出力され、JSON Schemaに追加されます。
|
||||
|
||||
## `Field`の追加引数
|
||||
|
||||
後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます:
|
||||
|
||||
```Python hl_lines="4 10 11 12 13"
|
||||
{!../../../docs_src/schema_extra_example/tutorial002.py!}
|
||||
```
|
||||
|
||||
!!! warning "注意"
|
||||
これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。
|
||||
|
||||
## `Body`の追加引数
|
||||
|
||||
追加情報を`Field`に渡すのと同じように、`Path`、`Query`、`Body`などでも同じことができます。
|
||||
|
||||
例えば、`Body`にボディリクエストの`example`を渡すことができます:
|
||||
|
||||
```Python hl_lines="21 22 23 24 25 26"
|
||||
{!../../../docs_src/schema_extra_example/tutorial003.py!}
|
||||
```
|
||||
|
||||
## ドキュメントのUIの例
|
||||
|
||||
上記のいずれの方法でも、`/docs`の中では以下のようになります:
|
||||
|
||||
<img src="https://fastapi.tiangolo.com/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は`examples`を持たない古いバージョンのJSON Schemaをベースにしています。
|
||||
|
||||
そのため、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>を独自に定義しており(`examples`ではなく`example`として)、それがdocs UI(Swagger UIを使用)で使用されています。
|
||||
|
||||
つまり、`example`はJSON Schemaの一部ではありませんが、OpenAPIの一部であり、それがdocs UIで使用されることになります。
|
||||
|
||||
## その他の情報
|
||||
|
||||
同じように、フロントエンドのユーザーインターフェースなどをカスタマイズするために、各モデルのJSON Schemaに追加される独自の追加情報を追加することができます。
|
||||
101
docs/ja/docs/tutorial/security/index.md
Normal file
101
docs/ja/docs/tutorial/security/index.md
Normal file
@@ -0,0 +1,101 @@
|
||||
# セキュリティ入門
|
||||
|
||||
セキュリティ、認証、認可を扱うには多くの方法があります。
|
||||
|
||||
そして、通常、それは複雑で「難しい」トピックです。
|
||||
|
||||
多くのフレームワークやシステムでは、セキュリティと認証を処理するだけで、膨大な労力とコードが必要になります(多くの場合、書かれた全コードの50%以上を占めることがあります)。
|
||||
|
||||
**FastAPI** は、セキュリティの仕様をすべて勉強して学ぶことなく、標準的な方法で簡単に、迅速に**セキュリティ**を扱うためのツールをいくつか提供します。
|
||||
|
||||
しかし、その前に、いくつかの小さな概念を確認しましょう。
|
||||
|
||||
## お急ぎですか?
|
||||
|
||||
もし、これらの用語に興味がなく、ユーザー名とパスワードに基づく認証でセキュリティを**今すぐ**確保する必要がある場合は、次の章に進んでください。
|
||||
|
||||
## OAuth2
|
||||
|
||||
OAuth2は、認証と認可を処理するためのいくつかの方法を定義した仕様です。
|
||||
|
||||
かなり広範囲な仕様で、いくつかの複雑なユースケースをカバーしています。
|
||||
|
||||
これには「サードパーティ」を使用して認証する方法が含まれています。
|
||||
|
||||
これが、「Facebook、Google、Twitter、GitHubを使ってログイン」を使用したすべてのシステムの背後で使われている仕組みです。
|
||||
|
||||
### OAuth 1
|
||||
|
||||
OAuth 1というものもありましたが、これはOAuth2とは全く異なり、通信をどのように暗号化するかという仕様が直接的に含まれており、より複雑なものとなっています。
|
||||
|
||||
現在ではあまり普及していませんし、使われてもいません。
|
||||
|
||||
OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。
|
||||
|
||||
!!! tip "豆知識"
|
||||
**デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。
|
||||
|
||||
|
||||
## OpenID Connect
|
||||
|
||||
OpenID Connectは、**OAuth2**をベースにした別の仕様です。
|
||||
|
||||
これはOAuth2を拡張したもので、OAuth2ではやや曖昧だった部分を明確にし、より相互運用性を高めようとしたものです。
|
||||
|
||||
例として、GoogleのログインはOpenID Connectを使用しています(これはOAuth2がベースになっています)。
|
||||
|
||||
しかし、FacebookのログインはOpenID Connectをサポートしていません。OAuth2を独自にアレンジしています。
|
||||
|
||||
### OpenID (「OpenID Connect」ではない)
|
||||
|
||||
また、「OpenID」という仕様もありました。それは、**OpenID Connect**と同じことを解決しようとしたものですが、OAuth2に基づいているわけではありませんでした。
|
||||
|
||||
つまり、完全な追加システムだったのです。
|
||||
|
||||
現在ではあまり普及していませんし、使われてもいません。
|
||||
|
||||
## OpenAPI
|
||||
|
||||
OpenAPI(以前はSwaggerとして知られていました)は、APIを構築するためのオープンな仕様です(現在はLinux Foundationの一部になっています)。
|
||||
|
||||
**FastAPI**は、**OpenAPI**をベースにしています。
|
||||
|
||||
それが、複数の自動対話型ドキュメント・インターフェースやコード生成などを可能にしているのです。
|
||||
|
||||
OpenAPIには、複数のセキュリティ「スキーム」を定義する方法があります。
|
||||
|
||||
それらを使用することで、これらの対話型ドキュメントシステムを含む、標準ベースのツールをすべて活用できます。
|
||||
|
||||
OpenAPIでは、以下のセキュリティスキームを定義しています:
|
||||
|
||||
* `apiKey`: アプリケーション固有のキーで、これらのものから取得できます。
|
||||
* クエリパラメータ
|
||||
* ヘッダー
|
||||
* クッキー
|
||||
* `http`: 標準的なHTTP認証システムで、これらのものを含みます。
|
||||
* `bearer`: ヘッダ `Authorization` の値が `Bearer ` で、トークンが含まれます。これはOAuth2から継承しています。
|
||||
* HTTP Basic認証
|
||||
* HTTP ダイジェスト認証など
|
||||
* `oauth2`: OAuth2のセキュリティ処理方法(「フロー」と呼ばれます)のすべて。
|
||||
* これらのフローのいくつかは、OAuth 2.0認証プロバイダ(Google、Facebook、Twitter、GitHubなど)を構築するのに適しています。
|
||||
* `implicit`
|
||||
* `clientCredentials`
|
||||
* `authorizationCode`
|
||||
* しかし、同じアプリケーション内で認証を直接処理するために完全に機能する特定の「フロー」があります。
|
||||
* `password`: 次のいくつかの章では、その例を紹介します。
|
||||
* `openIdConnect`: OAuth2認証データを自動的に発見する方法を定義できます。
|
||||
* この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。
|
||||
|
||||
|
||||
!!! tip "豆知識"
|
||||
Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。
|
||||
|
||||
最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。
|
||||
|
||||
## **FastAPI** ユーティリティ
|
||||
|
||||
FastAPIは `fastapi.security` モジュールの中で、これらのセキュリティスキームごとにいくつかのツールを提供し、これらのセキュリティメカニズムを簡単に使用できるようにします。
|
||||
|
||||
次の章では、**FastAPI** が提供するこれらのツールを使って、あなたのAPIにセキュリティを追加する方法について見ていきます。
|
||||
|
||||
また、それがどのようにインタラクティブなドキュメントシステムに自動的に統合されるかも見ていきます。
|
||||
@@ -167,7 +167,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し
|
||||
|
||||
JWTアクセストークンを作成し、それを返します。
|
||||
|
||||
```Python hl_lines="115-128"
|
||||
```Python hl_lines="115-130"
|
||||
{!../../../docs_src/security/tutorial004.py!}
|
||||
```
|
||||
|
||||
|
||||
698
docs/ko/docs/deployment/docker.md
Normal file
698
docs/ko/docs/deployment/docker.md
Normal file
@@ -0,0 +1,698 @@
|
||||
# 컨테이너의 FastAPI - 도커
|
||||
|
||||
FastAPI 어플리케이션을 배포할 때 일반적인 접근 방법은 **리눅스 컨테이너 이미지**를 생성하는 것입니다. 이 방법은 주로 <a href="https://www.docker.com/" class="external-link" target="_blank">**도커**</a>를 사용해 이루어집니다. 그런 다음 해당 컨테이너 이미지를 몇가지 방법으로 배포할 수 있습니다.
|
||||
|
||||
리눅스 컨테이너를 사용하는 데에는 **보안**, **반복 가능성**, **단순함** 등의 장점이 있습니다.
|
||||
|
||||
!!! 팁
|
||||
시간에 쫓기고 있고 이미 이런것들을 알고 있다면 [`Dockerfile`👇](#build-a-docker-image-for-fastapi)로 점프할 수 있습니다.
|
||||
|
||||
<details>
|
||||
<summary>도커파일 미리보기 👀</summary>
|
||||
|
||||
```Dockerfile
|
||||
FROM python:3.9
|
||||
|
||||
WORKDIR /code
|
||||
|
||||
COPY ./requirements.txt /code/requirements.txt
|
||||
|
||||
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
|
||||
COPY ./app /code/app
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
|
||||
# If running behind a proxy like Nginx or Traefik add --proxy-headers
|
||||
# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"]
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## 컨테이너란
|
||||
|
||||
컨테이너(주로 리눅스 컨테이너)는 어플리케이션의 의존성과 필요한 파일들을 모두 패키징하는 매우 **가벼운** 방법입니다. 컨테이너는 같은 시스템에 있는 다른 컨테이너(다른 어플리케이션이나 요소들)와 독립적으로 유지됩니다.
|
||||
|
||||
리눅스 컨테이너는 호스트(머신, 가상 머신, 클라우드 서버 등)와 같은 리눅스 커널을 사용해 실행됩니다. 이말은 리눅스 컨테이너가 (전체 운영체제를 모방하는 다른 가상 머신과 비교했을 때) 매우 가볍다는 것을 의미합니다.
|
||||
|
||||
이 방법을 통해, 컨테이너는 직접 프로세스를 실행하는 것과 비슷한 정도의 **적은 자원**을 소비합니다 (가상 머신은 훨씬 많은 자원을 소비할 것입니다).
|
||||
|
||||
컨테이너는 또한 그들만의 **독립된** 실행 프로세스 (일반적으로 하나의 프로세스로 충분합니다), 파일 시스템, 그리고 네트워크를 가지므로 배포, 보안, 개발 및 기타 과정을 단순화 합니다.
|
||||
|
||||
## 컨테이너 이미지란
|
||||
|
||||
**컨테이너**는 **컨테이너 이미지**를 실행한 것 입니다.
|
||||
|
||||
컨테이너 이미지란 컨테이너에 필요한 모든 파일, 환경 변수 그리고 디폴트 명령/프로그램의 **정적** 버전입니다. 여기서 **정적**이란 말은 컨테이너 **이미지**가 작동되거나 실행되지 않으며, 단지 패키지 파일과 메타 데이터라는 것을 의미합니다.
|
||||
|
||||
저장된 정적 컨텐츠인 **컨테이너 이미지**와 대조되게, **컨테이너**란 보통 실행될 수 있는 작동 인스턴스를 의미합니다.
|
||||
|
||||
**컨테이너**가 (**컨테이너 이미지**로 부터) 시작되고 실행되면, 컨테이너는 파일이나 환경 변수를 생성하거나 변경할 수 있습니다. 이러한 변화는 오직 컨테이너에서만 존재하며, 그 기반이 되는 컨테이너 이미지에는 지속되지 않습니다 (즉 디스크에는 저장되지 않습니다).
|
||||
|
||||
컨테이너 이미지는 **프로그램** 파일과 컨텐츠, 즉 `python`과 어떤 파일 `main.py`에 비교할 수 있습니다.
|
||||
|
||||
그리고 (**컨테이너 이미지**와 대비해서) **컨테이너**는 이미지의 실제 실행 인스턴스로 **프로세스**에 비교할 수 있습니다. 사실, 컨테이너는 **프로세스 러닝**이 있을 때만 실행됩니다 (그리고 보통 하나의 프로세스 입니다). 컨테이너는 내부에서 실행되는 프로세스가 없으면 종료됩니다.
|
||||
|
||||
## 컨테이너 이미지
|
||||
|
||||
도커는 **컨테이너 이미지**와 **컨테이너**를 생성하고 관리하는데 주요 도구 중 하나가 되어왔습니다.
|
||||
|
||||
그리고 <a href="https://hub.docker.com/" class="external-link" target="_blank">도커 허브</a>에 다양한 도구, 환경, 데이터베이스, 그리고 어플리케이션에 대해 미리 만들어진 **공식 컨테이너 이미지**가 공개되어 있습니다.
|
||||
|
||||
예를 들어, 공식 <a href="https://hub.docker.com/_/python" class="external-link" target="_blank">파이썬 이미지</a>가 있습니다.
|
||||
|
||||
또한 다른 대상, 예를 들면 데이터베이스를 위한 이미지들도 있습니다:
|
||||
|
||||
* <a href="https://hub.docker.com/_/postgres" class="external-link" target="_blank">PostgreSQL</a>
|
||||
* <a href="https://hub.docker.com/_/mysql" class="external-link" target="_blank">MySQL</a>
|
||||
* <a href="https://hub.docker.com/_/mongo" class="external-link" target="_blank">MongoDB</a>
|
||||
* <a href="https://hub.docker.com/_/redis" class="external-link" target="_blank">Redis</a> 등
|
||||
|
||||
미리 만들어진 컨테이너 이미지를 사용하면 서로 다른 도구들을 **결합**하기 쉽습니다. 대부분의 경우에, **공식 이미지들**을 사용하고 환경 변수를 통해 설정할 수 있습니다.
|
||||
|
||||
이런 방법으로 대부분의 경우에 컨테이너와 도커에 대해 배울 수 있으며 다양한 도구와 요소들에 대한 지식을 재사용할 수 있습니다.
|
||||
|
||||
따라서, 서로 다른 **다중 컨테이너**를 생성한 다음 이들을 연결할 수 있습니다. 예를 들어 데이터베이스, 파이썬 어플리케이션, 리액트 프론트엔드 어플리케이션을 사용하는 웹 서버에 대한 컨테이너를 만들어 이들의 내부 네트워크로 각 컨테이너를 연결할 수 있습니다.
|
||||
|
||||
모든 컨테이너 관리 시스템(도커나 쿠버네티스)은 이러한 네트워킹 특성을 포함하고 있습니다.
|
||||
|
||||
## 컨테이너와 프로세스
|
||||
|
||||
**컨테이너 이미지**는 보통 **컨테이너**를 시작하기 위해 필요한 메타데이터와 디폴트 커맨드/프로그램과 그 프로그램에 전달하기 위한 파라미터들을 포함합니다. 이는 커맨드 라인에서 프로그램을 실행할 때 필요한 값들과 유사합니다.
|
||||
|
||||
**컨테이너**가 시작되면, 해당 커맨드/프로그램이 실행됩니다 (그러나 다른 커맨드/프로그램을 실행하도록 오버라이드 할 수 있습니다).
|
||||
|
||||
컨테이너는 **메인 프로세스**(커맨드 또는 프로그램)이 실행되는 동안 실행됩니다.
|
||||
|
||||
컨테이너는 일반적으로 **단일 프로세스**를 가지고 있지만, 메인 프로세스의 서브 프로세스를 시작하는 것도 가능하며, 이 방법으로 하나의 컨테이너에 **다중 프로세스**를 가질 수 있습니다.
|
||||
|
||||
그러나 **최소한 하나의 실행중인 프로세스**를 가지지 않고서는 실행중인 컨테이너를 가질 수 없습니다. 만약 메인 프로세스가 중단되면, 컨테이너도 중단됩니다.
|
||||
|
||||
## FastAPI를 위한 도커 이미지 빌드하기
|
||||
|
||||
이제 무언가를 만들어 봅시다! 🚀
|
||||
|
||||
**공식 파이썬** 이미지에 기반하여, FastAPI를 위한 **도커 이미지**를 **맨 처음부터** 생성하는 방법을 보이겠습니다.
|
||||
|
||||
**대부분의 경우**에 다음과 같은 것들을 하게 됩니다. 예를 들면:
|
||||
|
||||
* **쿠버네티스** 또는 유사한 도구 사용하기
|
||||
* **라즈베리 파이**로 실행하기
|
||||
* 컨테이너 이미지를 실행할 클라우드 서비스 사용하기 등
|
||||
|
||||
### 요구 패키지
|
||||
|
||||
일반적으로는 어플리케이션의 특정 파일을 위한 **패키지 요구 조건**이 있을 것입니다.
|
||||
|
||||
그 요구 조건을 **설치**하는 방법은 여러분이 사용하는 도구에 따라 다를 것입니다.
|
||||
|
||||
가장 일반적인 방법은 패키지 이름과 버전이 줄 별로 기록된 `requirements.txt` 파일을 만드는 것입니다.
|
||||
|
||||
버전의 범위를 설정하기 위해서는 [FastAPI 버전들에 대하여](./versions.md){.internal-link target=_blank}에 쓰여진 것과 같은 아이디어를 사용합니다.
|
||||
|
||||
예를 들어, `requirements.txt` 파일은 다음과 같을 수 있습니다:
|
||||
|
||||
```
|
||||
fastapi>=0.68.0,<0.69.0
|
||||
pydantic>=1.8.0,<2.0.0
|
||||
uvicorn>=0.15.0,<0.16.0
|
||||
```
|
||||
|
||||
그리고 일반적으로 패키지 종속성은 `pip`로 설치합니다. 예를 들어:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install -r requirements.txt
|
||||
---> 100%
|
||||
Successfully installed fastapi pydantic uvicorn
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
!!! 정보
|
||||
패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다.
|
||||
|
||||
나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇
|
||||
|
||||
### **FastAPI** 코드 생성하기
|
||||
|
||||
* `app` 디렉터리를 생성하고 이동합니다.
|
||||
* 빈 파일 `__init__.py`을 생성합니다.
|
||||
* 다음과 같은 `main.py`을 생성합니다:
|
||||
|
||||
```Python
|
||||
from typing import Union
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
return {"Hello": "World"}
|
||||
|
||||
|
||||
@app.get("/items/{item_id}")
|
||||
def read_item(item_id: int, q: Union[str, None] = None):
|
||||
return {"item_id": item_id, "q": q}
|
||||
```
|
||||
|
||||
### 도커파일
|
||||
|
||||
이제 같은 프로젝트 디렉터리에 다음과 같은 파일 `Dockerfile`을 생성합니다:
|
||||
|
||||
```{ .dockerfile .annotate }
|
||||
# (1)
|
||||
FROM python:3.9
|
||||
|
||||
# (2)
|
||||
WORKDIR /code
|
||||
|
||||
# (3)
|
||||
COPY ./requirements.txt /code/requirements.txt
|
||||
|
||||
# (4)
|
||||
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
|
||||
# (5)
|
||||
COPY ./app /code/app
|
||||
|
||||
# (6)
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
```
|
||||
|
||||
1. 공식 파이썬 베이스 이미지에서 시작합니다.
|
||||
|
||||
2. 현재 워킹 디렉터리를 `/code`로 설정합니다.
|
||||
|
||||
여기에 `requirements.txt` 파일과 `app` 디렉터리를 위치시킬 것입니다.
|
||||
|
||||
3. 요구 조건과 파일을 `/code` 디렉터리로 복사합니다.
|
||||
|
||||
처음에는 **오직** 요구 조건이 필요한 파일만 복사하고, 이외의 코드는 그대로 둡니다.
|
||||
|
||||
이 파일이 **자주 바뀌지 않기 때문에**, 도커는 파일을 탐지하여 이 단계의 **캐시**를 사용하여 다음 단계에서도 캐시를 사용할 수 있도록 합니다.
|
||||
|
||||
4. 요구 조건 파일에 있는 패키지 종속성을 설치합니다.
|
||||
|
||||
`--no-cache-dir` 옵션은 `pip`에게 다운로드한 패키지들을 로컬 환경에 저장하지 않도록 전달합니다. 이는 마치 같은 패키지를 설치하기 위해 오직 `pip`만 다시 실행하면 될 것 같지만, 컨테이너로 작업하는 경우 그렇지는 않습니다.
|
||||
|
||||
!!! 노트
|
||||
`--no-cache-dir` 는 오직 `pip`와 관련되어 있으며, 도커나 컨테이너와는 무관합니다.
|
||||
|
||||
`--upgrade` 옵션은 `pip`에게 설치된 패키지들을 업데이트하도록 합니다.
|
||||
|
||||
이전 단계에서 파일을 복사한 것이 **도커 캐시**에 의해 탐지되기 때문에, 이 단계에서도 가능한 한 **도커 캐시**를 사용하게 됩니다.
|
||||
|
||||
이 단계에서 캐시를 사용하면 **매번** 모든 종속성을 다운로드 받고 설치할 필요가 없어, 개발 과정에서 이미지를 지속적으로 생성하는 데에 드는 **시간**을 많이 **절약**할 수 있습니다.
|
||||
|
||||
5. `/code` 디렉터리에 `./app` 디렉터리를 복사합니다.
|
||||
|
||||
**자주 변경되는** 모든 코드를 포함하고 있기 때문에, 도커 **캐시**는 이 단계나 **이후의 단계에서** 잘 사용되지 않습니다.
|
||||
|
||||
그러므로 컨테이너 이미지 빌드 시간을 최적화하기 위해 `Dockerfile`의 **거의 끝 부분**에 입력하는 것이 중요합니다.
|
||||
|
||||
6. `uvicorn` 서버를 실행하기 위해 **커맨드**를 설정합니다.
|
||||
|
||||
`CMD`는 문자열 리스트를 입력받고, 각 문자열은 커맨드 라인의 각 줄에 입력할 문자열입니다.
|
||||
|
||||
이 커맨드는 **현재 워킹 디렉터리**에서 실행되며, 이는 위에서 `WORKDIR /code`로 설정한 `/code` 디렉터리와 같습니다.
|
||||
|
||||
프로그램이 `/code`에서 시작하고 그 속에 `./app` 디렉터리가 여러분의 코드와 함께 들어있기 때문에, **Uvicorn**은 이를 보고 `app`을 `app.main`으로부터 **불러 올** 것입니다.
|
||||
|
||||
!!! 팁
|
||||
각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆
|
||||
|
||||
이제 여러분은 다음과 같은 디렉터리 구조를 가지고 있을 것입니다:
|
||||
|
||||
```
|
||||
.
|
||||
├── app
|
||||
│ ├── __init__.py
|
||||
│ └── main.py
|
||||
├── Dockerfile
|
||||
└── requirements.txt
|
||||
```
|
||||
|
||||
#### TLS 종료 프록시의 배후
|
||||
|
||||
만약 여러분이 컨테이너를 Nginx 또는 Traefik과 같은 TLS 종료 프록시 (로드 밸런서) 뒤에서 실행하고 있다면, `--proxy-headers` 옵션을 더하는 것이 좋습니다. 이 옵션은 Uvicorn에게 어플리케이션이 HTTPS 등의 뒤에서 실행되고 있으므로 프록시에서 전송된 헤더를 신뢰할 수 있다고 알립니다.
|
||||
|
||||
```Dockerfile
|
||||
CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"]
|
||||
```
|
||||
|
||||
#### 도커 캐시
|
||||
|
||||
이 `Dockerfile`에는 중요한 트릭이 있는데, 처음에는 **의존성이 있는 파일만** 복사하고, 나머지 코드는 그대로 둡니다. 왜 이런 방법을 써야하는지 설명하겠습니다.
|
||||
|
||||
```Dockerfile
|
||||
COPY ./requirements.txt /code/requirements.txt
|
||||
```
|
||||
|
||||
도커와 다른 도구들은 컨테이너 이미지를 **증가하는 방식으로 빌드**합니다. `Dockerfile`의 맨 윗 부분부터 시작해, 레이어 위에 새로운 레이어를 더하는 방식으로, `Dockerfile`의 각 지시 사항으로 부터 생성된 어떤 파일이든 더해갑니다.
|
||||
|
||||
도커 그리고 이와 유사한 도구들은 이미지 생성 시에 **내부 캐시**를 사용합니다. 만약 어떤 파일이 마지막으로 컨테이너 이미지를 빌드한 때로부터 바뀌지 않았다면, 파일을 다시 복사하여 새로운 레이어를 처음부터 생성하는 것이 아니라, 마지막에 생성했던 **같은 레이어를 재사용**합니다.
|
||||
|
||||
단지 파일 복사를 지양하는 것으로 효율이 많이 향상되는 것은 아니지만, 그 단계에서 캐시를 사용했기 때문에, **다음 단계에서도 마찬가지로 캐시를 사용**할 수 있습니다. 예를 들어, 다음과 같은 의존성을 설치하는 지시 사항을 위한 캐시를 사용할 수 있습니다:
|
||||
|
||||
```Dockerfile
|
||||
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
```
|
||||
|
||||
패키지를 포함하는 파일은 **자주 변경되지 않습니다**. 따라서 해당 파일만 복사하므로서, 도커는 그 단계의 **캐시를 사용**할 수 있습니다.
|
||||
|
||||
그 다음으로, 도커는 **다음 단계에서** 의존성을 다운로드하고 설치하는 **캐시를 사용**할 수 있게 됩니다. 바로 이 과정에서 우리는 **많은 시간을 절약**하게 됩니다. ✨ ...그리고 기다리는 지루함도 피할 수 있습니다. 😪😆
|
||||
|
||||
패키지 의존성을 다운로드 받고 설치하는 데이는 **수 분이 걸릴 수 있지만**, **캐시**를 사용하면 최대 **수 초만에** 끝낼 수 있습니다.
|
||||
|
||||
또한 여러분이 개발 과정에서 코드의 변경 사항이 반영되었는지 확인하기 위해 컨테이너 이미지를 계속해서 빌드하면, 절약된 시간은 축적되어 더욱 커질 것입니다.
|
||||
|
||||
그리고 나서 `Dockerfile`의 거의 끝 부분에서, 모든 코드를 복사합니다. 이것이 **가장 빈번하게 변경**되는 부분이며, 대부분의 경우에 이 다음 단계에서는 캐시를 사용할 수 없기 때문에 가장 마지막에 둡니다.
|
||||
|
||||
```Dockerfile
|
||||
COPY ./app /code/app
|
||||
```
|
||||
|
||||
### 도커 이미지 생성하기
|
||||
|
||||
이제 모든 파일이 제자리에 있으니, 컨테이너 이미지를 빌드합니다.
|
||||
|
||||
* (여러분의 `Dockerfile`과 `app` 디렉터리가 위치한) 프로젝트 디렉터리로 이동합니다.
|
||||
* FastAPI 이미지를 빌드합니다:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ docker build -t myimage .
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
!!! 팁
|
||||
맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다.
|
||||
|
||||
이 경우에는 현재 디렉터리(`.`)와 같습니다.
|
||||
|
||||
### 도커 컨테이너 시작하기
|
||||
|
||||
* 여러분의 이미지에 기반하여 컨테이너를 실행합니다:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ docker run -d --name mycontainer -p 80:80 myimage
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## 체크하기
|
||||
|
||||
여러분의 도커 컨테이너 URL에서 실행 사항을 체크할 수 있습니다. 예를 들어: <a href="http://192.168.99.100/items/5?q=somequery" class="external-link" target="_blank">http://192.168.99.100/items/5?q=somequery</a> 또는 <a href="http://127.0.0.1/items/5?q=somequery" class="external-link" target="_blank">http://127.0.0.1/items/5?q=somequery</a> (또는 동일하게, 여러분의 도커 호스트를 이용해서 체크할 수도 있습니다).
|
||||
|
||||
아래와 비슷한 것을 보게 될 것입니다:
|
||||
|
||||
```JSON
|
||||
{"item_id": 5, "q": "somequery"}
|
||||
```
|
||||
|
||||
## 인터랙티브 API 문서
|
||||
|
||||
이제 여러분은 <a href="http://192.168.99.100/docs" class="external-link" target="_blank">http://192.168.99.100/docs</a> 또는 <a href="http://127.0.0.1/docs" class="external-link" target="_blank">http://127.0.0.1/docs</a>로 이동할 수 있습니다(또는, 여러분의 도커 호스트를 이용할 수 있습니다).
|
||||
|
||||
여러분은 자동으로 생성된 인터랙티브 API(<a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank">Swagger UI</a>에서 제공된)를 볼 수 있습니다:
|
||||
|
||||

|
||||
|
||||
## 대안 API 문서
|
||||
|
||||
또한 여러분은 <a href="http://192.168.99.100/redoc" class="external-link" target="_blank">http://192.168.99.100/redoc</a> 또는 <a href="http://127.0.0.1/redoc" class="external-link" target="_blank">http://127.0.0.1/redoc</a>으로 이동할 수 있습니다(또는, 여러분의 도커 호스트를 이용할 수 있습니다).
|
||||
|
||||
여러분은 자동으로 생성된 대안 문서(<a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank">ReDoc</a>에서 제공된)를 볼 수 있습니다:
|
||||
|
||||

|
||||
|
||||
## 단일 파일 FastAPI로 도커 이미지 생성하기
|
||||
|
||||
만약 여러분의 FastAPI가 하나의 파일이라면, 예를 들어 `./app` 디렉터리 없이 `main.py` 파일만으로 이루어져 있다면, 파일 구조는 다음과 유사할 것입니다:
|
||||
|
||||
```
|
||||
.
|
||||
├── Dockerfile
|
||||
├── main.py
|
||||
└── requirements.txt
|
||||
```
|
||||
|
||||
그러면 여러분들은 `Dockerfile` 내에 있는 파일을 복사하기 위해 그저 상응하는 경로를 바꾸기만 하면 됩니다:
|
||||
|
||||
```{ .dockerfile .annotate hl_lines="10 13" }
|
||||
FROM python:3.9
|
||||
|
||||
WORKDIR /code
|
||||
|
||||
COPY ./requirements.txt /code/requirements.txt
|
||||
|
||||
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
|
||||
# (1)
|
||||
COPY ./main.py /code/
|
||||
|
||||
# (2)
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
```
|
||||
|
||||
1. `main.py` 파일을 `/code` 디렉터리로 곧바로 복사합니다(`./app` 디렉터리는 고려하지 않습니다).
|
||||
|
||||
2. Uvicorn을 실행해 `app` 객체를 (`app.main` 대신) `main`으로 부터 불러오도록 합니다.
|
||||
|
||||
그 다음 Uvicorn 커맨드를 조정해서 FastAPI 객체를 불러오는데 `app.main` 대신에 새로운 모듈 `main`을 사용하도록 합니다.
|
||||
|
||||
## 배포 개념
|
||||
|
||||
이제 컨테이너의 측면에서 [배포 개념](./concepts.md){.internal-link target=_blank}에서 다루었던 것과 같은 배포 개념에 대해 이야기해 보겠습니다.
|
||||
|
||||
컨테이너는 주로 어플리케이션을 빌드하고 배포하기 위한 과정을 단순화하는 도구이지만, **배포 개념**에 대한 특정한 접근법을 강요하지 않기 때문에 가능한 배포 전략에는 여러가지가 있습니다.
|
||||
|
||||
**좋은 소식**은 서로 다른 전략들을 포괄하는 배포 개념이 있다는 점입니다. 🎉
|
||||
|
||||
컨테이너 측면에서 **배포 개념**을 리뷰해 보겠습니다:
|
||||
|
||||
* HTTPS
|
||||
* 구동하기
|
||||
* 재시작
|
||||
* 복제 (실행 중인 프로세스 개수)
|
||||
* 메모리
|
||||
* 시작하기 전 단계들
|
||||
|
||||
## HTTPS
|
||||
|
||||
만약 우리가 FastAPI 어플리케이션을 위한 **컨테이너 이미지**에만 집중한다면 (그리고 나중에 실행될 **컨테이너**에), HTTPS는 일반적으로 다른 도구에 의해 **외부적으로** 다루어질 것 입니다.
|
||||
|
||||
**HTTPS**와 **인증서**의 **자동** 취득을 다루는 것은 다른 컨테이너가 될 수 있는데, 예를 들어 <a href="https://traefik.io/" class="external-link" target="_blank">Traefik</a>을 사용하는 것입니다.
|
||||
|
||||
!!! 팁
|
||||
Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다.
|
||||
|
||||
대안적으로, HTTPS는 클라우드 제공자에 의해 서비스의 일환으로 다루어질 수도 있습니다 (이때도 어플리케이션은 여전히 컨테이너에서 실행될 것입니다).
|
||||
|
||||
## 구동과 재시작
|
||||
|
||||
여러분의 컨테이너를 **시작하고 실행하는** 데에 일반적으로 사용되는 도구는 따로 있습니다.
|
||||
|
||||
이는 **도커** 자체일 수도 있고, **도커 컴포즈**, **쿠버네티스**, **클라우드 서비스** 등이 될 수 있습니다.
|
||||
|
||||
대부분 (또는 전체) 경우에, 컨테이너를 구동하거나 고장시에 재시작하도록 하는 간단한 옵션이 있습니다. 예를 들어, 도커에서는, 커맨드 라인 옵션 `--restart` 입니다.
|
||||
|
||||
컨테이너를 사용하지 않고서는, 어플리케이션을 구동하고 재시작하는 것이 매우 번거롭고 어려울 수 있습니다. 하지만 **컨테이너를 사용한다면** 대부분의 경우에 이런 기능은 기본적으로 포함되어 있습니다. ✨
|
||||
|
||||
## 복제 - 프로세스 개수
|
||||
|
||||
만약 여러분이 **쿠버네티스**와 머신 <abbr title="A group of machines that are configured to be connected and work together in some way.">클러스터</abbr>, 도커 스왐 모드, 노마드, 또는 다른 여러 머신 위에 분산 컨테이너를 관리하는 복잡한 시스템을 다루고 있다면, 여러분은 각 컨테이너에서 (워커와 함께 사용하는 Gunicorn 같은) **프로세스 매니저** 대신 **클러스터 레벨**에서 **복제를 다루**고 싶을 것입니다.
|
||||
|
||||
쿠버네티스와 같은 분산 컨테이너 관리 시스템 중 일부는 일반적으로 들어오는 요청에 대한 **로드 밸런싱**을 지원하면서 **컨테이너 복제**를 다루는 통합된 방법을 가지고 있습니다. 모두 **클러스터 레벨**에서 말이죠.
|
||||
|
||||
이런 경우에, 여러분은 [위에서 묘사된 것](#dockerfile)처럼 **처음부터 도커 이미지를** 빌드해서, 의존성을 설치하고, Uvicorn 워커를 관리하는 Gunicorn 대신 **단일 Uvicorn 프로세스**를 실행하고 싶을 것입니다.
|
||||
|
||||
### 로드 밸런서
|
||||
|
||||
컨테이너로 작업할 때, 여러분은 일반적으로 **메인 포트의 상황을 감지하는** 요소를 가지고 있을 것입니다. 이는 **HTTPS**를 다루는 **TLS 종료 프록시**와 같은 다른 컨테이너일 수도 있고, 유사한 다른 도구일 수도 있습니다.
|
||||
|
||||
이 요소가 요청들의 **로드**를 읽어들이고 각 워커에게 (바라건대) **균형적으로** 분배한다면, 이 요소는 일반적으로 **로드 밸런서**라고 불립니다.
|
||||
|
||||
!!! 팁
|
||||
HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다.
|
||||
|
||||
또한 컨테이너로 작업할 때, 컨테이너를 시작하고 관리하기 위해 사용한 것과 동일한 시스템은 이미 해당 **로드 밸런서**로 부터 여러분의 앱에 해당하는 컨테이너로 **네트워크 통신**(예를 들어, HTTP 요청)을 전송하는 내부적인 도구를 가지고 있을 것입니다 (여기서도 로드 밸런서는 **TLS 종료 프록시**일 수 있습니다).
|
||||
|
||||
### 하나의 로드 밸런서 - 다중 워커 컨테이너
|
||||
|
||||
**쿠버네티스**나 또는 다른 분산 컨테이너 관리 시스템으로 작업할 때, 시스템 내부의 네트워킹 메커니즘을 이용함으로써 메인 **포트**를 감지하고 있는 단일 **로드 밸런서**는 여러분의 앱에서 실행되고 있는 **여러개의 컨테이너**에 통신(요청들)을 전송할 수 있게 됩니다.
|
||||
|
||||
여러분의 앱에서 실행되고 있는 각각의 컨테이너는 일반적으로 **하나의 프로세스**만 가질 것입니다 (예를 들어, FastAPI 어플리케이션에서 실행되는 하나의 Uvicorn 프로세스처럼). 이 컨테이너들은 모두 같은 것을 실행하는 점에서 **동일한 컨테이너**이지만, 프로세스, 메모리 등은 공유하지 않습니다. 이 방식으로 여러분은 CPU의 **서로 다른 코어들** 또는 **서로 다른 머신들**을 **병렬화**하는 이점을 얻을 수 있습니다.
|
||||
|
||||
또한 **로드 밸런서**가 있는 분산 컨테이너 시스템은 여러분의 앱에 있는 컨테이너 각각에 **차례대로 요청을 분산**시킬 것 입니다. 따라서 각 요청은 여러분의 앱에서 실행되는 여러개의 **복제된 컨테이너들** 중 하나에 의해 다루어질 것 입니다.
|
||||
|
||||
그리고 일반적으로 **로드 밸런서**는 여러분의 클러스터에 있는 *다른* 앱으로 가는 요청들도 다룰 수 있으며 (예를 들어, 다른 도메인으로 가거나 다른 URL 경로 접두사를 가지는 경우), 이 통신들을 클러스터에 있는 *바로 그 다른* 어플리케이션으로 제대로 전송할 수 있습니다.
|
||||
|
||||
### 단일 프로세스를 가지는 컨테이너
|
||||
|
||||
이 시나리오의 경우, 여러분은 이미 클러스터 레벨에서 복제를 다루고 있을 것이므로 **컨테이너 당 단일 (Uvicorn) 프로세스**를 가지고자 할 것입니다.
|
||||
|
||||
따라서, 여러분은 Gunicorn 이나 Uvicorn 워커, 또는 Uvicorn 워커를 사용하는 Uvicorn 매니저와 같은 프로세스 매니저를 가지고 싶어하지 **않을** 것입니다. 여러분은 컨테이너 당 **단일 Uvicorn 프로세스**를 가지고 싶어할 것입니다 (그러나 아마도 다중 컨테이너를 가질 것입니다).
|
||||
|
||||
이미 여러분이 클러스터 시스템을 관리하고 있으므로, (Uvicorn 워커를 관리하는 Gunicorn 이나 Uvicorn 처럼) 컨테이너 내에 다른 프로세스 매니저를 가지는 것은 **불필요한 복잡성**만 더하게 될 것입니다.
|
||||
|
||||
### 다중 프로세스를 가지는 컨테이너와 특수한 경우들
|
||||
|
||||
당연한 말이지만, 여러분이 내부적으로 **Uvicorn 워커 프로세스들**를 시작하는 **Gunicorn 프로세스 매니저**를 가지는 단일 컨테이너를 원하는 **특수한 경우**도 있을 것입니다.
|
||||
|
||||
그런 경우에, 여러분들은 **Gunicorn**을 프로세스 매니저로 포함하는 **공식 도커 이미지**를 사용할 수 있습니다. 이 프로세스 매니저는 다중 **Uvicorn 워커 프로세스들**을 실행하며, 디폴트 세팅으로 현재 CPU 코어에 기반하여 자동으로 워커 개수를 조정합니다. 이 사항에 대해서는 아래의 [Gunicorn과 함께하는 공식 도커 이미지 - Uvicorn](#official-docker-image-with-gunicorn-uvicorn)에서 더 다루겠습니다.
|
||||
|
||||
이런 경우에 해당하는 몇가지 예시가 있습니다:
|
||||
|
||||
#### 단순한 앱
|
||||
|
||||
만약 여러분의 어플리케이션이 **충분히 단순**해서 (적어도 아직은) 프로세스 개수를 파인-튠 할 필요가 없거나 클러스터가 아닌 **단일 서버**에서 실행하고 있다면, 여러분은 컨테이너 내에 프로세스 매니저를 사용하거나 (공식 도커 이미지에서) 자동으로 설정되는 디폴트 값을 사용할 수 있습니다.
|
||||
|
||||
#### 도커 구성
|
||||
|
||||
여러분은 **도커 컴포즈**로 (클러스터가 아닌) **단일 서버로** 배포할 수 있으며, 이 경우에 공유된 네트워크와 **로드 밸런싱**을 포함하는 (도커 컴포즈로) 컨테이너의 복제를 관리하는 단순한 방법이 없을 수도 있습니다.
|
||||
|
||||
그렇다면 여러분은 **프로세스 매니저**와 함께 내부에 **몇개의 워커 프로세스들**을 시작하는 **단일 컨테이너**를 필요로 할 수 있습니다.
|
||||
|
||||
#### Prometheus와 다른 이유들
|
||||
|
||||
여러분은 **단일 프로세스**를 가지는 **다중 컨테이너** 대신 **다중 프로세스**를 가지는 **단일 컨테이너**를 채택하는 **다른 이유**가 있을 수 있습니다.
|
||||
|
||||
예를 들어 (여러분의 장치 설정에 따라) Prometheus 익스포터와 같이 같은 컨테이너에 들어오는 **각 요청에 대해** 접근권한을 가지는 도구를 사용할 수 있습니다.
|
||||
|
||||
이 경우에 여러분이 **여러개의 컨테이너들**을 가지고 있다면, Prometheus가 **메트릭을 읽어 들일 때**, 디폴트로 **매번 하나의 컨테이너**(특정 리퀘스트를 관리하는 바로 그 컨테이너)로 부터 읽어들일 것입니다. 이는 모든 복제된 컨테이너에 대해 **축적된 메트릭들**을 읽어들이는 것과 대비됩니다.
|
||||
|
||||
그렇다면 이 경우에는 **다중 프로세스**를 가지는 **하나의 컨테이너**를 두어서 같은 컨테이너에서 모든 내부 프로세스에 대한 Prometheus 메트릭을 수집하는 로컬 도구(예를 들어 Prometheus 익스포터 같은)를 두어서 이 메그릭들을 하나의 컨테이너에 내에서 공유하는 방법이 더 단순할 것입니다.
|
||||
|
||||
---
|
||||
|
||||
요점은, 이 중의 **어느것도** 여러분들이 반드시 따라야하는 **확정된 사실**이 아니라는 것입니다. 여러분은 이 아이디어들을 **여러분의 고유한 이용 사례를 평가**하는데 사용하고, 여러분의 시스템에 가장 적합한 접근법이 어떤 것인지 결정하며, 다음의 개념들을 관리하는 방법을 확인할 수 있습니다:
|
||||
|
||||
* 보안 - HTTPS
|
||||
* 구동하기
|
||||
* 재시작
|
||||
* 복제 (실행 중인 프로세스 개수)
|
||||
* 메모리
|
||||
* 시작하기 전 단계들
|
||||
|
||||
## 메모리
|
||||
|
||||
만약 여러분이 **컨테이너 당 단일 프로세스**를 실행한다면, 여러분은 각 컨테이너(복제된 경우에는 여러개의 컨테이너들)에 대해 잘 정의되고, 안정적이며, 제한된 용량의 메모리 소비량을 가지고 있을 것입니다.
|
||||
|
||||
그러면 여러분의 컨테이너 관리 시스템(예를 들어 **쿠버네티스**) 설정에서 앞서 정의된 것과 같은 메모리 제한과 요구사항을 설정할 수 있습니다. 이런 방법으로 **가용 머신**이 필요로하는 메모리와 클러스터에 있는 가용 머신들을 염두에 두고 **컨테이너를 복제**할 수 있습니다.
|
||||
|
||||
만약 여러분의 어플리케이션이 **단순**하다면, 이것은 **문제가 되지 않을** 것이고, 고정된 메모리 제한을 구체화할 필요도 없을 것입니다. 하지만 여러분의 어플리케이션이 (예를 들어 **머신 러닝** 모델같이) **많은 메모리를 소요한다면**, 어플리케이션이 얼마나 많은 양의 메모리를 사용하는지 확인하고 **각 머신에서** 사용하는 **컨테이너의 수**를 조정할 필요가 있습니다 (그리고 필요에 따라 여러분의 클러스터에 머신을 추가할 수 있습니다).
|
||||
|
||||
만약 여러분이 **컨테이너 당 여러개의 프로세스**를 실행한다면 (예를 들어 공식 도커 이미지 처럼), 여러분은 시작된 프로세스 개수가 가용한 것 보다 **더 많은 메모리를 소비**하지 않는지 확인해야 합니다.
|
||||
|
||||
## 시작하기 전 단계들과 컨테이너
|
||||
|
||||
만약 여러분이 컨테이너(예를 들어 도커, 쿠버네티스)를 사용한다면, 여러분이 접근할 수 있는 주요 방법은 크게 두가지가 있습니다.
|
||||
|
||||
### 다중 컨테이너
|
||||
|
||||
만약 여러분이 **여러개의 컨테이너**를 가지고 있다면, 아마도 각각의 컨테이너는 **하나의 프로세스**를 가지고 있을 것입니다(예를 들어, **쿠버네티스** 클러스터에서). 그러면 여러분은 복제된 워커 컨테이너를 실행하기 **이전에**, 하나의 컨테이너에 있는 **이전의 단계들을** 수행하는 단일 프로세스를 가지는 **별도의 컨테이너들**을 가지고 싶을 것입니다.
|
||||
|
||||
!!! 정보
|
||||
만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" class="external-link" target="_blank">Init Container</a>일 것입니다.
|
||||
|
||||
만약 여러분의 이용 사례에서 이전 단계들을 **병렬적으로 여러번** 수행하는데에 문제가 없다면 (예를 들어 데이터베이스 이전을 실행하지 않고 데이터베이스가 준비되었는지 확인만 하는 경우), 메인 프로세스를 시작하기 전에 이 단계들을 각 컨테이너에 넣을 수 있습니다.
|
||||
|
||||
### 단일 컨테이너
|
||||
|
||||
만약 여러분의 셋업이 **다중 프로세스**(또는 하나의 프로세스)를 시작하는 **하나의 컨테이너**를 가지는 단순한 셋업이라면, 사전 단계들을 앱을 포함하는 프로세스를 시작하기 직전에 같은 컨테이너에서 실행할 수 있습니다. 공식 도커 이미지는 이를 내부적으로 지원합니다.
|
||||
|
||||
## Gunicorn과 함께하는 공식 도커 이미지 - Uvicorn
|
||||
|
||||
앞 챕터에서 자세하게 설명된 것 처럼, Uvicorn 워커와 같이 실행되는 Gunicorn을 포함하는 공식 도커 이미지가 있습니다: [서버 워커 - Uvicorn과 함께하는 Gunicorn](./server-workers.md){.internal-link target=_blank}.
|
||||
|
||||
이 이미지는 주로 위에서 설명된 상황에서 유용할 것입니다: [다중 프로세스를 가지는 컨테이너와 특수한 경우들](#containers-with-multiple-processes-and-special-cases).
|
||||
|
||||
* <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
|
||||
|
||||
!!! 경고
|
||||
여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다.
|
||||
|
||||
이 이미지는 가능한 CPU 코어에 기반한 **몇개의 워커 프로세스**를 설정하는 **자동-튜닝** 메커니즘을 포함하고 있습니다.
|
||||
|
||||
이 이미지는 **민감한 디폴트** 값을 가지고 있지만, 여러분들은 여전히 **환경 변수** 또는 설정 파일을 통해 설정값을 수정하고 업데이트 할 수 있습니다.
|
||||
|
||||
또한 스크립트를 통해 <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker#pre_start_path" class="external-link" target="_blank">**시작하기 전 사전 단계**</a>를 실행하는 것을 지원합니다.
|
||||
|
||||
!!! 팁
|
||||
모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: <a href="https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker" class="external-link" target="_blank">tiangolo/uvicorn-gunicorn-fastapi</a>.
|
||||
|
||||
### 공식 도커 이미지에 있는 프로세스 개수
|
||||
|
||||
이 이미지에 있는 **프로세스 개수**는 가용한 CPU **코어들**로 부터 **자동으로 계산**됩니다.
|
||||
|
||||
이것이 의미하는 바는 이미지가 CPU로부터 **최대한의 성능**을 **쥐어짜낸다**는 것입니다.
|
||||
|
||||
여러분은 이 설정 값을 **환경 변수**나 기타 방법들로 조정할 수 있습니다.
|
||||
|
||||
그러나 프로세스의 개수가 컨테이너가 실행되고 있는 CPU에 의존한다는 것은 또한 **소요되는 메모리의 크기** 또한 이에 의존한다는 것을 의미합니다.
|
||||
|
||||
그렇기 때문에, 만약 여러분의 어플리케이션이 많은 메모리를 요구하고 (예를 들어 머신러닝 모델처럼), 여러분의 서버가 CPU 코어 수는 많지만 **적은 메모리**를 가지고 있다면, 여러분의 컨테이너는 가용한 메모리보다 많은 메모리를 사용하려고 시도할 수 있으며, 결국 퍼포먼스를 크게 떨어뜨릴 수 있습니다(심지어 고장이 날 수도 있습니다). 🚨
|
||||
|
||||
### `Dockerfile` 생성하기
|
||||
|
||||
이 이미지에 기반해 `Dockerfile`을 생성하는 방법은 다음과 같습니다:
|
||||
|
||||
```Dockerfile
|
||||
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9
|
||||
|
||||
COPY ./requirements.txt /app/requirements.txt
|
||||
|
||||
RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt
|
||||
|
||||
COPY ./app /app
|
||||
```
|
||||
|
||||
### 더 큰 어플리케이션
|
||||
|
||||
만약 여러분이 [다중 파일을 가지는 더 큰 어플리케이션](../tutorial/bigger-applications.md){.internal-link target=_blank}을 생성하는 섹션을 따랐다면, 여러분의 `Dockerfile`은 대신 이렇게 생겼을 것입니다:
|
||||
|
||||
```Dockerfile hl_lines="7"
|
||||
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9
|
||||
|
||||
COPY ./requirements.txt /app/requirements.txt
|
||||
|
||||
RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt
|
||||
|
||||
COPY ./app /app/app
|
||||
```
|
||||
|
||||
### 언제 사용할까
|
||||
|
||||
여러분들이 **쿠버네티스**(또는 유사한 다른 도구) 사용하거나 클러스터 레벨에서 다중 컨테이너를 이용해 이미 **사본**을 설정하고 있다면, 공식 베이스 이미지(또는 유사한 다른 이미지)를 사용하지 **않는** 것 좋습니다. 그런 경우에 여러분은 다음에 설명된 것 처럼 **처음부터 이미지를 빌드하는 것**이 더 낫습니다: [FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi).
|
||||
|
||||
이 이미지는 위의 [다중 프로세스를 가지는 컨테이너와 특수한 경우들](#containers-with-multiple-processes-and-special-cases)에서 설명된 특수한 경우에 대해서만 주로 유용할 것입니다. 예를 들어, 만약 여러분의 어플리케이션이 **충분히 단순**해서 CPU에 기반한 디폴트 프로세스 개수를 설정하는 것이 잘 작동한다면, 클러스터 레벨에서 수동으로 사본을 설정할 필요가 없을 것이고, 여러분의 앱에서 하나 이상의 컨테이너를 실행하지도 않을 것입니다. 또는 만약에 여러분이 **도커 컴포즈**로 배포하거나, 단일 서버에서 실행하거나 하는 경우에도 마찬가지입니다.
|
||||
|
||||
## 컨테이너 이미지 배포하기
|
||||
|
||||
컨테이너 (도커) 이미지를 완성한 뒤에 이를 배포하는 방법에는 여러가지 방법이 있습니다.
|
||||
|
||||
예를 들어:
|
||||
|
||||
* 단일 서버에서 **도커 컴포즈**로 배포하기
|
||||
* **쿠버네티스** 클러스터로 배포하기
|
||||
* 도커 스왐 모드 클러스터로 배포하기
|
||||
* 노마드 같은 다른 도구로 배포하기
|
||||
* 여러분의 컨테이너 이미지를 배포해주는 클라우드 서비스로 배포하기
|
||||
|
||||
## Poetry의 도커 이미지
|
||||
|
||||
만약 여러분들이 프로젝트 의존성을 관리하기 위해 <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a>를 사용한다면, 도커의 멀티-스테이지 빌딩을 사용할 수 있습니다:
|
||||
|
||||
```{ .dockerfile .annotate }
|
||||
# (1)
|
||||
FROM python:3.9 as requirements-stage
|
||||
|
||||
# (2)
|
||||
WORKDIR /tmp
|
||||
|
||||
# (3)
|
||||
RUN pip install poetry
|
||||
|
||||
# (4)
|
||||
COPY ./pyproject.toml ./poetry.lock* /tmp/
|
||||
|
||||
# (5)
|
||||
RUN poetry export -f requirements.txt --output requirements.txt --without-hashes
|
||||
|
||||
# (6)
|
||||
FROM python:3.9
|
||||
|
||||
# (7)
|
||||
WORKDIR /code
|
||||
|
||||
# (8)
|
||||
COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt
|
||||
|
||||
# (9)
|
||||
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
||||
|
||||
# (10)
|
||||
COPY ./app /code/app
|
||||
|
||||
# (11)
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
|
||||
```
|
||||
|
||||
1. 첫 스테이지로, `requirements-stage`라고 이름 붙였습니다.
|
||||
|
||||
2. `/tmp`를 현재의 워킹 디렉터리로 설정합니다.
|
||||
|
||||
이 위치에 우리는 `requirements.txt` 파일을 생성할 것입니다.
|
||||
|
||||
3. 이 도커 스테이지에서 Poetry를 설치합니다.
|
||||
|
||||
4. 파일 `pyproject.toml`와 `poetry.lock`를 `/tmp` 디렉터리로 복사합니다.
|
||||
|
||||
`./poetry.lock*` (`*`로 끝나는) 파일을 사용하기 때문에, 파일이 아직 사용가능하지 않더라도 고장나지 않을 것입니다.
|
||||
|
||||
5. `requirements.txt` 파일을 생성합니다.
|
||||
|
||||
6. 이것이 마지막 스테이지로, 여기에 위치한 모든 것이 마지막 컨테이너 이미지에 포함될 것입니다.
|
||||
|
||||
7. 현재의 워킹 디렉터리를 `/code`로 설정합니다.
|
||||
|
||||
8. 파일 `requirements.txt`를 `/code` 디렉터리로 복사합니다.
|
||||
|
||||
이 파일은 오직 이전의 도커 스테이지에만 존재하며, 때문에 복사하기 위해서 `--from-requirements-stage` 옵션이 필요합니다.
|
||||
|
||||
9. 생성된 `requirements.txt` 파일에 패키지 의존성을 설치합니다.
|
||||
|
||||
10. `app` 디렉터리를 `/code` 디렉터리로 복사합니다.
|
||||
|
||||
11. `uvicorn` 커맨드를 실행하여, `app.main`에서 불러온 `app` 객체를 사용하도록 합니다.
|
||||
|
||||
!!! 팁
|
||||
버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다.
|
||||
|
||||
**도커 스테이지**란 `Dockefile`의 일부로서 나중에 사용하기 위한 파일들을 생성하기 위한 **일시적인 컨테이너 이미지**로 작동합니다.
|
||||
|
||||
첫 스테이지는 오직 **Poetry를 설치**하고 Poetry의 `pyproject.toml` 파일로부터 프로젝트 의존성을 위한 **`requirements.txt`를 생성**하기 위해 사용됩니다.
|
||||
|
||||
이 `requirements.txt` 파일은 **다음 스테이지**에서 `pip`로 사용될 것입니다.
|
||||
|
||||
마지막 컨테이너 이미지에는 **오직 마지막 스테이지만** 보존됩니다. 이전 스테이지(들)은 버려집니다.
|
||||
|
||||
Poetry를 사용할 때 **도커 멀티-스테이지 빌드**를 사용하는 것이 좋은데, 여러분들의 프로젝트 의존성을 설치하기 위해 마지막 컨테이너 이미지에 **오직** `requirements.txt` 파일만 필요하지, Poetry와 그 의존성은 있을 필요가 없기 때문입니다.
|
||||
|
||||
이 다음 (또한 마지막) 스테이지에서 여러분들은 이전에 설명된 것과 비슷한 방식으로 방식으로 이미지를 빌드할 수 있습니다.
|
||||
|
||||
### TLS 종료 프록시의 배후 - Poetry
|
||||
|
||||
이전에 언급한 것과 같이, 만약 여러분이 컨테이너를 Nginx 또는 Traefik과 같은 TLS 종료 프록시 (로드 밸런서) 뒤에서 실행하고 있다면, 커맨드에 `--proxy-headers` 옵션을 추가합니다:
|
||||
|
||||
```Dockerfile
|
||||
CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"]
|
||||
```
|
||||
|
||||
## 요약
|
||||
|
||||
컨테이너 시스템(예를 들어 **도커**나 **쿠버네티스**)을 사용하여 모든 **배포 개념**을 다루는 것은 꽤 간단합니다:
|
||||
|
||||
* HTTPS
|
||||
* 구동하기
|
||||
* 재시작
|
||||
* 복제 (실행 중인 프로세스 개수)
|
||||
* 메모리
|
||||
* 시작하기 전 단계들
|
||||
|
||||
대부분의 경우에서 여러분은 어떤 베이스 이미지도 사용하지 않고 공식 파이썬 도커 이미지에 기반해 **처음부터 컨테이너 이미지를 빌드**할 것입니다.
|
||||
|
||||
`Dockerfile`에 있는 지시 사항을 **순서대로** 다루고 **도커 캐시**를 사용하는 것으로 여러분은 **빌드 시간을 최소화**할 수 있으며, 이로써 생산성을 최대화할 수 있습니다 (그리고 지루함을 피할 수 있죠) 😎
|
||||
|
||||
특별한 경우에는, FastAPI를 위한 공식 도커 이미지를 사용할 수도 있습니다. 🤓
|
||||
21
docs/ko/docs/deployment/index.md
Normal file
21
docs/ko/docs/deployment/index.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# 배포하기 - 들어가면서
|
||||
|
||||
**FastAPI**을 배포하는 것은 비교적 쉽습니다.
|
||||
|
||||
## 배포의 의미
|
||||
|
||||
**배포**란 애플리케이션을 **사용자가 사용**할 수 있도록 하는 데 필요한 단계를 수행하는 것을 의미합니다.
|
||||
|
||||
**웹 API**의 경우, 일반적으로 **사용자**가 중단이나 오류 없이 애플리케이션에 효율적으로 **접근**할 수 있도록 좋은 성능, 안정성 등을 제공하는 **서버 프로그램과** 함께 **원격 시스템**에 이를 설치하는 작업을 의미합니다.
|
||||
|
||||
이는 지속적으로 코드를 변경하고, 지우고, 수정하고, 개발 서버를 중지했다가 다시 시작하는 등의 **개발** 단계와 대조됩니다.
|
||||
|
||||
## 배포 전략
|
||||
|
||||
사용하는 도구나 특정 사례에 따라 여러 가지 방법이 있습니다.
|
||||
|
||||
배포도구들을 사용하여 직접 **서버에 배포**하거나, 배포작업의 일부를 수행하는 **클라우드 서비스** 또는 다른 방법을 사용할 수도 있습니다.
|
||||
|
||||
**FastAPI** 애플리케이션을 배포할 때 선택할 수 있는 몇 가지 주요 방법을 보여 드리겠습니다 (대부분 다른 유형의 웹 애플리케이션에도 적용됩니다).
|
||||
|
||||
다음 차례에 자세한 내용과 이를 위한 몇 가지 기술을 볼 수 있습니다. ✨
|
||||
180
docs/ko/docs/deployment/server-workers.md
Normal file
180
docs/ko/docs/deployment/server-workers.md
Normal file
@@ -0,0 +1,180 @@
|
||||
# 서버 워커 - 구니콘과 유비콘
|
||||
|
||||
전단계에서의 배포 개념들을 다시 확인해보겠습니다:
|
||||
|
||||
* 보안 - HTTPS
|
||||
* 서버 시작과 동시에 실행하기
|
||||
* 재시작
|
||||
* **복제본 (실행 중인 프로세스의 숫자)**
|
||||
* 메모리
|
||||
* 시작하기 전의 여러 단계들
|
||||
|
||||
지금까지 문서의 모든 튜토리얼을 참고하여 **단일 프로세스**로 Uvicorn과 같은 **서버 프로그램**을 실행했을 것입니다.
|
||||
|
||||
애플리케이션을 배포할 때 **다중 코어**를 활용하고 더 많은 요청을 처리할 수 있도록 **프로세스 복제본**이 필요합니다.
|
||||
|
||||
전 과정이었던 [배포 개념들](./concepts.md){.internal-link target=_blank}에서 본 것처럼 여러가지 방법이 존재합니다.
|
||||
|
||||
지금부터 <a href="https://gunicorn.org/" class="external-link" target="_blank">**구니콘**</a>을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다.
|
||||
|
||||
!!! 정보
|
||||
만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](./docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다.
|
||||
|
||||
특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다.
|
||||
|
||||
## 구니콘과 유비콘 워커
|
||||
|
||||
**Gunicorn**은 **WSGI 표준**을 주로 사용하는 애플리케이션 서버입니다. 이것은 구니콘이 플라스크와 쟝고와 같은 애플리케이션을 제공할 수 있다는 것을 의미합니다. 구니콘 자체는 최신 **<a href="https://asgi.readthedocs.io/en/latest/" class="external-link" target="_blank">ASGI 표준</a>**을 사용하기 때문에 FastAPI와 호환되지 않습니다.
|
||||
|
||||
하지만 구니콘은 **프로세스 관리자**역할을 하고 사용자에게 특정 **워커 프로세스 클래스**를 알려줍니다. 그런 다음 구니콘은 해당 클래스를 사용하여 하나 이상의 **워커 프로세스**를 시작합니다.
|
||||
|
||||
그리고 **유비콘**은 **구니콘과 호환되는 워커 클래스**가 있습니다.
|
||||
|
||||
이 조합을 사용하여 구니콘은 **프로세스 관리자** 역할을 하며 **포트**와 **IP**를 관찰하고, **유비콘 클래스**를 실행하는 워커 프로세스로 통신 정보를 **전송**합니다.
|
||||
|
||||
그리고 나서 구니콘과 호환되는 **유비콘 워커** 클래스는 구니콘이 보낸 데이터를 FastAPI에서 사용하기 위한 ASGI 표준으로 변환하는 일을 담당합니다.
|
||||
|
||||
## 구니콘과 유비콘 설치하기
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "uvicorn[standard]" gunicorn
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
이 명령어는 유비콘 `standard` 추가 패키지(좋은 성능을 위한)와 구니콘을 설치할 것입니다.
|
||||
|
||||
## 구니콘을 유비콘 워커와 함께 실행하기
|
||||
|
||||
설치 후 구니콘 실행하기:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80
|
||||
|
||||
[19499] [INFO] Starting gunicorn 20.1.0
|
||||
[19499] [INFO] Listening at: http://0.0.0.0:80 (19499)
|
||||
[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker
|
||||
[19511] [INFO] Booting worker with pid: 19511
|
||||
[19513] [INFO] Booting worker with pid: 19513
|
||||
[19514] [INFO] Booting worker with pid: 19514
|
||||
[19515] [INFO] Booting worker with pid: 19515
|
||||
[19511] [INFO] Started server process [19511]
|
||||
[19511] [INFO] Waiting for application startup.
|
||||
[19511] [INFO] Application startup complete.
|
||||
[19513] [INFO] Started server process [19513]
|
||||
[19513] [INFO] Waiting for application startup.
|
||||
[19513] [INFO] Application startup complete.
|
||||
[19514] [INFO] Started server process [19514]
|
||||
[19514] [INFO] Waiting for application startup.
|
||||
[19514] [INFO] Application startup complete.
|
||||
[19515] [INFO] Started server process [19515]
|
||||
[19515] [INFO] Waiting for application startup.
|
||||
[19515] [INFO] Application startup complete.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
각 옵션이 무엇을 의미하는지 살펴봅시다:
|
||||
|
||||
* 이것은 유비콘과 똑같은 문법입니다. `main`은 파이썬 모듈 네임 "`main`"을 의미하므로 `main.py`파일을 뜻합니다. 그리고 `app`은 **FastAPI** 어플리케이션이 들어 있는 변수의 이름입니다.
|
||||
* `main:app`이 파이썬의 `import` 문법과 흡사한 면이 있다는 걸 알 수 있습니다:
|
||||
|
||||
```Python
|
||||
from main import app
|
||||
```
|
||||
|
||||
* 곧, `main:app`안에 있는 콜론의 의미는 파이썬에서 `from main import app`에서의 `import`와 같습니다.
|
||||
* `--workers`: 사용할 워커 프로세스의 개수이며 숫자만큼의 유비콘 워커를 실행합니다. 이 예제에서는 4개의 워커를 실행합니다.
|
||||
* `--worker-class`: 워커 프로세스에서 사용하기 위한 구니콘과 호환되는 워커클래스.
|
||||
* 이런식으로 구니콘이 import하여 사용할 수 있는 클래스를 전달해줍니다:
|
||||
|
||||
```Python
|
||||
import uvicorn.workers.UvicornWorker
|
||||
```
|
||||
|
||||
* `--bind`: 구니콘이 관찰할 IP와 포트를 의미합니다. 콜론 (`:`)을 사용하여 IP와 포트를 구분합니다.
|
||||
* 만약에 `--bind 0.0.0.0:80` (구니콘 옵션) 대신 유비콘을 직접 실행하고 싶다면 `--host 0.0.0.0`과 `--port 80`을 사용해야 합니다.
|
||||
|
||||
출력에서 각 프로세스에 대한 **PID** (process ID)를 확인할 수 있습니다. (단순한 숫자입니다)
|
||||
|
||||
출력 내용:
|
||||
|
||||
* 구니콘 **프로세스 매니저**는 PID `19499`로 실행됩니다. (직접 실행할 경우 숫자가 다를 수 있습니다)
|
||||
* 다음으로 `Listening at: http://0.0.0.0:80`을 시작합니다.
|
||||
* 그런 다음 사용해야할 `uvicorn.workers.UvicornWorker`의 워커클래스를 탐지합니다.
|
||||
* 그리고 PID `19511`, `19513`, `19514`, 그리고 `19515`를 가진 **4개의 워커**를 실행합니다.
|
||||
|
||||
|
||||
또한 구니콘은 워커의 수를 유지하기 위해 **죽은 프로세스**를 관리하고 **재시작**하는 작업을 책임집니다. 이것은 이번 장 상단 목록의 **재시작** 개념을 부분적으로 도와주는 것입니다.
|
||||
|
||||
그럼에도 불구하고 필요할 경우 외부에서 **구니콘을 재시작**하고, 혹은 **서버를 시작할 때 실행**할 수 있도록 하고 싶어할 것입니다.
|
||||
|
||||
## 유비콘과 워커
|
||||
|
||||
유비콘은 몇 개의 **워커 프로세스**와 함께 실행할 수 있는 선택지가 있습니다.
|
||||
|
||||
그럼에도 불구하고, 유비콘은 워커 프로세스를 다루는 데에 있어서 구니콘보다 더 제한적입니다. 따라서 이 수준(파이썬 수준)의 프로세스 관리자를 사용하려면 구니콘을 프로세스 관리자로 사용하는 것이 좋습니다.
|
||||
|
||||
보통 이렇게 실행할 수 있습니다:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
|
||||
<font color="#A6E22E">INFO</font>: Uvicorn running on <b>http://0.0.0.0:8080</b> (Press CTRL+C to quit)
|
||||
<font color="#A6E22E">INFO</font>: Started parent process [<font color="#A1EFE4"><b>27365</b></font>]
|
||||
<font color="#A6E22E">INFO</font>: Started server process [<font color="#A1EFE4">27368</font>]
|
||||
<font color="#A6E22E">INFO</font>: Waiting for application startup.
|
||||
<font color="#A6E22E">INFO</font>: Application startup complete.
|
||||
<font color="#A6E22E">INFO</font>: Started server process [<font color="#A1EFE4">27369</font>]
|
||||
<font color="#A6E22E">INFO</font>: Waiting for application startup.
|
||||
<font color="#A6E22E">INFO</font>: Application startup complete.
|
||||
<font color="#A6E22E">INFO</font>: Started server process [<font color="#A1EFE4">27370</font>]
|
||||
<font color="#A6E22E">INFO</font>: Waiting for application startup.
|
||||
<font color="#A6E22E">INFO</font>: Application startup complete.
|
||||
<font color="#A6E22E">INFO</font>: Started server process [<font color="#A1EFE4">27367</font>]
|
||||
<font color="#A6E22E">INFO</font>: Waiting for application startup.
|
||||
<font color="#A6E22E">INFO</font>: Application startup complete.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
새로운 옵션인 `--workers`은 유비콘에게 4개의 워커 프로세스를 사용한다고 알려줍니다.
|
||||
|
||||
각 프로세스의 **PID**를 확인할 수 있습니다. `27365`는 상위 프로세스(**프로세스 매니저**), 그리고 각각의 워커프로세스는 `27368`, `27369`, `27370`, 그리고 `27367`입니다.
|
||||
|
||||
## 배포 개념들
|
||||
|
||||
여기에서는 **유비콘 워커 프로세스**를 관리하는 **구니콘**(또는 유비콘)을 사용하여 애플리케이션을 **병렬화**하고, CPU **멀티 코어**의 장점을 활용하고, **더 많은 요청**을 처리할 수 있는 방법을 살펴보았습니다.
|
||||
|
||||
워커를 사용하는 것은 배포 개념 목록에서 주로 **복제본** 부분과 **재시작**에 약간 도움이 되지만 다른 배포 개념들도 다루어야 합니다:
|
||||
|
||||
* **보안 - HTTPS**
|
||||
* **서버 시작과 동시에 실행하기**
|
||||
* ***재시작***
|
||||
* 복제본 (실행 중인 프로세스의 숫자)
|
||||
* **메모리**
|
||||
* **시작하기 전의 여러 단계들**
|
||||
|
||||
|
||||
## 컨테이너와 도커
|
||||
|
||||
다음 장인 [FastAPI와 컨테이너 - 도커](./docker.md){.internal-link target=_blank}에서 다른 **배포 개념들**을 다루는 전략들을 알려드리겠습니다.
|
||||
|
||||
또한 간단한 케이스에서 사용할 수 있는, **구니콘과 유비콘 워커**가 포함돼 있는 **공식 도커 이미지**와 함께 몇 가지 기본 구성을 보여드리겠습니다.
|
||||
|
||||
그리고 단일 유비콘 프로세스(구니콘 없이)를 실행할 수 있도록 **사용자 자신의 이미지를 처음부터 구축**하는 방법도 보여드리겠습니다. 이는 간단한 과정이며, **쿠버네티스**와 같은 분산 컨테이너 관리 시스템을 사용할 때 수행할 작업입니다.
|
||||
|
||||
## 요약
|
||||
|
||||
당신은 **구니콘**(또는 유비콘)을 유비콘 워커와 함께 프로세스 관리자로 사용하여 **멀티-코어 CPU**를 활용하는 **멀티 프로세스를 병렬로 실행**할 수 있습니다.
|
||||
|
||||
다른 배포 개념을 직접 다루면서 **자신만의 배포 시스템**을 구성하는 경우 이러한 도구와 개념들을 활용할 수 있습니다.
|
||||
|
||||
다음 장에서 컨테이너(예: 도커 및 쿠버네티스)와 함께하는 **FastAPI**에 대해 배워보세요. 이러한 툴에는 다른 **배포 개념**들을 간단히 해결할 수 있는 방법이 있습니다. ✨
|
||||
203
docs/ko/docs/features.md
Normal file
203
docs/ko/docs/features.md
Normal file
@@ -0,0 +1,203 @@
|
||||
---
|
||||
hide:
|
||||
- navigation
|
||||
---
|
||||
|
||||
# 기능
|
||||
|
||||
## FastAPI의 기능
|
||||
|
||||
**FastAPI**는 다음과 같은 기능을 제공합니다:
|
||||
|
||||
### 개방형 표준을 기반으로
|
||||
|
||||
* <abbr title="엔드포인트, 라우트로도 알려져 있습니다">경로</abbr><abbr title="POST, GET, PUT, DELETE와 같은 HTTP 메소드로 알려져 있습니다">작동</abbr>, 매개변수, 본문 요청, 보안 그 외의 선언을 포함한 API 생성을 위한 <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank"><strong>OpenAPI</strong></a>
|
||||
* <a href="https://json-schema.org/" class="external-link" target="_blank"><strong>JSON Schema</strong></a> (OpenAPI 자체가 JSON Schema를 기반으로 하고 있습니다)를 사용한 자동 데이터 모델 문서화.
|
||||
* 단순히 떠올려서 덧붙인 기능이 아닙니다. 세심한 검토를 거친 후, 이러한 표준을 기반으로 설계되었습니다.
|
||||
* 이는 또한 다양한 언어로 자동적인 **클라이언트 코드 생성**을 사용할 수 있게 지원합니다.
|
||||
|
||||
### 문서 자동화
|
||||
|
||||
대화형 API 문서와 웹 탐색 유저 인터페이스를 제공합니다. 프레임워크가 OpenAPI를 기반으로 하기에, 2가지 옵션이 기본적으로 들어간 여러 옵션이 존재합니다.
|
||||
|
||||
* 대화형 탐색 <a href="https://github.com/swagger-api/swagger-ui" class="external-link" target="_blank"><strong>Swagger UI</strong></a>를 이용해, 브라우저에서 바로 여러분의 API를 호출하거나 테스트할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
* <a href="https://github.com/Rebilly/ReDoc" class="external-link" target="_blank"><strong>ReDoc</strong></a>을 이용해 API 문서화를 대체할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
### 그저 현대 파이썬
|
||||
|
||||
(Pydantic 덕분에) FastAPI는 표준 **파이썬 3.6 타입** 선언에 기반하고 있습니다. 새로 배울 문법이 없습니다. 그저 표준적인 현대 파이썬입니다.
|
||||
|
||||
만약 여러분이 파이썬 타입을 어떻게 사용하는지에 대한 2분 정도의 복습이 필요하다면 (비록 여러분이 FastAPI를 사용하지 않는다 하더라도), 다음의 짧은 자습서를 확인하세요: [파이썬 타입](python-types.md){.internal-link target=\_blank}.
|
||||
|
||||
여러분은 타입을 이용한 표준 파이썬을 다음과 같이 적을 수 있습니다:
|
||||
|
||||
```Python
|
||||
from datetime import date
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
# 변수를 str로 선언
|
||||
# 그 후 함수 안에서 편집기 지원을 받으세요
|
||||
def main(user_id: str):
|
||||
return user_id
|
||||
|
||||
|
||||
# Pydantic 모델
|
||||
class User(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
joined: date
|
||||
```
|
||||
|
||||
위의 코드는 다음과 같이 사용될 수 있습니다:
|
||||
|
||||
```Python
|
||||
my_user: User = User(id=3, name="John Doe", joined="2018-07-19")
|
||||
|
||||
second_user_data = {
|
||||
"id": 4,
|
||||
"name": "Mary",
|
||||
"joined": "2018-11-30",
|
||||
}
|
||||
|
||||
my_second_user: User = User(**second_user_data)
|
||||
```
|
||||
|
||||
!!! 정보
|
||||
`**second_user_data`가 뜻하는 것:
|
||||
|
||||
`second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")`
|
||||
|
||||
### 편집기 지원
|
||||
|
||||
모든 프레임워크는 사용하기 쉽고 직관적으로 설계되었으며, 좋은 개발 경험을 보장하기 위해 개발을 시작하기도 전에 모든 결정들은 여러 편집기에서 테스트됩니다.
|
||||
|
||||
최근 파이썬 개발자 설문조사에서 <a href="https://www.jetbrains.com/research/python-developers-survey-2017/#tools-and-features" class="external-link" target="_blank">"자동 완성"이 가장 많이 사용되는 기능</a>이라는 것이 밝혀졌습니다.
|
||||
|
||||
**FastAPI** 프레임워크의 모든 부분은 이를 충족하기 위해 설계되었습니다. 자동완성은 어느 곳에서나 작동합니다.
|
||||
|
||||
여러분은 문서로 다시 돌아올 일이 거의 없을 겁니다.
|
||||
|
||||
다음은 편집기가 어떻게 여러분을 도와주는지 보여줍니다:
|
||||
|
||||
* <a href="https://code.visualstudio.com/" class="external-link" target="_blank">Visual Studio Code</a>에서:
|
||||
|
||||

|
||||
|
||||
* <a href="https://www.jetbrains.com/pycharm/" class="external-link" target="_blank">PyCharm</a>에서:
|
||||
|
||||

|
||||
|
||||
여러분이 이전에 불가능하다고 고려했던 코드도 완성할 수 있을 겁니다. 예를 들어, 요청에서 전달되는 (중첩될 수도 있는)JSON 본문 내부에 있는 `price` 키입니다.
|
||||
|
||||
잘못된 키 이름을 적을 일도, 문서를 왔다 갔다할 일도 없으며, 혹은 마지막으로 `username` 또는 `user_name`을 사용했는지 찾기 위해 위 아래로 스크롤할 일도 없습니다.
|
||||
|
||||
### 토막 정보
|
||||
|
||||
어느 곳에서나 선택적 구성이 가능한 모든 것에 합리적인 기본값이 설정되어 있습니다. 모든 매개변수는 여러분이 필요하거나, 원하는 API를 정의하기 위해 미세하게 조정할 수 있습니다.
|
||||
|
||||
하지만 기본적으로 모든 것이 "그냥 작동합니다".
|
||||
|
||||
### 검증
|
||||
|
||||
* 다음을 포함한, 대부분의 (혹은 모든?) 파이썬 **데이터 타입** 검증할 수 있습니다:
|
||||
* JSON 객체 (`dict`).
|
||||
* 아이템 타입을 정의하는 JSON 배열 (`list`).
|
||||
* 최소 길이와 최대 길이를 정의하는 문자열 (`str`) 필드.
|
||||
* 최솟값과 최댓값을 가지는 숫자 (`int`, `float`), 그 외.
|
||||
|
||||
* 다음과 같이 더욱 이색적인 타입에 대해 검증할 수 있습니다:
|
||||
* URL.
|
||||
* 이메일.
|
||||
* UUID.
|
||||
* ...다른 것들.
|
||||
|
||||
모든 검증은 견고하면서 잘 확립된 **Pydantic**에 의해 처리됩니다.
|
||||
|
||||
### 보안과 인증
|
||||
|
||||
보안과 인증이 통합되어 있습니다. 데이터베이스나 데이터 모델과의 타협없이 사용할 수 있습니다.
|
||||
|
||||
다음을 포함하는, 모든 보안 스키마가 OpenAPI에 정의되어 있습니다.
|
||||
|
||||
* HTTP Basic.
|
||||
* **OAuth2** (**JWT tokens** 또한 포함). [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=\_blank}에 있는 자습서를 확인해 보세요.
|
||||
* 다음에 들어 있는 API 키:
|
||||
* 헤더.
|
||||
* 매개변수.
|
||||
* 쿠키 및 그 외.
|
||||
|
||||
추가적으로 (**세션 쿠키**를 포함한) 모든 보안 기능은 Starlette에 있습니다.
|
||||
|
||||
모두 재사용할 수 있는 도구와 컴포넌트로 만들어져 있어 여러분의 시스템, 데이터 저장소, 관계형 및 NoSQL 데이터베이스 등과 쉽게 통합할 수 있습니다.
|
||||
|
||||
### 의존성 주입
|
||||
|
||||
FastAPI는 사용하기 매우 간편하지만, 엄청난 <abbr title='"컴포넌트", "자원", "서비스", "제공자"로도 알려진'><strong>의존성 주입</strong></abbr>시스템을 포함하고 있습니다.
|
||||
|
||||
* 의존성은 의존성을 가질수도 있어, 이를 통해 의존성의 계층이나 **의존성의 "그래프"**를 형성합니다.
|
||||
* 모든 것이 프레임워크에 의해 **자동적으로 처리됩니다**.
|
||||
* 모든 의존성은 요청에서 데이터를 요구하여 자동 문서화와 **경로 작동 제약을 강화할 수 있습니다**.
|
||||
* 의존성에서 정의된 _경로 작동_ 매개변수에 대해서도 **자동 검증**이 이루어 집니다.
|
||||
* 복잡한 사용자의 인증 시스템, **데이터베이스 연결**, 등등을 지원합니다.
|
||||
* 데이터베이스, 프론트엔드 등과 관련되어 **타협하지 않아도 됩니다**. 하지만 그 모든 것과 쉽게 통합이 가능합니다.
|
||||
|
||||
### 제한 없는 "플러그인"
|
||||
|
||||
또는 다른 방법으로, 그것들을 사용할 필요 없이 필요한 코드만 임포트할 수 있습니다.
|
||||
|
||||
어느 통합도 (의존성과 함께) 사용하기 쉽게 설계되어 있어, *경로 작동*에 사용된 것과 동일한 구조와 문법을 사용하여 2줄의 코드로 여러분의 어플리케이션에 사용할 "플러그인"을 만들 수 있습니다.
|
||||
|
||||
### 테스트 결과
|
||||
|
||||
* 100% <abbr title="자동적으로 테스트된 코드의 양">테스트 범위</abbr>.
|
||||
* 100% <abbr title="파이썬의 타입 어노테이션, 이를 통해 여러분의 편집기와 외부 도구는 여러분에게 더 나은 지원을 할 수 있습니다">타입이 명시된</abbr> 코드 베이스.
|
||||
* 상용 어플리케이션에서의 사용.
|
||||
|
||||
## Starlette 기능
|
||||
|
||||
**FastAPI**는 <a href="https://www.starlette.io/" class="external-link" target="_blank"><strong>Starlette</strong></a>를 기반으로 구축되었으며, 이와 완전히 호환됩니다. 따라서, 여러분이 보유하고 있는 어떤 추가적인 Starlette 코드도 작동할 것입니다.
|
||||
|
||||
`FastAPI`는 실제로 `Starlette`의 하위 클래스입니다. 그래서, 여러분이 이미 Starlette을 알고 있거나 사용하고 있으면, 대부분의 기능이 같은 방식으로 작동할 것입니다.
|
||||
|
||||
**FastAPI**를 사용하면 여러분은 **Starlette**의 기능 대부분을 얻게 될 것입니다(FastAPI가 단순히 Starlette를 강화했기 때문입니다):
|
||||
|
||||
* 아주 인상적인 성능. 이는 <a href="https://github.com/encode/starlette#performance" class="external-link" target="_blank">**NodeJS**와 **Go**와 동등하게 사용 가능한 가장 빠른 파이썬 프레임워크 중 하나입니다</a>.
|
||||
* **WebSocket** 지원.
|
||||
* 프로세스 내의 백그라운드 작업.
|
||||
* 시작과 종료 이벤트.
|
||||
* HTTPX 기반 테스트 클라이언트.
|
||||
* **CORS**, GZip, 정적 파일, 스트리밍 응답.
|
||||
* **세션과 쿠키** 지원.
|
||||
* 100% 테스트 범위.
|
||||
* 100% 타입이 명시된 코드 베이스.
|
||||
|
||||
## Pydantic 기능
|
||||
|
||||
**FastAPI**는 <a href="https://pydantic-docs.helpmanual.io" class="external-link" target="_blank"><strong>Pydantic</strong></a>을 기반으로 하며 Pydantic과 완벽하게 호환됩니다. 그래서 어느 추가적인 Pydantic 코드를 여러분이 가지고 있든 작동할 것입니다.
|
||||
|
||||
Pydantic을 기반으로 하는, 데이터베이스를 위한 <abbr title="Object-Relational Mapper">ORM</abbr>, <abbr title="Object-Document Mapper">ODM</abbr>을 포함한 외부 라이브러리를 포함합니다.
|
||||
|
||||
이는 모든 것이 자동으로 검증되기 때문에, 많은 경우에서 요청을 통해 얻은 동일한 객체를, **직접 데이터베이스로** 넘겨줄 수 있습니다.
|
||||
|
||||
반대로도 마찬가지이며, 많은 경우에서 여러분은 **직접 클라이언트로** 그저 객체를 넘겨줄 수 있습니다.
|
||||
|
||||
**FastAPI**를 사용하면 (모든 데이터 처리를 위해 FastAPI가 Pydantic을 기반으로 하기 있기에) **Pydantic**의 모든 기능을 얻게 됩니다:
|
||||
|
||||
* **어렵지 않은 언어**:
|
||||
* 새로운 스키마 정의 마이크로 언어를 배우지 않아도 됩니다.
|
||||
* 여러분이 파이썬 타입을 안다면, 여러분은 Pydantic을 어떻게 사용하는지 아는 겁니다.
|
||||
* 여러분의 **<abbr title="통합 개발 환경, 코드 편집기와 비슷합니다">IDE</abbr>/<abbr title="코드 에러를 확인하는 프로그램">린터</abbr>/뇌**와 잘 어울립니다:
|
||||
* Pydantic 데이터 구조는 단순 여러분이 정의한 클래스의 인스턴스이기 때문에, 자동 완성, 린팅, mypy 그리고 여러분의 직관까지 여러분의 검증된 데이터와 올바르게 작동합니다.
|
||||
* **복잡한 구조**를 검증합니다:
|
||||
* 계층적인 Pydantic 모델, 파이썬 `typing`의 `List`와 `Dict`, 그 외를 사용합니다.
|
||||
* 그리고 검증자는 복잡한 데이터 스키마를 명확하고 쉽게 정의 및 확인하며 JSON 스키마로 문서화합니다.
|
||||
* 여러분은 깊게 **중첩된 JSON** 객체를 가질 수 있으며, 이 객체 모두 검증하고 설명을 붙일 수 있습니다.
|
||||
* **확장 가능성**:
|
||||
* Pydantic은 사용자 정의 데이터 타입을 정의할 수 있게 하거나, 검증자 데코레이터가 붙은 모델의 메소드를 사용하여 검증을 확장할 수 있습니다.
|
||||
* 100% 테스트 범위.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user