请求体现的是后端的数据服务能力,而响应体现的是后端向前端的数据展示能力。
一,一个完整的web响应应该包含哪些东西
一个完整的 Web 响应通常包含以下几个主要部分:
1. 状态行
- HTTP 版本
- 状态码
- 状态消息
例如:`HTTP/1.1 200 OK`
2. 响应头
常见的响应头包括:
a. 通用头部:
- Date: 响应生成的日期和时间
- Connection: 连接状态(如 keep-alive 或 close)
b. 响应特定头部:
- Server: 服务器软件名称和版本
- Content-Type: 响应体的 MIME 类型
- Content-Length: 响应体的长度(以字节为单位)
- Content-Encoding: 响应体的编码方式(如 gzip)
c. 实体头部:
- Last-Modified: 资源的最后修改日期
- ETag: 资源的唯一标识符
- Expires: 资源的过期时间
- Cache-Control: 缓存控制指令
d. 安全相关头部:
- Set-Cookie: 设置 HTTP cookie
- X-XSS-Protection: 控制浏览器的 XSS 筛选器
- X-Frame-Options: 控制页面是否可以被嵌入框架
- Content-Security-Policy: 内容安全策略
- Strict-Transport-Security: 强制使用 HTTPS
e. 跨域相关头部:
- Access-Control-Allow-Origin: 指定允许跨域请求的源
- Access-Control-Allow-Methods: 允许的 HTTP 方法
- Access-Control-Allow-Headers: 允许的请求头
3. 空行
用于分隔头部和响应体
4. 响应体
- 包含请求的资源或处理结果
- 格式取决于 Content-Type(如 HTML、JSON、XML、图片等)
示例:
HTTP/1.1 200 OK
Date: Mon, 23 May 2023 12:28:53 GMT
Server: Apache/2.4.41 (Ubuntu)
Content-Type: application/json; charset=utf-8
Content-Length: 234
Cache-Control: max-age=3600
ETag: "686897696a7c876b7e"
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000; includeSubDomains
{
"id": 12345,
"name": "Example Product",
"description": "This is an example product description.",
"price": 99.99,
"inStock": true
}
注意事项:
- 并非所有响应都需要包含响应体(如 204 No Content)。
- 响应头的具体内容会根据请求和应用需求而变化。
- 在实际应用中,应当根据安全需求和性能考虑来选择合适的响应头。
- 对于流式响应或大文件传输,可能会使用分块传输编码(Transfer-Encoding: chunked)。
- 在设计 API 时,应考虑响应的一致性,包括错误处理和状态码的使用。
二,响应
(一)简单响应
就像前面我们定义的路由处理函数一样,可以通过返回一个字典来返回一个简单的响应内容:
import uvicorn
from fastapi import FastAPI, Header
app = FastAPI()
@app.get("/test/")
def test():
response = {
"message": "Hello, World!"}
print(type(response)) # -> <class 'dict'>
return response
if '__main__' == __name__:
uvicorn.run(app, host='127.0.0.1', port=8088)
通过打印的内容我们可以看到,返回的是一个 Python 字典,来看看 FastAPI 是怎么处理它的:

具体到不同的客户端情况:
1,使用浏览器直接访问:
- 你会看到 JSON 格式的文本
2,使用 JavaScript/Ajax:
fetch('http://127.0.0.1:8088/test/')
.then(response => response.json())
.then(data => console.log(typeof data, data));
// 输出:object {message: "Hello, World!"}
- 接收到的是 JavaScript 对象
3,使用 Python requests 库:
import requests
response = requests.get('http://127.0.0.1:8088/test/')
data = response.json()
print(type(data), data)
# 输出:<class 'dict'> {'message': 'Hello, World!'}
- 解析后得到的是 Python 字典
4,使用 curl 命令行工具:
curl http://127.0.0.1:8088/test/
# 输出:{"message": "Hello, World!"}
- 接收到的是 JSON 格式的字符串
(二)响应数据模型
我们可以定义请求体的数据模型来接收请求体的数据,同样也可以定义响应数据模型来规范响应数据。
- 响应数据模型在 API 文档页中为 JSON 格式。
只需要在任意的路由处理函数中使用 response_model 参数来声明用于响应的模型。
FastAPI 将使用此 response_model 来:
- 将输出数据转换为其声明的类型。
- 校验数据。
- 在 OpenAPI 的路径操作中为响应添加一个 JSON Schema。
- 并在自动生成文档系统中使用。
1,定义与使用响应数据模型
首先同样使用 pydantic 定义响应数据模型:
import uvicorn
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# 1,定义请求提数据模型
class User(BaseModel):
first_name: str
last_name: str
# 2,定义响应数据模型
class UserExtra(BaseModel):
first_name: str
last_name: str
full_name: str | None = None
# 处理请求
@app.post("/create-user/", response_model=UserExtra)
async def create_user(user: User) -> Any:
# 4,处理请求数据
full_name = user.first_name + ' ' + user.last_name
# 5,返回数据
return {
"first_name": user.first_name,
"last_name": user.last_name,
"full_name": full_name
}
if '__main__' == __name__:
uvicorn.run(app, host='127.0.0.1', port=8088)
之所以要将响应模型放在参数中声明,而不是放在函数返回值中使用,是因为路由处理函数可能不会真正返回响应模型(可能是一个 dict、数据库对象或其他模型),这是就可以使用 response_model 来执行字段约束和序列化。
查看 API:


当路由处理函数的返回值无法被 response_model 处理成满足响应模型的数据的时候,就会报错:
import uvicorn
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# 1,定义请求提数据模型
class User(BaseModel):
first_name: str
last_name: str
# 2,定义响应数据模型
class UserExtra(BaseModel):
first_name: str
last_name: str
full_name: str | None = None
# 处理请求
@app.post("/create-user/", response_model=

:做出响应&spm=1001.2101.3001.5002&articleId=140619663&d=1&t=3&u=e86c32bca6244ad2abb72c72f7eff493)
2245

被折叠的 条评论
为什么被折叠?



