首页 技术 正文
技术 2022年11月10日
0 收藏 421 点赞 3,456 浏览 2134 个字

背景

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

最简单的栗子

路径操作函数返回一个 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 Optionalimport uvicorn
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponsefrom pydantic import BaseModelapp = 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 itemif __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)

正确传参的请求结果

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,156
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,624
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,468
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,240
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,876
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,043