FastAPI(46)- JSONResponse

发布时间:2022-06-26 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了FastAPI(46)- JSONResponse脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

FastAPI(46)- JSONResponse

#!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)

FastAPI(46)- JSONResponse

 

正常传参的请求结果

FastAPI(46)- JSONResponse

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 是自动帮忙做了转换的

等价写法如下

FastAPI(46)- JSONResponse

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)

FastAPI(46)- JSONResponse

 

打印数据,来看看细节

FastAPI(46)- JSONResponse

@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) 

FastAPI(46)- JSONResponse

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 源码

FastAPI(46)- JSONResponse

会调用 json.dumps() 方法

 

看看 Response 源码

FastAPI(46)- JSONResponse

看到其实可以自定义 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)

 

正确传参的请求结果

FastAPI(46)- JSONResponse

 

更多自定义响应类型

  • JSONResponse
  • HTMLResponse、PlainTextResponse
  • ORJSONResponse、UJSONResponse
  • RedirectResponse
  • StreamingResponse、FileResponse

 

  • 背景
  •     返回响应数据的常见方式(基础版)
  • 最简单的栗子
  •     正常传参的请求结果
  •     console 打印结果
  •     等价写法
  •     打印数据,来看看细节
  •     假设将 item Pydantic Model 类型直接传给 JSONResponse 呢?
  • 看看 JSONResponse 源码
  • 看看 Response 源码
  • 修改 status_code 响应码
  •     正确传参的请求结果
  • 更多自定义响应类型

 

  • 本文作者: 小菠萝测试笔记
  • 本文链接: https://www.cnblogs.com/poloyy/p/15364445.html

背景

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

 

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

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

 

最简单的栗子

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

FastAPI(46)- JSONResponse

#!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)

FastAPI(46)- JSONResponse

 

正常传参的请求结果

FastAPI(46)- JSONResponse

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 是自动帮忙做了转换的

等价写法如下

FastAPI(46)- JSONResponse

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)

FastAPI(46)- JSONResponse

 

打印数据,来看看细节

FastAPI(46)- JSONResponse

@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) 

FastAPI(46)- JSONResponse

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 源码

FastAPI(46)- JSONResponse

会调用 json.dumps() 方法

 

看看 Response 源码

FastAPI(46)- JSONResponse

看到其实可以自定义 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)

 

正确传参的请求结果

FastAPI(46)- JSONResponse

 

更多自定义响应类型

  • JSONResponse
  • HTMLResponse、PlainTextResponse
  • ORJSONResponse、UJSONResponse
  • RedirectResponse
  • StreamingResponse、FileResponse

 

  • 背景
  •     返回响应数据的常见方式(基础版)
  • 最简单的栗子
  •     正常传参的请求结果
  •     console 打印结果
  •     等价写法
  •     打印数据,来看看细节
  •     假设将 item Pydantic Model 类型直接传给 JSONResponse 呢?
  • 看看 JSONResponse 源码
  • 看看 Response 源码
  • 修改 status_code 响应码
  •     正确传参的请求结果
  • 更多自定义响应类型

 

  • 本文作者: 小菠萝测试笔记
  • 本文链接: https://www.cnblogs.com/poloyy/p/15364445.html

脚本宝典总结

以上是脚本宝典为你收集整理的FastAPI(46)- JSONResponse全部内容,希望文章能够帮你解决FastAPI(46)- JSONResponse所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:数据库