当前位置:网站首页>FastAPI encapsulates a generic response
FastAPI encapsulates a generic response
2022-07-31 12:32:00 【Xiaodou Whole Sugar (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
)
We just need to finish processing our logic here,并将数据放到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 到底怎么选?千万别用错了!
PAT考试总结(考试心得)
Quickly learn database management
JVS低代码能力简介及功能清单
行业案例 | 全面防护 赛宁助力能源工控安全建设
FIFO深度计算学习记录(汇总)
系统集成项目管理工程师(软考中级)知识点总结【挣值分析】【关键路径】
In Excel using ODBC consumer SAP ABAP CDS view
golang八股文整理(持续搬运)
centos7安装mysql5.7
After Effects 教程,如何在 After Effects 中修复曝光不足的镜头?
Anaconda安装labelImg图像标注软件
Acwing第 62 场周赛【未完结】
PyQt5快速开发与实战 9.7 UI层的自动化测试
JVS开发套件产品定位
ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your
Exploring Plain Vision Transformer Backbones for Object Detection Paper Reading Notes
PyQt5 rapid development and actual combat 10.1 Get city weather forecast
centos7安装mysql5.7步骤(图解版)
vb.net 画曲线









