FastAPI(46)- JSONResponse
FastAPI(46)- JSONResponse
- 创建 FastAPI 路径操作函数时,通常可以从中返回任何数据:字典、列表、Pydantic 模型、数据库模型等
- 默认情况下,FastAPI 会使用 jsonable_encoder 自动将该返回值转换为 JSON 字符串
- 然后,FastAPI 会将与 JSON 兼容的数据(例如 dict)放在 JSONResponse 中,然后将 JSONResponse 返回给客户端
- 总结:默认情况下,FastAPI 将使用 JSONResponse 返回响应
- 但是可以直接从路径操作函数中返回自定义的 JSONResponse
返回响应数据的常见方式(基础版)
路径操作函数返回一个 Pydantic Model
Response Header 的显示 content-type 是 JSON
console 打印结果
id='string' name='string' title='string' <class '38_responses.Item'>
INFO: 127.0.0.1:51856 - "POST /item HTTP/1.1" 200 OK
- item 类型的确是 Pydantic Model 类
- 但最终返回给客户端的是一个 JSON 数据
等价写法
@app.post("/item")
async def get_item(item: Item):
return item
@app.post("/item")
async def get_item(item: Item):
return item
这样写也能返回 JSON 数据,是因为FastAPI 是自动帮忙做了转换的
等价写法如下
{'id': 'string', 'name': 'string', 'title': 'string'} <class 'dict'>
INFO: 127.0.0.1:52880 - "POST /item2 HTTP/1.1" 200 OK
假设将 item Pydantic Model 类型直接传给 JSONResponse 呢?
@app.post("/item3")
async def get_item(item: Item):
return JSONResponse(content=item)
访问该接口就会报错
会调用 json.dumps() 方法
看看 Response 源码
更多自定义响应类型
- JSONResponse
- 本文作者: 小菠萝测试笔记
- 本文链接: