当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
学习爬虫之Scrapy框架学习(1)---Scrapy框架初学习及豆瓣top250电影信息获取的实战!
MySQL日志中“binlog”的三种格式玩起来真爽
立方体IV(暑假每日一题 10)
尚硅谷–MySQL–基础篇(P1~P95)
JVM 运行时数据区与JMM 内存模型详解
普林斯顿微积分读本03第二章--编程实现函数图像绘制、三角学回顾
Is the working process of the belt you know the story - actionreducerstore
Shengxin Weekly Issue 38
基本语法(二)
三六零与公安部三所发布报告:关基设施保护成为网络安全博弈关键
Exploring Plain Vision Transformer Backbones for Object Detection 论文阅读笔记
手撕Verilog PWM呼吸灯
DCM 中间件家族迎来新成员
kubernetes之服务发现
CWE4.8 -- 2022年危害最大的25种软件安全问题
A Week of Wonderful Content Sharing (Issue 14)
Different lower_case_table_names settings for server ('1') and data dictionary ('0') solution
如何正确地把服务器端返回的文件二进制流写入到本地保存成文件
AMBA APB学习记录(AMBA 3/4)
消息队列面试题(2022最新整理)








