fastapi高性能异步python后端框架

教程:https://fastapi.tiangolo.com/zh/tutorial/
API:https://fastapi.tiangolo.com/zh/reference/
文档: https://fastapi.tiangolo.com
Source Code: https://github.com/tiangolo/fastapi
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints.
特性:
- Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.
- 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.
不说废话
依赖
Python 3.8+
安装
| 1 | pip install fastapi | 
开始
main.py
| 1 | # 类型检查,Union允许为多种类型的检查,相当于或 | 
- 使用 - async/- await来将上述代码变为异步
- 测试 : 
 http://127.0.0.1:8000/items/5?q=somequery.- 返回值: - item_id:5 - q:“somequery” 
- 开启服务器,运行main中的app程序,–reload会自动刷新 - 1 
 2
 3- uvicorn main:app --reload 
 # 或者是在最新的版本是这样的:
 fastapi dev main.py
| 序号 | 方法 | 描述 | 
|---|---|---|
| 1 | get | 查看 | 
| 2 | post | 创建 | 
| 3 | put | 更新 | 
| 4 | delete | 删除 | 
新案例

新增PUT和Item,PUT就是最下面的函数,除了方法为put以外没有差异,Item是自建类,用于数据类型检查。
可以在路径传参,声明的参数不是路径参数时,路径操作函数会把该参数自动解释为查询参数。即问号后面的参数,比如“?skip=0&limit=10”会被解析成函数传参skip=0,limit=10
测试和文档
swagger类似,直接在/docs路径 点击try 即可
测试
编写测试文件,然后pytest
调试
uvicorn
状态管理
可能没法啊,只能add_task,没法删除
在FastAPI中,可以使用背景任务(background tasks)来实现状态管理。以下是一个简单的示例,展示了如何使用FastAPI和BackgroundTask实现状态管理:
| 1 | from fastapi import FastAPI, BackgroundTasks | 
关注点分离
bymin
| 1 | 
工具
自动化文档和自动化测试
包括/docs用于自动化测试(相当于swagger)和/redoc
可以自动生成待测试的接口和Curl命令,并且可以修改请求。
数据库ES的接入
TODO
