当前位置:网站首页>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
边栏推荐
- 分布式监视 Zabbix 和 Prometheus 到底怎么选?千万别用错了!
- 建情人节表白网站(超详细过程,包教包会)
- 立一个flag
- How does the SAP ABAP OData service support the $filter (filter) operation trial version
- 在 Excel 里使用 ODBC 读取 SAP BTP 平台上 CDS view 的数据
- VBA输出日志到工作簿demo
- 机器学习基本概念
- The function of SQL GROUP BY dependence
- CWE4.8 -- The 25 most damaging software security issues in 2022
- 行业案例 | 全面防护 赛宁助力能源工控安全建设
猜你喜欢
随机推荐
全动力学约束的机器人高效时间最优轨迹规划
订song餐系统
[Shader] Shader official example [easy to understand]
字符函数和字符串函数
TOGAF10标准读书会第2场活动精彩继续,高光时刻回顾!
MySQL百万数据优化总结 一
JVS开发套件产品定位
攻防演练丨赛宁红方管控平台走进广东三地 助力数字政府网络安全建设
SAP ABAP OData 服务如何支持 $filter (过滤)操作试读版
WebGL给Unity传递参数问题1: Cannot read properties of undefined (reading ‘SendMessage‘)
荣耀手机参数写错,客服认为没错
VBA实现双击单元格自动输出对号再次双击取消对号
消息队列面试题(2022最新整理)
Spark GC日志分析
Quickly learn database management
三相PWM整流器预测直接功率控制
[core]-ARMV7-A, ARMV8-A, ARMV9-A Architecture Introduction "Recommended Collection"
关于IDEA开发工具的介绍
一文吃透哈希表
初识QEMU









