当前位置:网站首页>FastAPI 封装一个通用的response
FastAPI 封装一个通用的response
2022-07-31 12:22:00 【小兜全糖(Cx)】
- 安装依赖包
anyio==3.6.1
fastapi==0.79.0
pydantic==1.9.1
sniffio==1.2.0
starlette==0.19.1
h11==0.13.0
uvicorn==0.18.2
pymongo==4.2.0
- 自定义response类
from fastapi.responses import Response
from bson.json_util import dumps
class CoustomResponse(Response):
def __init__(self, content, msg, status,error=None):
if msg:
content['msg'] = msg
if error:
content['error'] = error
super().__init__(
content=dumps(content),
media_type="application/json",
status_code=status
)
我们只需要在这里将我们的逻辑处理完,并将数据放到content中就可以了
3. demo
from fastapi import FastAPI,status
import uvicorn
from fastapi.responses import Response
from bson.json_util import dumps
class CoustomResponse(Response):
def __init__(self, content, msg, status,error=None):
if msg:
content['msg'] = msg
if error:
content['error'] = error
super().__init__(
content=dumps(content),
media_type="application/json",
status_code=status
)
app = FastAPI(default_response_class=CoustomResponse)
@app.get('/test')
async def test():
return CoustomResponse(content={
"haha":"haha"},msg={
"data":"test"},error=None,status=status.HTTP_200_OK)
if __name__=='__main__':
uvicorn.run('main:app',host='0.0.0.0',port=9999,reload=True)
https://stackoverflow.com/questions/63960879/fastapi-custom-response-class-as-default-response-class
边栏推荐
猜你喜欢

JVS应用中心

Exploring Plain Vision Transformer Backbones for Object Detection Paper Reading Notes

A Week of Wonderful Content Sharing (Issue 14)

学习爬虫之Scrapy框架学习(1)---Scrapy框架初学习及豆瓣top250电影信息获取的实战!

系统集成项目管理工程师(软考中级)知识点总结【挣值分析】【关键路径】

Obsidian设置图床

深度学习基本概念

SAP 电商云 Spartacus UI 和 Accelerator UI 里的 ASM 模块

ASM module in SAP Ecommerce Cloud Spartacus UI and Accelerator UI

基于verilog的CRC校验(汇总)
随机推荐
Json和对象之间转换的封装(Gson)
基于姿态估计的护具佩戴检测与动作识别
攻防演练丨赛宁红方管控平台走进广东三地 助力数字政府网络安全建设
How does the SAP ABAP OData service support the $filter (filter) operation trial version
通过斐波那契数再谈函数递归2.0
The 2nd activity of the TOGAF10 Standard Reading Club continues wonderfully, and the highlights will be reviewed!
Double non-one into bytes!!Pure dry goods sharing
Obsidian设置图床
Markdown编辑器语法
Comparison of ipv4 and ipv6 (IPV4)
TOGAF10标准读书会第2场活动精彩继续,高光时刻回顾!
Addition logic for SAP Commerce Cloud Product Review
榕树贷款GPU 硬件架构
[core]-ARMV7-A, ARMV8-A, ARMV9-A Architecture Introduction "Recommended Collection"
ipv4和ipv6对比(IPV4)
MySQL日志中“binlog”的三种格式玩起来真爽
最近两个月谷歌 ad 掉的厉害
Cognitive-exercise rehabilitation medical robot application design
MySQL面试八股文(2022最新整理)
0x80070570 The file or directory is damaged and cannot be deleted (how to delete 0x80070091)