所谓的“请求与响应”是就是考虑 http 协议的请求与响应过程。HTTP报文本身是由多行数据构成的字文本,构成十分复杂,但是逻辑十分简单。

我们使用框架的原因就是简化封包的过程,而将精力放在如何处理数据的逻辑上。在框架下的“请求”就是如何通过框架获取请求的参数;在框架下的“响应”就是如何将要返回的数据交给框架处理。

01 路径参数

路径参数一般用于 get 请求。

1
2
3
http://example.com/xxy/p/110119120

# 其中,`110119120`就是路径参数

1.1 示例

1
2
3
4
5
6
7
8
9
# 通过`{}`来标注变量

@app01.get("articles/{id}")
def get_article(id):
print("id", id, type(id))
return{
"article_id": id
}

1.2 注意顺序

对比下列两个代码,代码的结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
@app01.get("articles/1")
def get_article(id):
print("id", id, type(id))
return{
"article_id": "root_user"
}

@app01.get("articles/{id}")
def get_article(id):
print("id", id, type(id))
return{
"article_id": id
}
1
2
3
4
5
6
7
8
9
10
11
12
13
@app01.get("articles/{id}")
def get_article(id):
print("id", id, type(id))
return{
"article_id": id
}

@app01.get("articles/1")
def get_article(id):
print("id", id, type(id))
return{
"article_id": "root_user"
}

所以,注意,路由匹配是有顺序的!~

1.3 类型限制

1
2
3
4
5
6
7
8
# 参数默认类型是str,可以通过指定数据类型实现类型转换

@app01.get("articles/{id}")
def get_article(id:int):
print("id", id, type(id))
return{
"article_id": id
}

02 请求参数

请求参数也一般用于 get 请求。

1
2
3
http://example.com/jobs/python?type=ai

# 其中,问号后面,`type=ai`就是请求参数

2.1 示例

1
2
3
4
5
6
7
8
from typing import Union
@app02.get("/jobs/{kd}")
async def get_jobs(kd, xl:Union[str, None]=None, gj:Optional[str]=None):
return{
"kd": kd,
"xl": xl,
"gj": gj,
}

在指定数据类型时,需要多类型的情况下可以使用,Union 来实现。

特殊情况:仅仅需要和 None类型联合时,可以简写:Optional[str] = Union[str, None]

03 请求体数据

请求体,一般用于 POST 请求

FastAPI 基于 Pydantic ,用来做类型的强制校验,不符合类型要求就会抛出异常。

1
2
# 安装Pydantic
pip install pydantic

请求体内数据格式一般为json: Content-Type: application/json

3.1 示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14

from pydantic import BaseModel
from typing import List

class User(BaseModel):
name: str
age: int
birth: date
friends: List[int]

from typing import Union
@app03.post("/user")
async def get_data(user: User):
return user

3.2 数据校验

04 form表单数据

form表单数据,一般用于POST请求。

与json方式的请求体不同,使用form表单数据时 Content-Type: application/x-www-form-urlencoded。比如在OAuth2 规范的一种使用方式中,需要将用户名、密码作为表单字段发送,而不是JSON

FastAPI可以使用Form组件来接受表单数据,需要先使用pip install python-multipart 命令进行安装。

1
pip install python-multipart

4.1 示例

1
2
3
4
5
6
7
8
from fastapi import FastAPI, Form

app = FastAPI()

@app.post("regin")
def regin(username: str = Form(), possword: str = Form()):
return {"username": username}