image.png

教程:https://fastapi.tiangolo.com/zh/tutorial/

API:https://fastapi.tiangolo.com/zh/reference/

文档https://fastapi.tiangolo.com

Source Codehttps://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
2
3
4
5
pip install fastapi
# an ASGI server, for production such as [Uvicorn](https://www.uvicorn.org/) or [Hypercorn](https://github.com/pgjones/hypercorn).

# pip install "uvicorn[standard]"

开始

main.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 类型检查,Union允许为多种类型的检查,相当于或
from typing import Union

from fastapi import FastAPI

app = FastAPI()

# 根路径返回值
@app.get("/")
def read_root():
return {"Hello": "World"}

# /items/,{item_id}作为路径传递,q作为参数传递
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
  1. 使用 async / await 来将上述代码变为异步

  2. 测试 :
    http://127.0.0.1:8000/items/5?q=somequery.

    返回值:

    item_id:5

    q:“somequery”

  3. 开启服务器,运行main中的app程序,–reload会自动刷新

    1
    2
    3
    uvicorn main:app --reload
    # 或者是在最新的版本是这样的:
    fastapi dev main.py
序号 方法 描述
1 get 查看
2 post 创建
3 put 更新
4 delete 删除

新案例

image.png
新增PUT和Item,PUT就是最下面的函数,除了方法为put以外没有差异,Item是自建类,用于数据类型检查。

可以在路径传参,声明的参数不是路径参数时,路径操作函数会把该参数自动解释为查询参数。即问号后面的参数,比如“?skip=0&limit=10”会被解析成函数传参skip=0,limit=10

测试和文档

swagger类似,直接在/docs路径 点击try 即可

docs的管理:加tags将几个接口分为一组,等等

测试

编写测试文件,然后pytest

调试

uvicorn

状态管理

可能没法啊,只能add_task,没法删除

在FastAPI中,可以使用背景任务(background tasks)来实现状态管理。以下是一个简单的示例,展示了如何使用FastAPI和BackgroundTask实现状态管理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

class StatusManager:
def __init__(self):
self.is_running = False

def startCapture(self, background_tasks: BackgroundTasks):
self.is_running = True
background_tasks.add_task(self.stopCapture)

def stopCapture(self):
self.is_running = False

# 获取状态管理器实例
status_manager = StatusManager()

@app.get("/status")
async def get_status():
return {"is_running": status_manager.is_running}

@app.post("/startCapture")
async def start_capture():
status_manager.startCapture()
return {"message": "Capture started"}

@app.post("/stopCapture")
async def stop_capture():
status_manager.stopCapture()
return {"message": "Capture stopped"}

关注点分离

bymin

1

工具

自动化文档和自动化测试

包括/docs用于自动化测试(相当于swagger)和/redoc
可以自动生成待测试的接口和Curl命令,并且可以修改请求。

数据库ES的接入

TODO