FastAPI(46)- JSONResponse

背景

  • 创建 FastAPI 路径操作函数时,通常可以从中返回任何数据:字典、列表、Pydantic 模型、数据库模型等
  • 默认情况下,FastAPI 会使用 jsonable_encoder 自动将该返回值转换为 JSON 字符串
  • 然后,FastAPI 会将与 JSON 兼容的数据(例如 dict)放在 JSONResponse 中,然后将 JSONResponse 返回给客户端
  • 总结:默认情况下,FastAPI 将使用 JSONResponse 返回响应
  • 但是可以直接从路径操作函数中返回自定义的 JSONResponse

返回响应数据的常见方式(基础版)

https://www.cnblogs.com/poloyy/p/15364635.html

最简单的栗子

路径操作函数返回一个 Pydantic Model

#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/10/3 3:26 下午
# file: 38_responses.py
"""
from typing import Optional

import uvicorn
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse

from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    id: str
    name: str
    title: Optional[str] = None


@app.post("/item")
async def get_item(item: Item):
    # 打印看看传进来的数据是什么
    print(item, type(item))

    # 直接返回传进来的数据
    return item

if __name__ == '__main__':
    uvicorn.run(app="38_responses:app", reload=True, host="127.0.0.1", port=8080)

正常传参的请求结果

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

这样写也能返回 JSON 数据,是因为FastAPI 是自动帮忙做了转换的

等价写法如下

from fastapi.encoders import jsonable_encoder

@app.post("/item")
async def get_item(item: Item):
    json_body = jsonable_encoder(item)
    return JSONResponse(content=json_body)

打印数据,来看看细节

@app.post("/item2")
async def get_item(item: Item):
    json_body = jsonable_encoder(item)
    
    print(json_body, type(json_body))
    
    return JSONResponse(content=json_body) 

console 打印结果

{'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)

访问该接口就会报错

    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Item is not JSON serializable
  • 类型错误:项目类型的对象不是 JSON 可序列化的
  • 因为它无法转换为 JSON 数据,所以报错了

看看 JSONResponse 源码

会调用 json.dumps() 方法

看看 Response 源码

看到其实可以自定义 status_code、headers、media_type 哦

headers 后面再用单独的篇幅来讲

修改 status_code 响应码

@app.post("/item2")
async def get_item(item: Item):
    json_item = jsonable_encoder(item)
    return JSONResponse(content=json_item, status_code=status.HTTP_201_CREATED)

正确传参的请求结果

更多自定义响应类型

原文地址:https://www.cnblogs.com/poloyy/p/15364445.html