From 381e123aa29fd928632d5668f9d3a707096a74be Mon Sep 17 00:00:00 2001 From: jamesyangget Date: Fri, 20 Mar 2020 23:25:26 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BF=BB=E8=AF=91README?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 361 +++++++++++++++---------------- tutorial/{index.md => README.md} | 0 2 files changed, 169 insertions(+), 192 deletions(-) rename tutorial/{index.md => README.md} (100%) diff --git a/README.md b/README.md index 11c9453..be9b76d 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ FastAPI

- FastAPI framework, high performance, easy to learn, fast to code, ready for production + FastAPI 框架,高性能,易学,快速编码,随时可供生产

@@ -21,46 +21,43 @@ --- -**Documentation**: https://fastapi.tiangolo.com +**文档**:https://fastapi.tiangolo.com -**Source Code**: https://github.com/tiangolo/fastapi +**源码**:https://github.com/tiangolo/fastapi --- -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. +FastAPI 是一个现代、快速(高性能)的 Web 框架,基于标准 Python 类型提示,使用 Python 3.6+ 构建 API。 -The key features are: +主要功能包括: -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). +* **快速**: 与 **NodeJS** 和 **Go** ,相比有相当的高性能(感谢 Starlette 和 Pydantic)。 [现有最快的Python框架之一](#performance)。 -* **Fast to code**: Increase the speed to develop features by about 200% to 300% *. -* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * -* **Intuitive**: Great editor support. Completion everywhere. Less time debugging. -* **Easy**: Designed to be easy to use and learn. Less time reading docs. -* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. -* **Robust**: Get production-ready code. With automatic interactive documentation. -* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema. +* **快速编码**:将功能开发速度提高约200%至300%。 +* **更少的Bug**:减少约40%的人为(开发人员)导致的错误。 +* **直观**:更好的编辑支持。补全任何地方(也称为自动完成,自动完成,IntelliSense)。更少的调试时间。 +* **简单**:方便使用和学习。减少阅读文档的时间。 +* **简洁**:最小化代码重复。每个参数声明的多个要素。更少的错误。 +* **Robust**:获取便于生产的代码。带自动交互式文档。 +* **基于标准**:基于(并完全兼容)API 的开放标准:OpenAPI(以前称为Swagger)和 JSON Schema。 -* estimation based on tests on an internal development team, building production applications. +* 根据内部开发团队的测试进行估算,以构建生产应用程序。 -## 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)
- --- "*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 [...]*" @@ -68,61 +65,51 @@ The key features are: "*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)
- --- "*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)
- --- -## **Typer**, the FastAPI of CLIs +## **Typer**,CLI中的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(Command Line Interface)应用,请查看**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: - -* Starlette for the web parts. -* Pydantic for the data parts. +FastAPI站在巨人的肩膀上: -## Installation +* Starlette 用于Web部分。 +* Pydantic 用于数据部分。 -
+## 安装 -```console +```bash $ pip install fastapi ---> 100% ``` -
- -You will also need an ASGI server, for production such as Uvicorn or Hypercorn. +你还需要一个ASGI服务器来进行生产,例如Uvicorn 或者 Hypercorn。 -
- -```console +```bash $ pip install uvicorn ---> 100% ``` -
- -## Example +## 示例 -### Create it +### 创建 -* Create a file `main.py` with: +* 创建一个`main.py` 文件: ```Python from fastapi import FastAPI @@ -141,99 +128,89 @@ def read_item(item_id: int, q: str = None): ```
-Or use async def... +或者使用async def... +

如果你的代码使用 async / await,请使用 async def

+
from fastapi import FastAPI
 
-If your code uses `async` / `await`, use `async def`:
+app = FastAPI()
 
-```Python hl_lines="7 12"
-from fastapi import FastAPI
 
-app = FastAPI()
+@app.get("/")
+async def read_root():
+    return {"Hello": "World"}
 
 
-@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.
-
+@app.get("/items/{item_id}")
+async def read_item(item_id: int, q: str = None):
+    return {"item_id": item_id, "q": q}
+

注意

+

如果你不知道,请在文档中的 "急吗?" 查看有关 asyncawait的部分。

-### Run it -Run the server with: +### 运行 -
+使用以下命令运行服务: -```console +```bash $ 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. +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. - +
+关于 uvicorn main:app --reload命令... +

uvicorn main:app 命令指:

+
    +
  • mainmain.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_). -* 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. +现在修改文件`main.py`以接收来自`PUT`请求的主体。 -Declare the body using standard Python types, thanks to Pydantic. +使用标准的Python类型声明主体,感谢Pydantic。 ```Python hl_lines="2 7 8 9 10 23 24 25" from fastapi import FastAPI @@ -263,175 +240,175 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -The server should reload automatically (because you added `--reload` to the `uvicorn` command above). +服务应该会自动重新加载(因为你在上面的`uvicorn`命令中添加了`--reload`)。 -### Interactive API docs upgrade +### 交互式API文档升级 -Now go to 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: +* 替代文档也将体现新的查询参数和正文: ![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. +你可以使用标准的现代Python类型来做到这一点。 -You don't have to learn a new syntax, the methods or classes of a specific library, etc. +你不必学习新的语法,特定库的方法或类等。 -Just standard **Python 3.6+**. +只是标准的**Python 3.6 +**。 -For example, for an `int`: +例如,对于一个`int`: ```Python item_id: int ``` -or for a more complex `Item` model: +或更复杂的`Item`模型: ```Python item: Item ``` -...and with that single declaration you get: - -* Editor support, including: - * Completion. - * Type checks. -* Validation of data: - * Automatic and clear errors when the data is invalid. - * Validation even for deeply nested JSON objects. -* 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: +...通过单个声明,你将得到: + +* 编辑器支持,包括: + * 代码补全。 + * 类型检查。 +* 数据验证: + * 数据无效时自动清除错误。 + * 甚至对深度嵌套的JSON对象也进行验证。 +* 输入数据的转换(也称为:序列化,解析,编组):从网络转换为Python数据和类型。 阅读: + * JSON。 + * 路径参数。 + * 查询参数。 + * Cookies。 + * 标头。 + * 表单。 + * 文件。 +* 输入数据的转换(也称为:序列化,解析,编组):从Python数据类型转换为网络数据(如JSON): + * 转换Python类型(`str`,`int`,`float`,`bool`,`list`等)。 + * `datetime`对象。 + * `UUID`对象。 + * 数据库模型。 + * ...还有很多。 +* 自动交互式API文档,包括2个备用用户界面: * 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`类型。 + * 如果不是,客户端将看到一个有用的明确错误。 +* 检查是否有一个名为`q`的可选查询参数(如`http://127.0.0.1:8000/items/foo?q=somequery`中的内容)用于`GET`请求。 + * 由于`q`参数是用`= None`声明的,因此它是可选的。 + * 如果没有`None`,则将是必需的(与`PUT`一样,主体也是如此)。 +* 对于`/items/{item_id}`的`PUT`请求,将正文读取为JSON: + * 检查它是否具有必需的`name`属性,该属性应为`str`。 + * 检查它是否具有必需的`price`属性,该属性必须是`float`。 + * 检查它是否具有可选属性`is_offer`,如果存在则应为`bool`。 + * 所有这些对于深度嵌套的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: +**剧透警报**:教程-用户指南包括: -* 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: +* 从其他不同地方声明**参数**:**标头**,**Cookies**,**表单字段**和**文件**。 +* 如何将**验证约束**设置为`maximum_length`或`regex`。 +* 一个非常强大且易于使用的**依赖注入**(也称为组件,资源,提供者,服务,可注入)系统。 +* 安全性和身份验证,身份验证支持**OAuth2**包括通过**JWT令牌**和**HTTP Basic**。 +* 用于声明**深度嵌套的JSON模型**的更高级(但同样容易)的技术(感谢Pydantic)。 +* 许多额外的功能(感谢Starlette): * **WebSockets** * **GraphQL** - * extremely easy tests based on `requests` and `pytest` + * 基于`requests`和`pytest`的极其简单的测试 * **CORS** - * **Cookie Sessions** - * ...and more. + * **Cookie会话** + * ...和更多。 -## 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). (*) +独立的TechEmpower基准测试显示**FastAPI**应用程序在Uvicorn下运行为最快的Python框架之一,仅在Starlette和Uvicorn(由FastAPI内部使用)之下。 -To understand more about it, see the section Benchmarks. +要了解更多信息,请参阅基准测试。 -## Optional Dependencies +## 可选依赖项 -Used by Pydantic: +使用Pydantic: -* ujson - for faster JSON "parsing". +* ujson - 为了更快的JSON“解析”(将来自HTTP请求的字符串转换为Python数据)。 * email_validator - for email validation. -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 - 如果你想使用`request.form()`支持“解析”(将来自HTTP请求的字符串转换为Python数据),则为必需。 +* 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许可条款获得许可。 \ No newline at end of file diff --git a/tutorial/index.md b/tutorial/README.md similarity index 100% rename from tutorial/index.md rename to tutorial/README.md -- GitLab