From 589de8cb5825eeaa9f12f9cea69388d3b992d70d Mon Sep 17 00:00:00 2001 From: "ryusuke.miyaji" Date: Wed, 3 Jun 2020 02:01:49 +0900 Subject: [PATCH 01/17] add ja and translate key feature --- docs/en/mkdocs.yml | 1 + docs/es/mkdocs.yml | 1 + docs/ja/docs/index.md | 445 ++++++++++++++++++++++++++++++++++++++++++ docs/ja/mkdocs.yml | 66 +++++++ docs/pt/mkdocs.yml | 1 + docs/zh/mkdocs.yml | 1 + 6 files changed, 515 insertions(+) create mode 100644 docs/ja/docs/index.md create mode 100644 docs/ja/mkdocs.yml diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 1dac0fde477fe..abbe25450e8f8 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -22,6 +22,7 @@ nav: - Languages: - en: / - es: /es/ + - ja: /ja/ - pt: /pt/ - zh: /zh/ - features.md diff --git a/docs/es/mkdocs.yml b/docs/es/mkdocs.yml index 1d42105307fa1..e87262b697013 100644 --- a/docs/es/mkdocs.yml +++ b/docs/es/mkdocs.yml @@ -22,6 +22,7 @@ nav: - Languages: - en: / - es: /es/ + - ja: /ja/ - pt: /pt/ - zh: /zh/ - features.md diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md new file mode 100644 index 0000000000000..3dfc0c65218b3 --- /dev/null +++ b/docs/ja/docs/index.md @@ -0,0 +1,445 @@ +{!../../../docs/missing-translation.md!} + +

+ FastAPI +

+

+ FastAPI framework, high performance, easy to learn, fast to code, ready for production +

+

+ + Build Status + + + Coverage + + + Package version + + + Join the chat at https://gitter.im/tiangolo/fastapi + +

+ +--- + +**ドキュメント**: https://fastapi.tiangolo.com + +**ソースコード**: https://github.com/tiangolo/fastapi + +--- + +FastAPI は、モダンで、速い(高いパフォーマンスな)、標準の Python 型ヒントに基づいて、Python 3.6 以降のバージョンで API をビルドするための Web フレームワークです。 + +主な特徴: + +- **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげです)。 [最も高速な Python フレームワークの一つです](#performance). + +- **高速なコーディング**: 開発速度を約 200%~300%向上させます。 \* +- **少ないバグ**: 開発者起因のヒューマンエラーを約 40%削減します。 \* +- **直感的**: 素晴らしいエディタのサポートや オートコンプリート。 デバッグ時間を削減します。 +- **簡単**: 簡単に利用、習得できるようにデザインされています。ドキュメントを読む時間を削減します。 +- **短い**: コードの重複を最小限にしています。各パラメータからの複数の機能。少ないバグ。 +- **堅牢性**: 自動対話ドキュメントを使用して、本番環境で使用できるコードを取得します。 +- **Standards-based**: API のオープンスタンダードに基づいており、完全に互換性があります: OpenAPI (以前は Swagger として知られていました) や JSON スキーマ. + +\* 社内開発チームでのテストに基づき見積もってから、本番アプリケーションの構築します。 + +## Opinions + +"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_I’m over the moon excited about **FastAPI**. It’s so fun!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" + +"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +## **Typer**, the FastAPI of CLIs + + + +If you are building a CLI app to be used in the terminal instead of a web API, check out **Typer**. + +**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀 + +## Requirements + +Python 3.6+ + +FastAPI stands on the shoulders of giants: + +- Starlette for the web parts. +- Pydantic for the data parts. + +## Installation + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +You will also need an ASGI server, for production such as Uvicorn or Hypercorn. + +
+ +```console +$ pip install uvicorn + +---> 100% +``` + +
+ +## Example + +### Create it + +- Create a file `main.py` with: + +```Python +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: str = None): + return {"item_id": item_id, "q": q} +``` + +
+Or use async def... + +If your code uses `async` / `await`, use `async def`: + +```Python hl_lines="7 12" +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: str = None): + return {"item_id": item_id, "q": q} +``` + +**Note**: + +If you don't know, check the _"In a hurry?"_ section about `async` and `await` in the docs. + +
+ +### Run it + +Run the server with: + +
+ +```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. +``` + +
+ +
+About the command uvicorn main:app --reload... + +The command `uvicorn main:app` refers to: + +- `main`: the file `main.py` (the Python "module"). +- `app`: the object created inside of `main.py` with the line `app = FastAPI()`. +- `--reload`: make the server restart after code changes. Only do this for development. + +
+ +### Check it + +Open your browser at http://127.0.0.1:8000/items/5?q=somequery. + +You will see the JSON response as: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +You already created an API that: + +- Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`. +- Both _paths_ take `GET` operations (also known as HTTP _methods_). +- The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`. +- The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`. + +### Interactive API docs + +Now go to http://127.0.0.1:8000/docs. + +You will see the automatic interactive API documentation (provided by Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternative API docs + +And now, go to http://127.0.0.1:8000/redoc. + +You will see the alternative automatic documentation (provided by ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Example upgrade + +Now modify the file `main.py` to receive a body from a `PUT` request. + +Declare the body using standard Python types, thanks to Pydantic. + +```Python hl_lines="2 7 8 9 10 23 24 25" +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: bool = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: str = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +The server should reload automatically (because you added `--reload` to the `uvicorn` command above). + +### Interactive API docs upgrade + +Now go to http://127.0.0.1:8000/docs. + +- The interactive API documentation will be automatically updated, including the new body: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +- Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +- Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternative API docs upgrade + +And now, go to http://127.0.0.1:8000/redoc. + +- The alternative documentation will also reflect the new query parameter and body: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Recap + +In summary, you declare **once** the types of parameters, body, etc. as function parameters. + +You do that with standard modern Python types. + +You don't have to learn a new syntax, the methods or classes of a specific library, etc. + +Just standard **Python 3.6+**. + +For example, for an `int`: + +```Python +item_id: int +``` + +or for a more complex `Item` model: + +```Python +item: Item +``` + +...and with that single declaration you get: + +- Editor support, including: + - Completion. + - Type checks. +- Validation of data: + - Automatic and clear errors when the data is invalid. + - Validation even for deeply nested JSON objects. +- Conversion of input data: coming from the network to Python data and types. Reading from: + - JSON. + - Path parameters. + - Query parameters. + - Cookies. + - Headers. + - Forms. + - Files. +- Conversion of output data: converting from Python data and types to network data (as JSON): + - Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc). + - `datetime` objects. + - `UUID` objects. + - Database models. + - ...and many more. +- Automatic interactive API documentation, including 2 alternative user interfaces: + - Swagger UI. + - ReDoc. + +--- + +Coming back to the previous code example, **FastAPI** will: + +- Validate that there is an `item_id` in the path for `GET` and `PUT` requests. +- Validate that the `item_id` is of type `int` for `GET` and `PUT` requests. + - If it is not, the client will see a useful, clear error. +- Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. + - As the `q` parameter is declared with `= None`, it is optional. + - Without the `None` it would be required (as is the body in the case with `PUT`). +- For `PUT` requests to `/items/{item_id}`, Read the body as JSON: + - Check that it has a required attribute `name` that should be a `str`. + - Check that it has a required attribute `price` that has to be a `float`. + - Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. + - All this would also work for deeply nested JSON objects. +- Convert from and to JSON automatically. +- Document everything with OpenAPI, that can be used by: + - Interactive documentation systems. + - Automatic client code generation systems, for many languages. +- Provide 2 interactive documentation web interfaces directly. + +--- + +We just scratched the surface, but you already get the idea of how it all works. + +Try changing the line with: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...from: + +```Python + ... "item_name": item.name ... +``` + +...to: + +```Python + ... "item_price": item.price ... +``` + +...and see how your editor will auto-complete the attributes and know their types: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +For a more complete example including more features, see the Tutorial - User Guide. + +**Spoiler alert**: the tutorial - user guide includes: + +- Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**. +- How to set **validation constraints** as `maximum_length` or `regex`. +- A very powerful and easy to use **Dependency Injection** system. +- Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth. +- More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic). +- Many extra features (thanks to Starlette) as: + - **WebSockets** + - **GraphQL** + - extremely easy tests based on `requests` and `pytest` + - **CORS** + - **Cookie Sessions** + - ...and more. + +## Performance + +Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (\*) + +To understand more about it, see the section Benchmarks. + +## Optional Dependencies + +Used by Pydantic: + +- ujson - for faster JSON "parsing". +- email_validator - for email validation. + +Used by Starlette: + +- requests - Required if you want to use the `TestClient`. +- aiofiles - Required if you want to use `FileResponse` or `StaticFiles`. +- jinja2 - Required if you want to use the default template configuration. +- python-multipart - Required if you want to support form "parsing", with `request.form()`. +- itsdangerous - Required for `SessionMiddleware` support. +- pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI). +- graphene - Required for `GraphQLApp` support. +- ujson - Required if you want to use `UJSONResponse`. + +Used by FastAPI / Starlette: + +- uvicorn - for the server that loads and serves your application. +- orjson - Required if you want to use `ORJSONResponse`. + +You can install all of these with `pip install fastapi[all]`. + +## License + +This project is licensed under the terms of the MIT license. diff --git a/docs/ja/mkdocs.yml b/docs/ja/mkdocs.yml new file mode 100644 index 0000000000000..8f55ea67cb2f7 --- /dev/null +++ b/docs/ja/mkdocs.yml @@ -0,0 +1,66 @@ +site_name: FastAPI +site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production +site_url: https://fastapi.tiangolo.com/ja/ +theme: + name: material + palette: + primary: teal + accent: amber + icon: + repo: fontawesome/brands/github-alt + logo: https://fastapi.tiangolo.com/img/icon-white.svg + favicon: https://fastapi.tiangolo.com/img/favicon.png + language: ja +repo_name: tiangolo/fastapi +repo_url: https://github.com/tiangolo/fastapi +edit_uri: '' +google_analytics: +- UA-133183413-1 +- auto +nav: +- FastAPI: index.md +- Languages: + - en: / + - es: /es/ + - ja: /ja/ + - pt: /pt/ + - zh: /zh/ +markdown_extensions: +- toc: + permalink: true +- markdown.extensions.codehilite: + guess_lang: false +- markdown_include.include: + base_path: docs +- admonition +- codehilite +- extra +- pymdownx.superfences: + custom_fences: + - name: mermaid + class: mermaid + format: !!python/name:pymdownx.superfences.fence_div_format '' +- pymdownx.tabbed +extra: + social: + - icon: fontawesome/brands/github-alt + link: https://github.com/tiangolo/typer + - icon: fontawesome/brands/twitter + link: https://twitter.com/tiangolo + - icon: fontawesome/brands/linkedin + link: https://www.linkedin.com/in/tiangolo + - icon: fontawesome/brands/dev + link: https://dev.to/tiangolo + - icon: fontawesome/brands/medium + link: https://medium.com/@tiangolo + - icon: fontawesome/solid/globe + link: https://tiangolo.com +extra_css: +- https://fastapi.tiangolo.com/css/termynal.css +- https://fastapi.tiangolo.com/css/custom.css +extra_javascript: +- https://unpkg.com/mermaid@8.4.6/dist/mermaid.min.js +- https://fastapi.tiangolo.com/js/termynal.js +- https://fastapi.tiangolo.com/js/custom.js +- https://fastapi.tiangolo.com/js/chat.js +- https://sidecar.gitter.im/dist/sidecar.v1.js diff --git a/docs/pt/mkdocs.yml b/docs/pt/mkdocs.yml index 105f7e6f32fbb..d54ac1c9d1ac1 100644 --- a/docs/pt/mkdocs.yml +++ b/docs/pt/mkdocs.yml @@ -22,6 +22,7 @@ nav: - Languages: - en: / - es: /es/ + - ja: /ja/ - pt: /pt/ - zh: /zh/ - features.md diff --git a/docs/zh/mkdocs.yml b/docs/zh/mkdocs.yml index 75a7e9707670b..26b7433c4b22d 100644 --- a/docs/zh/mkdocs.yml +++ b/docs/zh/mkdocs.yml @@ -22,6 +22,7 @@ nav: - Languages: - en: / - es: /es/ + - ja: /ja/ - pt: /pt/ - zh: /zh/ - features.md From 2b5be360f7c4f350318366121e12d21c89b7a1db Mon Sep 17 00:00:00 2001 From: ryuckel <36391432+ryuckel@users.noreply.github.com> Date: Wed, 3 Jun 2020 02:42:55 +0900 Subject: [PATCH 02/17] translate opinions --- docs/ja/docs/index.md | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 3dfc0c65218b3..9bc79f005843c 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -1,5 +1,3 @@ -{!../../../docs/missing-translation.md!} -

FastAPI

@@ -45,43 +43,43 @@ FastAPI は、モダンで、速い(高いパフォーマンスな)、標準の \* 社内開発チームでのテストに基づき見積もってから、本番アプリケーションの構築します。 -## Opinions +## 評価 -"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" +"_[...] 最近 **FastAPI** を使っています。 [...] 実際に私のチームの全ての **Microsoftの機械学習サービス** で使用する予定です。 そのうちのいくつかのコアな**Windows**製品と**Office**製品に統合されつつあります。_" -
Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (参照)
--- -"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" +"_FastAPIライブラリを採用して**REST**サーバを構築し、それをクエリして**予測**を取得しています。 [for Ludwig]_" -
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (参照)
--- -"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" +"_**Netflix** Netflixは、**危機管理**オーケストレーションフレームワーク、**Dispatch**のオープンソースリリースを発表できることをうれしく思います。 [built with **FastAPI**]_" -
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (参照)
--- -"_I’m over the moon excited about **FastAPI**. It’s so fun!_" +"_私は**FastAPI**にワクワクしています。 めちゃくちゃ楽しいです!_" -
Brian Okken - Python Bytes podcast host (ref)
+
Brian Okken - Python Bytes podcast host (参照)
--- -"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" +"_正直、超堅実で洗練されているように見えます。いろんな意味で、それは私がハグしたかったものです。_" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (参照)
--- -"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" +"_REST APIを構築するための**モダンなフレームワーク**を学びたい方は、**FastAPI**をチェックしてみてください。 [...] 高速で, 使用、習得が簡単です。[...]_" -"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" +"_私たちの**API**は**FastAPI**に切り替えました。[...] きっと気に入ると思います。 [...]_" -
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (参照) - (参照)
--- From e983659ec0f9252e5e94fe1e5e96712ef85f8b26 Mon Sep 17 00:00:00 2001 From: "ryusuke.miyaji" Date: Sun, 14 Jun 2020 13:53:59 +0900 Subject: [PATCH 03/17] translate by document upgrade --- docs/ja/docs/index.md | 72 +++++++++++++++++++++---------------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 9bc79f005843c..7e1dff1bfbecd 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -45,41 +45,41 @@ FastAPI は、モダンで、速い(高いパフォーマンスな)、標準の ## 評価 -"_[...] 最近 **FastAPI** を使っています。 [...] 実際に私のチームの全ての **Microsoftの機械学習サービス** で使用する予定です。 そのうちのいくつかのコアな**Windows**製品と**Office**製品に統合されつつあります。_" +"_[...] 最近 **FastAPI** を使っています。 [...] 実際に私のチームの全ての **Microsoft の機械学習サービス** で使用する予定です。 そのうちのいくつかのコアな**Windows**製品と**Office**製品に統合されつつあります。_" -
Kabir Khan - Microsoft (参照)
+
Kabir Khan - Microsoft (ref)
--- -"_FastAPIライブラリを採用して**REST**サーバを構築し、それをクエリして**予測**を取得しています。 [for Ludwig]_" +"_FastAPI ライブラリを採用して**REST**サーバを構築し、それをクエリして**予測**を取得しています。 [for Ludwig]_" -
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (参照)
+
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
--- -"_**Netflix** Netflixは、**危機管理**オーケストレーションフレームワーク、**Dispatch**のオープンソースリリースを発表できることをうれしく思います。 [built with **FastAPI**]_" +"_**Netflix** Netflix は、**危機管理**オーケストレーションフレームワーク、**Dispatch**のオープンソースリリースを発表できることをうれしく思います。 [built with **FastAPI**]_" -
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (参照)
+
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
--- "_私は**FastAPI**にワクワクしています。 めちゃくちゃ楽しいです!_" -
Brian Okken - Python Bytes podcast host (参照)
+
Brian Okken - Python Bytes podcast host (ref)
--- "_正直、超堅実で洗練されているように見えます。いろんな意味で、それは私がハグしたかったものです。_" -
Timothy Crosley - Hug creator (参照)
+
Timothy Crosley - Hug creator (ref)
--- -"_REST APIを構築するための**モダンなフレームワーク**を学びたい方は、**FastAPI**をチェックしてみてください。 [...] 高速で, 使用、習得が簡単です。[...]_" +"_REST API を構築するための**モダンなフレームワーク**を学びたい方は、\*\*FastAPI**をチェックしてみてください。 [...] 高速で, 使用、習得が簡単です。[...]_" "_私たちの**API**は**FastAPI**に切り替えました。[...] きっと気に入ると思います。 [...]_" -
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (参照) - (参照)
+
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
--- @@ -87,20 +87,20 @@ FastAPI は、モダンで、速い(高いパフォーマンスな)、標準の -If you are building a CLI app to be used in the terminal instead of a web API, check out **Typer**. +もし Web API の代わりにターミナルで使用するCLIアプリを構築する場合は、**Typer**を確認してください。 -**Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀 +**Typer**は FastAPI の兄弟です。そして、**CLI の FastAPI**を意図しています。 -## Requirements +## 必要条件 Python 3.6+ -FastAPI stands on the shoulders of giants: +FastAPI は巨人の肩の上に立っています。 -- Starlette for the web parts. -- Pydantic for the data parts. +- Web の部分のためのStarlette +- データの部分のためのPydantic -## Installation +## インストール
@@ -112,7 +112,7 @@ $ pip install fastapi
-You will also need an ASGI server, for production such as Uvicorn or Hypercorn. +Uvicorn または、 Hypercornのように、本番環境では ASGI サーバーが必要になります。
@@ -124,11 +124,11 @@ $ pip install uvicorn
-## Example +## アプリケーション例 -### Create it +### アプリケーションの作成 -- Create a file `main.py` with: +- `main.py` を作成し、以下のコードを入力します: ```Python from fastapi import FastAPI @@ -147,9 +147,9 @@ def read_item(item_id: int, q: str = None): ```
-Or use async def... +またはasync defを使います... -If your code uses `async` / `await`, use `async def`: +`async` / `await`を使用するときは、 `async def`を使います: ```Python hl_lines="7 12" from fastapi import FastAPI @@ -167,15 +167,15 @@ async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q} ``` -**Note**: +**注**: -If you don't know, check the _"In a hurry?"_ section about `async` and `await` in the docs. +ドキュメントの`async` と `await`についてわからない場合は、"In a hurry?"セクションをチェックしてください。
-### Run it +### 実行 -Run the server with: +以下のコマンドでサーバーを起動します:
@@ -192,27 +192,27 @@ INFO: Application startup complete.
-About the command uvicorn main:app --reload... +uvicorn main:app --reloadコマンドについて -The command `uvicorn main:app` refers to: +`uvicorn main:app`コマンドは以下の項目を参照します: -- `main`: the file `main.py` (the Python "module"). -- `app`: the object created inside of `main.py` with the line `app = FastAPI()`. -- `--reload`: make the server restart after code changes. Only do this for development. +- `main`: `main.py`ファイル (Python "モジュール") +- `app`: `main.py` の`app = FastAPI()`の行で生成されたオブジェクト +- `--reload`: コードを変更したらサーバーを再起動します。このオプションは開発環境でのみ使用します
-### Check it +### 動作確認 -Open your browser at http://127.0.0.1:8000/items/5?q=somequery. +ブラウザからhttp://127.0.0.1:8000/items/5?q=somequeryを開きます。 -You will see the JSON response as: +以下の JSON のレスポンスが確認できます: ```JSON {"item_id": 5, "q": "somequery"} ``` -You already created an API that: +もうすでに以下の API が作成されています: - Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`. - Both _paths_ take `GET` operations (also known as HTTP _methods_). From ac92c7ef8beb373c112d3e92bdbea4c23c5fcd2a Mon Sep 17 00:00:00 2001 From: "ryusuke.miyaji" Date: Sun, 14 Jun 2020 15:18:40 +0900 Subject: [PATCH 04/17] translate to end --- docs/ja/docs/index.md | 192 +++++++++++++++++++++--------------------- 1 file changed, 96 insertions(+), 96 deletions(-) diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 7e1dff1bfbecd..f1f33e95296b7 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -214,32 +214,32 @@ INFO: Application startup complete. もうすでに以下の API が作成されています: -- Receives HTTP requests in the _paths_ `/` and `/items/{item_id}`. -- Both _paths_ take `GET` operations (also known as HTTP _methods_). -- The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`. -- The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`. +- `/` と `/items/{item_id}`のパスで HTTP リクエストを受けます。 +- どちらのパスも `GET` 演算子 を取ります。(HTTP メソッドとしても知られています。) +- `/items/{item_id}` パスのパスパラメータ `item_id` は `int` でなければなりません。 +- パス `/items/{item_id}` はオプションの `str` クエリパラメータ `q` を持ちます。 -### Interactive API docs +### 自動対話型の API ドキュメント -Now go to http://127.0.0.1:8000/docs. +http://127.0.0.1:8000/docsにアクセスしてみてください。 -You will see the automatic interactive API documentation (provided by Swagger UI): +自動対話型の API ドキュメントが表示されます。 (Swagger UIが提供しています。): ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) -### Alternative API docs +### 代替の API ドキュメント -And now, go to http://127.0.0.1:8000/redoc. +http://127.0.0.1:8000/redocにアクセスしてみてください。 -You will see the alternative automatic documentation (provided by ReDoc): +代替の自動ドキュメントが表示されます。(ReDocが提供しています。): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) -## Example upgrade +## アップグレード例 -Now modify the file `main.py` to receive a body from a `PUT` request. +`PUT`リクエストからボディを受け取るために`main.py`を修正しましょう。 -Declare the body using standard Python types, thanks to Pydantic. +Pydantic によって、Python の標準的な型を使ってボディを宣言します。 ```Python hl_lines="2 7 8 9 10 23 24 25" from fastapi import FastAPI @@ -269,137 +269,137 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -The server should reload automatically (because you added `--reload` to the `uvicorn` command above). +サーバーは自動でリロードされます。(上述の`uvicorn`コマンドで`--reload`オプションを追加しているからです。) -### Interactive API docs upgrade +### 自動対話型の API ドキュメントのアップグレード -Now go to http://127.0.0.1:8000/docs. +http://127.0.0.1:8000/docsにアクセスしましょう。 -- The interactive API documentation will be automatically updated, including the new body: +- 自動対話型の API ドキュメントが新しいボディも含めて自動でアップデートされます: ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) -- Click on the button "Try it out", it allows you to fill the parameters and directly interact with the API: +- "Try it out"ボタンをクリックしてください。パラメータを入力して API と直接やりとりすることができます: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) -- Then click on the "Execute" button, the user interface will communicate with your API, send the parameters, get the results and show them on the screen: +- それから、"Execute" ボタンをクリックしてください。 ユーザーインターフェースは API と通信し、パラメータを送信し、結果を取得して画面に表示します: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) -### Alternative API docs upgrade +### 代替の API ドキュメントのアップグレード -And now, go to http://127.0.0.1:8000/redoc. +http://127.0.0.1:8000/redocにアクセスしましょう。 -- The alternative documentation will also reflect the new query parameter and body: +- 代替の API ドキュメントに新しいクエリパラメータやボディが反映されます。 ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) -### Recap +### リキャップ -In summary, you declare **once** the types of parameters, body, etc. as function parameters. +要約すると、関数のパラメータ、body などの種類を**一度だけ**宣言します。 -You do that with standard modern Python types. +標準的な最新の Python の型を使っています。 -You don't have to learn a new syntax, the methods or classes of a specific library, etc. +新しい構文や特定のライブラリのメソッドやクラスなどを覚える必要はありません。 -Just standard **Python 3.6+**. +単なる標準的な**3.6 以降の Python**です -For example, for an `int`: +例えば、`int`の場合: ```Python item_id: int ``` -or for a more complex `Item` model: +または、より複雑な`Item`モデルの場合: ```Python item: Item ``` -...and with that single declaration you get: +...そして、その単一の宣言で、以下のようになります: -- Editor support, including: - - Completion. - - Type checks. -- Validation of data: - - Automatic and clear errors when the data is invalid. - - Validation even for deeply nested JSON objects. -- Conversion of input data: coming from the network to Python data and types. Reading from: +- 以下を含むエディタサポート: + - 補完 + - タイプチェック +- データの検証: + - データが無効な場合に自動でエラーをクリアします。 + - 深い入れ子になった JSON オブジェクトでも検証が可能です。 +- 入力データの変換: ネットワークから Python のデータや型に変換してから読み取ります: - JSON. - - Path parameters. - - Query parameters. - - Cookies. - - Headers. - - Forms. - - Files. -- Conversion of output data: converting from Python data and types to network data (as JSON): + - パスパラメータ + - クエリパラメータ + - クッキー + - ヘッダー + - フォーム + - ファイル +- 出力データの変換: Python のデータや型からネットワークデータへ変換します (JSON として): - Convert Python types (`str`, `int`, `float`, `bool`, `list`, etc). - - `datetime` objects. - - `UUID` objects. - - Database models. - - ...and many more. -- Automatic interactive API documentation, including 2 alternative user interfaces: + - `datetime` オブジェクト + - `UUID` オブジェクト + - データベースモデル + - ...などなど +- 2 つの代替ユーザーインターフェースを含む自動インタラクティブ API ドキュメント: - Swagger UI. - ReDoc. --- -Coming back to the previous code example, **FastAPI** will: - -- Validate that there is an `item_id` in the path for `GET` and `PUT` requests. -- Validate that the `item_id` is of type `int` for `GET` and `PUT` requests. - - If it is not, the client will see a useful, clear error. -- Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. - - As the `q` parameter is declared with `= None`, it is optional. - - Without the `None` it would be required (as is the body in the case with `PUT`). -- For `PUT` requests to `/items/{item_id}`, Read the body as JSON: - - Check that it has a required attribute `name` that should be a `str`. - - Check that it has a required attribute `price` that has to be a `float`. - - Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. - - All this would also work for deeply nested JSON objects. -- Convert from and to JSON automatically. -- Document everything with OpenAPI, that can be used by: - - Interactive documentation systems. - - Automatic client code generation systems, for many languages. -- Provide 2 interactive documentation web interfaces directly. +コード例に戻りましょう、**FastAPI** は次のようになります: + +- GET`および`PUT`リクエストのパスに`item_id` があることを検証します。 +- item_id`が`GET`および`PUT`リクエストに対して`int` 型であることを検証します。 + - そうでない場合は、クライアントは有用で明確なエラーが表示されます。 +- `GET` リクエストに対してオプションのクエリパラメータ `q` (`http://127.0.0.1:8000/items/foo?q=somequery` のように) が存在するかどうかを調べます。 + - パラメータ `q` は `= None` で宣言されているので、オプションです。 + - `None`がなければ必須になります(`PUT`の場合のボディと同様です)。 +- `PUT` リクエストを `/items/{item_id}` に送信する場合は、本文を JSON として読み込みます: + - 必須の属性 `name` が `str` であることを確認してください。 + - 必須の属性 `price` が `float` でなければならないことを確認してください。 + - オプションの属性 `is_offer` がある場合は、`bool`であることを確認してください。 + - これらはすべて、深くネストされた JSON オブジェクトに対しても動作します。 +- JSON から JSON に自動的に変換します。 +- 使用できるものは OpenAPI を使用して文書化します: + - 対話的ななドキュメントシステム。 + - 多くの言語に対応した自動クライアントコード生成システム。 +- 2 つの対話的なドキュメント Web インターフェイスを直接提供します。 --- -We just scratched the surface, but you already get the idea of how it all works. +まだ表面的な部分に触れただけですが、もう全ての仕組みは分かっているはずです。 -Try changing the line with: +以下の行を変更してみてください: ```Python return {"item_name": item.name, "item_id": item_id} ``` -...from: +...から: ```Python ... "item_name": item.name ... ``` -...to: +...まで: ```Python ... "item_price": item.price ... ``` -...and see how your editor will auto-complete the attributes and know their types: +...そして、エディタが属性を自動補完し、そのタイプを知る方法をご覧ください。: ![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) -For a more complete example including more features, see the Tutorial - User Guide. +より多くの機能を含む、より完全な例については、チュートリアル - ユーザーガイドをご覧ください。 -**Spoiler alert**: the tutorial - user guide includes: +**Spoiler alert**: チュートリアル - ユーザーガイドは以下の情報が含まれています: - Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**. - How to set **validation constraints** as `maximum_length` or `regex`. - A very powerful and easy to use **Dependency Injection** system. - Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth. - More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic). -- Many extra features (thanks to Starlette) as: +- 以下のようなたくさんのおまけ機能(Starlette のおかげです): - **WebSockets** - **GraphQL** - extremely easy tests based on `requests` and `pytest` @@ -409,35 +409,35 @@ For a more complete example including more features, see the one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (\*) +独立した TechEmpower のベンチマークでは、Uvicorn で動作する**FastAPI**アプリケーションのうち、Starlette と Ubicorn の下でのみ利用可能な Python フレームワークの中で最も高速なものの 1 つであることが示されており、Starlette と Uvicorn 自身の下にのみ(FastAPI で内部的に使用されています)(\*) -To understand more about it, see the section Benchmarks. +詳細はベンチマークセクションをご覧ください。 -## Optional Dependencies +## オプションの依存関係 -Used by Pydantic: +Pydantic によって使用されています: -- ujson - for faster JSON "parsing". -- email_validator - for email validation. +- ujson - より速い JSON への"変換". +- email_validator - E メールの検証 -Used by Starlette: +Starlette によって使用されています: -- requests - Required if you want to use the `TestClient`. -- aiofiles - Required if you want to use `FileResponse` or `StaticFiles`. -- jinja2 - Required if you want to use the default template configuration. -- python-multipart - Required if you want to support form "parsing", with `request.form()`. -- itsdangerous - Required for `SessionMiddleware` support. -- pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI). -- graphene - Required for `GraphQLApp` support. -- ujson - Required if you want to use `UJSONResponse`. +- requests - `TestClient`を使用するために必要です。 +- aiofiles - `FileResponse` または `StaticFiles`を使用したい場合は必要です。 +- jinja2 - デフォルトのテンプレート設定を使用する場合は必要です。 +- python-multipart - "parsing"`request.form()`からの変換をサポートしたい場合は必要です。 +- itsdangerous - `SessionMiddleware` サポートのためには必要です。 +- pyyaml - Starlette の `SchemaGenerator` サポートのために必要です。 (FastAPI では必要ないでしょう。) +- graphene - `GraphQLApp` サポートのためには必要です。 +- ujson - `UJSONResponse`を使用する場合は必須です。 -Used by FastAPI / Starlette: +FastAPI / Starlette によって使用されています: -- uvicorn - for the server that loads and serves your application. -- orjson - Required if you want to use `ORJSONResponse`. +- uvicorn - アプリケーションをロードしてサービスを提供するサーバーを指定します。 +- orjson - `ORJSONResponse`を使用したい場合は必要です。 -You can install all of these with `pip install fastapi[all]`. +これらは全て `pip install fastapi[all]`でインストールできます。 -## License +## ライセンス -This project is licensed under the terms of the MIT license. +このプロジェクトは MIT ライセンスです。 From d9f234c7f517815e0f36bbbf22a76c4ff2a1d5ca Mon Sep 17 00:00:00 2001 From: ryuckel <36391432+ryuckel@users.noreply.github.com> Date: Sun, 14 Jun 2020 15:25:22 +0900 Subject: [PATCH 05/17] fix text --- docs/ja/docs/index.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index f1f33e95296b7..2b274cc01770e 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -75,7 +75,7 @@ FastAPI は、モダンで、速い(高いパフォーマンスな)、標準の --- -"_REST API を構築するための**モダンなフレームワーク**を学びたい方は、\*\*FastAPI**をチェックしてみてください。 [...] 高速で, 使用、習得が簡単です。[...]_" +"_REST API を構築するための**モダンなフレームワーク**を学びたい方は、**FastAPI** [...] をチェックしてみてください。 [...] 高速で, 使用、習得が簡単です。[...]_" "_私たちの**API**は**FastAPI**に切り替えました。[...] きっと気に入ると思います。 [...]_" @@ -347,8 +347,8 @@ item: Item コード例に戻りましょう、**FastAPI** は次のようになります: -- GET`および`PUT`リクエストのパスに`item_id` があることを検証します。 -- item_id`が`GET`および`PUT`リクエストに対して`int` 型であることを検証します。 +- `GET`および`PUT`リクエストのパスに`item_id` があることを検証します。 +- `item_id`が`GET`および`PUT`リクエストに対して`int` 型であることを検証します。 - そうでない場合は、クライアントは有用で明確なエラーが表示されます。 - `GET` リクエストに対してオプションのクエリパラメータ `q` (`http://127.0.0.1:8000/items/foo?q=somequery` のように) が存在するかどうかを調べます。 - パラメータ `q` は `= None` で宣言されているので、オプションです。 @@ -407,7 +407,7 @@ item: Item - **Cookie Sessions** - ...and more. -## Performance +## パフォーマンス 独立した TechEmpower のベンチマークでは、Uvicorn で動作する**FastAPI**アプリケーションのうち、Starlette と Ubicorn の下でのみ利用可能な Python フレームワークの中で最も高速なものの 1 つであることが示されており、Starlette と Uvicorn 自身の下にのみ(FastAPI で内部的に使用されています)(\*) From babbd2f571217ed688e3a84e28cc8a02aa396a66 Mon Sep 17 00:00:00 2001 From: ryuckel <36391432+ryuckel@users.noreply.github.com> Date: Sun, 14 Jun 2020 15:42:13 +0900 Subject: [PATCH 06/17] translate spoiler alert --- docs/ja/docs/index.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 2b274cc01770e..0aafc1c518485 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -392,20 +392,20 @@ item: Item より多くの機能を含む、より完全な例については、チュートリアル - ユーザーガイドをご覧ください。 -**Spoiler alert**: チュートリアル - ユーザーガイドは以下の情報が含まれています: +**ネタバレ注意**: チュートリアル - ユーザーガイドは以下の情報が含まれています: -- Declaration of **parameters** from other different places as: **headers**, **cookies**, **form fields** and **files**. -- How to set **validation constraints** as `maximum_length` or `regex`. -- A very powerful and easy to use **Dependency Injection** system. -- Security and authentication, including support for **OAuth2** with **JWT tokens** and **HTTP Basic** auth. -- More advanced (but equally easy) techniques for declaring **deeply nested JSON models** (thanks to Pydantic). +- **ヘッダー**、**クッキー**、**フォームフィールド**、**ファイル**などの他の場所からの **パラメータ** 宣言。 +- `maximum_length`や`regex`のような**検証や制約**を設定する方法。 +- 非常に強力で使いやすい依存性 **インジェクション**システム。 +- **JWT トークン**と **HTTP Basic認証** による **OAuth2** のサポートを含む、セキュリティと認証。 +- **深くネストされたJSONモデル**を宣言するためのより高度な(しかし同様に簡単な)技術(Pydanticのおかげです)。 - 以下のようなたくさんのおまけ機能(Starlette のおかげです): - **WebSockets** - **GraphQL** - - extremely easy tests based on `requests` and `pytest` + - `requests` や `pytest`をもとにした極限に簡単なテスト - **CORS** - - **Cookie Sessions** - - ...and more. + - **クッキーセッション** + - ...などなど。 ## パフォーマンス From d2936524c596146c4cdf3edb331d06a4991ea8fc Mon Sep 17 00:00:00 2001 From: "ryusuke.miyaji" Date: Thu, 25 Jun 2020 09:20:24 +0900 Subject: [PATCH 07/17] fix translations and typo --- docs/ja/docs/index.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 0aafc1c518485..d06e405e39e86 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -27,7 +27,7 @@ --- -FastAPI は、モダンで、速い(高いパフォーマンスな)、標準の Python 型ヒントに基づいて、Python 3.6 以降のバージョンで API をビルドするための Web フレームワークです。 +FastAPI は、Python 3.6 以降で標準である型ヒントに基づいて API を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 主な特徴: @@ -41,7 +41,7 @@ FastAPI は、モダンで、速い(高いパフォーマンスな)、標準の - **堅牢性**: 自動対話ドキュメントを使用して、本番環境で使用できるコードを取得します。 - **Standards-based**: API のオープンスタンダードに基づいており、完全に互換性があります: OpenAPI (以前は Swagger として知られていました) や JSON スキーマ. -\* 社内開発チームでのテストに基づき見積もってから、本番アプリケーションの構築します。 +\* 本番アプリケーションを構築している開発チームのテストによる見積もり。 ## 評価 @@ -57,7 +57,7 @@ FastAPI は、モダンで、速い(高いパフォーマンスな)、標準の --- -"_**Netflix** Netflix は、**危機管理**オーケストレーションフレームワーク、**Dispatch**のオープンソースリリースを発表できることをうれしく思います。 [built with **FastAPI**]_" +"_**Netflix** は、**危機管理**オーケストレーションフレームワーク、**Dispatch**のオープンソースリリースを発表できることをうれしく思います。 [built with **FastAPI**]_"
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
@@ -89,7 +89,7 @@ FastAPI は、モダンで、速い(高いパフォーマンスな)、標準の もし Web API の代わりにターミナルで使用するCLIアプリを構築する場合は、**Typer**を確認してください。 -**Typer**は FastAPI の兄弟です。そして、**CLI の FastAPI**を意図しています。 +**Typer**は FastAPI の兄弟です。そして、**CLI 版 の FastAPI**を意図しています。 ## 必要条件 @@ -303,7 +303,7 @@ def update_item(item_id: int, item: Item): 新しい構文や特定のライブラリのメソッドやクラスなどを覚える必要はありません。 -単なる標準的な**3.6 以降の Python**です +単なる標準的な**3.6 以降の Python**です。 例えば、`int`の場合: @@ -397,8 +397,8 @@ item: Item - **ヘッダー**、**クッキー**、**フォームフィールド**、**ファイル**などの他の場所からの **パラメータ** 宣言。 - `maximum_length`や`regex`のような**検証や制約**を設定する方法。 - 非常に強力で使いやすい依存性 **インジェクション**システム。 -- **JWT トークン**と **HTTP Basic認証** による **OAuth2** のサポートを含む、セキュリティと認証。 -- **深くネストされたJSONモデル**を宣言するためのより高度な(しかし同様に簡単な)技術(Pydanticのおかげです)。 +- **JWT トークン**と **HTTP Basic 認証** による **OAuth2** のサポートを含む、セキュリティと認証。 +- **深くネストされた JSON モデル**を宣言するためのより高度な(しかし同様に簡単な)技術(Pydantic のおかげです)。 - 以下のようなたくさんのおまけ機能(Starlette のおかげです): - **WebSockets** - **GraphQL** @@ -409,18 +409,18 @@ item: Item ## パフォーマンス -独立した TechEmpower のベンチマークでは、Uvicorn で動作する**FastAPI**アプリケーションのうち、Starlette と Ubicorn の下でのみ利用可能な Python フレームワークの中で最も高速なものの 1 つであることが示されており、Starlette と Uvicorn 自身の下にのみ(FastAPI で内部的に使用されています)(\*) +独立した TechEmpower のベンチマークでは、Uvicorn で動作する**FastAPI**アプリケーションが、Python フレームワークの中で最も高速なものの 1 つであることが示されてます、Starlette と Uvicorn(FastAPI で内部的に使用されています)のみ下回っています。(\*) 詳細はベンチマークセクションをご覧ください。 ## オプションの依存関係 -Pydantic によって使用されています: +Pydantic によって使用されるもの: - ujson - より速い JSON への"変換". - email_validator - E メールの検証 -Starlette によって使用されています: +Starlette によって使用されるもの: - requests - `TestClient`を使用するために必要です。 - aiofiles - `FileResponse` または `StaticFiles`を使用したい場合は必要です。 @@ -431,7 +431,7 @@ Starlette によって使用されています: - graphene - `GraphQLApp` サポートのためには必要です。 - ujson - `UJSONResponse`を使用する場合は必須です。 -FastAPI / Starlette によって使用されています: +FastAPI / Starlette に使用されるもの: - uvicorn - アプリケーションをロードしてサービスを提供するサーバーを指定します。 - orjson - `ORJSONResponse`を使用したい場合は必要です。 From 75d6ccbe61b10f22c0deeb566d28f84d122da705 Mon Sep 17 00:00:00 2001 From: "ryusuke.miyaji" Date: Thu, 25 Jun 2020 09:38:15 +0900 Subject: [PATCH 08/17] fix translations --- docs/ja/docs/index.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index d06e405e39e86..2d208a2e30c43 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -317,7 +317,7 @@ item_id: int item: Item ``` -...そして、その単一の宣言で、以下のようになります: +...そして、この一度の宣言で、以下のようになります: - 以下を含むエディタサポート: - 補完 @@ -354,13 +354,13 @@ item: Item - パラメータ `q` は `= None` で宣言されているので、オプションです。 - `None`がなければ必須になります(`PUT`の場合のボディと同様です)。 - `PUT` リクエストを `/items/{item_id}` に送信する場合は、本文を JSON として読み込みます: - - 必須の属性 `name` が `str` であることを確認してください。 - - 必須の属性 `price` が `float` でなければならないことを確認してください。 - - オプションの属性 `is_offer` がある場合は、`bool`であることを確認してください。 + - 必須の属性 `name` を確認してください。 それは `str` であるべきです。 + - 必須の属性 `price` を確認してください。それは `float` でなければならないです。 + - オプションの属性 `is_offer` を確認してください。値がある場合は、`bool` であるべきです。 - これらはすべて、深くネストされた JSON オブジェクトに対しても動作します。 - JSON から JSON に自動的に変換します。 - 使用できるものは OpenAPI を使用して文書化します: - - 対話的ななドキュメントシステム。 + - 対話的なドキュメントシステム。 - 多くの言語に対応した自動クライアントコード生成システム。 - 2 つの対話的なドキュメント Web インターフェイスを直接提供します。 @@ -386,7 +386,7 @@ item: Item ... "item_price": item.price ... ``` -...そして、エディタが属性を自動補完し、そのタイプを知る方法をご覧ください。: +...そして、エディタが属性を自動補完し、そのタイプを知る方法を確認してください。: ![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) @@ -433,7 +433,7 @@ Starlette によって使用されるもの: FastAPI / Starlette に使用されるもの: -- uvicorn - アプリケーションをロードしてサービスを提供するサーバーを指定します。 +- uvicorn - アプリケーションをロードしてサーブするサーバーのため。 - orjson - `ORJSONResponse`を使用したい場合は必要です。 これらは全て `pip install fastapi[all]`でインストールできます。 From 2289211b391b9e94fe59441ae3f26e8bf4bf0fd9 Mon Sep 17 00:00:00 2001 From: tokusumi Date: Tue, 30 Jun 2020 22:58:44 +0900 Subject: [PATCH 09/17] Add Japanese translation for tutorial/index.md --- docs/ja/docs/tutorial/index.md | 80 ++++++++++++++++++++++++++++++++++ docs/ja/mkdocs.yml | 2 + 2 files changed, 82 insertions(+) create mode 100644 docs/ja/docs/tutorial/index.md diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md new file mode 100644 index 0000000000000..a8cc814a19d0c --- /dev/null +++ b/docs/ja/docs/tutorial/index.md @@ -0,0 +1,80 @@ +# チュートリアル - ユーザーガイド - はじめに + +このチュートリアルは**FastAPI**のほぼすべての機能の使い方を段階的に紹介します。 + +各セクションは前のセクションを踏まえた内容になっています。しかし、トピックごとに分割されているので、特定のAPIの要求を満たすようなセクションに直接たどり着けるようになっています。 + +また、将来的にリファレンスとして機能するように構築されています。 + +従って、後でこのチュートリアルに戻ってきて必要なものを確認できます。 + +## コードを実行する + +すべてのコードブロックをコピーして直接使用できます(実際にテストされたPythonファイルです)。 + +いずれかの例を実行するには、コードを `main.py`ファイルにコピーし、` uvicorn`を次のように起動します: + +
+ +```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. +``` + +
+ +コードを記述またはコピーし、編集してローカルで実行することを**強くお勧めします**。 + +また、エディターで使用することで、FastAPIの利点が実際に示されます。作成する必要があるコードの量、すべての型チェック、自動補完などを確認できます。 + +--- + +## FastAPIをインストールする + +最初のステップは、FastAPIのインストールです。 + +チュートリアルのために、すべてのオプションの依存関係と機能をインストールしたいとき: + +
+ +```console +$ pip install fastapi[all] + +---> 100% +``` + +
+ +...これには、コードを実行するサーバーとして使用できる `uvicorn`も含まれます。 + +!!! 注意 + パーツ毎にインストールすることも可能です。 + + This is what you would probably do once you want to deploy your application to production: + + ``` + pip install fastapi + ``` + + Also install `uvicorn` to work as the server: + + ``` + pip install uvicorn + ``` + + And the same for each of the optional dependencies that you want to use. + +## 高度なユーザーガイド + +**高度なユーザーガイド**もあり、**チュートリアル - ユーザーガイド**の後で読むことができます。 + +**高度なユーザーガイド**は**チュートリアル - ユーザーガイド**に基づいており、同じ概念を使用し、いくつかの追加機能を紹介しています。 + +ただし、最初に**チュートリアル - ユーザーガイド**(現在読んでいる内容)をお読みください。 + +完全なアプリケーションを**チュートリアル-ユーザーガイド**だけで構築し、**高度なユーザーガイド**のアイデアを使用して、ニーズに応じたさまざまな拡張を行えるように設計されています 。 diff --git a/docs/ja/mkdocs.yml b/docs/ja/mkdocs.yml index 8f55ea67cb2f7..a960db320c231 100644 --- a/docs/ja/mkdocs.yml +++ b/docs/ja/mkdocs.yml @@ -25,6 +25,8 @@ nav: - ja: /ja/ - pt: /pt/ - zh: /zh/ +- チュートリアル - ユーザーガイド: + - tutorial/index.md markdown_extensions: - toc: permalink: true From cedd872aa883cd3c1fff1eeeba4230d0585d4eca Mon Sep 17 00:00:00 2001 From: "T. Tokusumi" <41147016+tokusumi@users.noreply.github.com> Date: Sat, 15 Aug 2020 20:48:47 +0900 Subject: [PATCH 10/17] Fix tip word --- docs/ja/docs/tutorial/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md index a8cc814a19d0c..cc3462f578a8f 100644 --- a/docs/ja/docs/tutorial/index.md +++ b/docs/ja/docs/tutorial/index.md @@ -52,7 +52,7 @@ $ pip install fastapi[all] ...これには、コードを実行するサーバーとして使用できる `uvicorn`も含まれます。 -!!! 注意 +!!! note "注意" パーツ毎にインストールすることも可能です。 This is what you would probably do once you want to deploy your application to production: From f5154a5a49f693593e93d00b5381773cce89447f Mon Sep 17 00:00:00 2001 From: "T. Tokusumi" <41147016+tokusumi@users.noreply.github.com> Date: Sun, 16 Aug 2020 01:33:19 +0900 Subject: [PATCH 11/17] Improve translation --- docs/ja/docs/tutorial/index.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md index cc3462f578a8f..e77e9deacdf0c 100644 --- a/docs/ja/docs/tutorial/index.md +++ b/docs/ja/docs/tutorial/index.md @@ -2,7 +2,7 @@ このチュートリアルは**FastAPI**のほぼすべての機能の使い方を段階的に紹介します。 -各セクションは前のセクションを踏まえた内容になっています。しかし、トピックごとに分割されているので、特定のAPIの要求を満たすようなセクションに直接たどり着けるようになっています。 +各セクションは前のセクションを踏まえた内容になっています。しかし、トピックごとに分割されているので、特定のAPIの要求を満たすようなトピックに直接たどり着けるようになっています。 また、将来的にリファレンスとして機能するように構築されています。 @@ -30,7 +30,7 @@ $ uvicorn main:app --reload コードを記述またはコピーし、編集してローカルで実行することを**強くお勧めします**。 -また、エディターで使用することで、FastAPIの利点が実際に示されます。作成する必要があるコードの量、すべての型チェック、自動補完などを確認できます。 +また、エディターで使用することで、書く必要のあるコードの少なさ、すべての型チェック、自動補完などのFastAPIの利点を実感できます。 --- @@ -52,22 +52,23 @@ $ pip install fastapi[all] ...これには、コードを実行するサーバーとして使用できる `uvicorn`も含まれます。 -!!! note "注意" +!!! note "備考" パーツ毎にインストールすることも可能です。 - This is what you would probably do once you want to deploy your application to production: + 以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです: ``` pip install fastapi ``` + また、サーバーとして動作するように`uvicorn` をインストールします: Also install `uvicorn` to work as the server: ``` pip install uvicorn ``` - And the same for each of the optional dependencies that you want to use. + そして、使用したい依存関係をそれぞれ同様にインストールします。 ## 高度なユーザーガイド @@ -77,4 +78,4 @@ $ pip install fastapi[all] ただし、最初に**チュートリアル - ユーザーガイド**(現在読んでいる内容)をお読みください。 -完全なアプリケーションを**チュートリアル-ユーザーガイド**だけで構築し、**高度なユーザーガイド**のアイデアを使用して、ニーズに応じたさまざまな拡張を行えるように設計されています 。 +**チュートリアル-ユーザーガイド**だけで完全なアプリケーションを構築できるように設計されています。加えて、**高度なユーザーガイド**の中からニーズに応じたアイデアを使用して、様々な拡張が可能です。 From c990f9cad2d07c619c213cf23bbe5f982f0b5114 Mon Sep 17 00:00:00 2001 From: "T. Tokusumi" <41147016+tokusumi@users.noreply.github.com> Date: Sat, 22 Aug 2020 12:44:36 +0900 Subject: [PATCH 12/17] delete a line to forget to erase --- docs/ja/docs/tutorial/index.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md index e77e9deacdf0c..c78f7795448db 100644 --- a/docs/ja/docs/tutorial/index.md +++ b/docs/ja/docs/tutorial/index.md @@ -62,7 +62,6 @@ $ pip install fastapi[all] ``` また、サーバーとして動作するように`uvicorn` をインストールします: - Also install `uvicorn` to work as the server: ``` pip install uvicorn From 74426d6f5a80528ca213db8b68a3242003758fef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=AD=E6=9D=91=E5=92=8C=E8=B2=B4?= Date: Sun, 23 Aug 2020 21:44:33 +0900 Subject: [PATCH 13/17] add tutorial/dependencies.md --- docs/ja/docs/tutorial/dependencies/index.md | 209 ++++++++++++++++++++ docs/ja/mkdocs.yml | 2 + 2 files changed, 211 insertions(+) create mode 100644 docs/ja/docs/tutorial/dependencies/index.md diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md new file mode 100644 index 0000000000000..ec563a16d7219 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -0,0 +1,209 @@ +# 依存関係 - 最初のステップ + +** FastAPI** は非常に強力でありながら直感的な **依存性注入** システムを持っています。 + +それは非常にシンプルに使用できるように設計されており、開発者が他のコンポーネント **FastAPI** と統合するのが非常に簡単になるように設計されています。 + +## 「依存性注入」とは + +**「依存性注入」** とは、プログラミングにおいて、コード(この場合は、*path operation関数*)が動作したり使用したりするために必要なもの(「依存関係」)を宣言する方法があることを意味します: + +そして、そのシステム(この場合は、**FastAPI**)は、必要な依存関係をコードに提供するために必要なことは何でも行います(依存関係を「注入」します)。 + +これは以下のようなことが必要な時にとても便利です: + +* ロジックを共有している。(同じコードロジックを何度も繰り返している)。 +* データベース接続を共有する。 +* セキュリティ、認証、ロール要件などを強制する。 +* そのほかにも多くのこと... + +これらすべてを、コードの繰り返しを最小限に抑えながら行います。 + +## 最初のステップ + +非常にシンプルな例を見てみましょう。あまりにもシンプルなので、今のところはあまり参考にならないでしょう。 + +しかし、この方法では **依存性注入** システムがどのように機能するかに焦点を当てることができます。 + +### 依存関係の作成 + +まずは依存関係に注目してみましょう。 + +以下のように、*path operation関数*と同じパラメータを全て取ることができる関数にすぎません: + +```Python hl_lines="8 9" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +これだけです。 + +**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スキーマに統合されます。 + +つまり、対話型ドキュメントにはこれらの依存関係から得られる全ての情報も含まれているということです: + + + +## 簡単な使い方 + +見てみると、*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スキーマに追加して、対話型のドキュメントシステムに表示されるようにします。 diff --git a/docs/ja/mkdocs.yml b/docs/ja/mkdocs.yml index a960db320c231..e3010f39bc65f 100644 --- a/docs/ja/mkdocs.yml +++ b/docs/ja/mkdocs.yml @@ -27,6 +27,8 @@ nav: - zh: /zh/ - チュートリアル - ユーザーガイド: - tutorial/index.md + - 依存関係: + - tutorial/dependencies/index.md markdown_extensions: - toc: permalink: true From e03092e12d42772a6b60e4a99a1f2705c8bbcbee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=AD=E6=9D=91=E5=92=8C=E8=B2=B4?= Date: Sun, 23 Aug 2020 21:48:50 +0900 Subject: [PATCH 14/17] fix typo --- docs/ja/docs/tutorial/dependencies/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md index ec563a16d7219..630be9f0997f3 100644 --- a/docs/ja/docs/tutorial/dependencies/index.md +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -1,6 +1,6 @@ # 依存関係 - 最初のステップ -** FastAPI** は非常に強力でありながら直感的な **依存性注入** システムを持っています。 +**FastAPI** は非常に強力でありながら直感的な **依存性注入** システムを持っています。 それは非常にシンプルに使用できるように設計されており、開発者が他のコンポーネント **FastAPI** と統合するのが非常に簡単になるように設計されています。 From 9dc62f2252358575ed572b1d20b35b7ab2ea19cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=AD=E6=9D=91=E5=92=8C=E8=B2=B4?= Date: Mon, 24 Aug 2020 00:41:10 +0900 Subject: [PATCH 15/17] add tutorial/dependencies/dependencies-with-yield.md --- .../dependencies/dependencies-with-yield.md | 225 ++++++++++++++++++ docs/ja/mkdocs.yml | 1 + 2 files changed, 226 insertions(+) create mode 100644 docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 0000000000000..14118dd9d0201 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,225 @@ +# yieldを持つ依存関係 + +FastAPIは、いくつかの終了後の追加のステップを行う依存関係をサポートしています。 + +これを行うには、`return`の代わりに`yield`を使い、その後に追加のステップを書きます。 + +!!! tip "豆知識" + `yield`は必ず一度だけ使用するようにしてください。 + +!!! info "情報" + これを動作させるには、**Python 3.7** 以上を使用するか、**Python 3.6** では"backports"をインストールする必要があります: + + ``` + pip install async-exit-stack async-generator + ``` + + これによりasync-exit-stackasync-generatorがインストールされます。 + +!!! note "技術詳細" + 以下と一緒に使用できる有効な関数なら何でも良いです: + + * `@contextlib.contextmanager`または + * `@contextlib.asynccontextmanager` + + これらは **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のContext Managersのおかげで動作します。 + + **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オブジェクトのことです。 + +例えば、ファイルを読み込むには`with`を使用することができます: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +その後の`open("./somefile.txt")`は「コンテキストマネージャ」と呼ばれるオブジェクトを作成します。 + +`with`ブロックが終了すると、例外があったとしてもファイルを確かに閉じます。 + +`yield`を依存関係を作成すると、**FastAPI** は内部的にそれをコンテキストマネージャに変換し、他の関連ツールと組み合わせます。 + +### `yield`を持つ依存関係でのコンテキストマネージャの使用 + +!!! warning "注意" + これは多かれ少なかれ、「高度な」発想です。 + + **FastAPI** を使い始めたばかりの方は、とりあえずスキップした方がよいかもしれません。 + +Pythonでは、以下の2つのメソッドを持つクラスを作成する: `__enter__()`と`__exit__()`ことでコンテキストマネージャを作成することができます。 + +また、依存関数の中で`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です: + + * `@contextlib.contextmanager` または + * `@contextlib.asynccontextmanager` + + これらを使って、関数を単一の`yield`でデコレートすることができます。 + + これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。 + + しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。 + + FastAPIが内部的にやってくれます。 diff --git a/docs/ja/mkdocs.yml b/docs/ja/mkdocs.yml index e3010f39bc65f..8de27c8c60283 100644 --- a/docs/ja/mkdocs.yml +++ b/docs/ja/mkdocs.yml @@ -29,6 +29,7 @@ nav: - tutorial/index.md - 依存関係: - tutorial/dependencies/index.md + - tutorial/dependencies/dependencies-with-yield.md markdown_extensions: - toc: permalink: true From 3081c0ba6472db9083e9545e4bc8369b7d4d1f9a Mon Sep 17 00:00:00 2001 From: SwftAlpc Date: Fri, 30 Oct 2020 01:09:15 +0900 Subject: [PATCH 16/17] Update docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md Co-authored-by: T. Tokusumi <41147016+tokusumi@users.noreply.github.com> --- docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index 14118dd9d0201..354bfbee415ab 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -17,7 +17,7 @@ FastAPIは、いくつかの