当前位置:网站首页>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
边栏推荐
- VBA实现双击单元格自动输出对号再次双击取消对号
- CameraToolUnity中两种摄像机的两种观察控制方式
- 基本语法(一)
- Different lower_case_table_names settings for server ('1') and data dictionary ('0') solution
- dosbox基础使用[通俗易懂]
- PAT考试总结(考试心得)
- Markdown编辑器语法
- [core]-ARMV7-A、ARMV8-A、ARMV9-A 架构简介「建议收藏」
- jmeter性能测试步骤入门(性能测试工具jmeter)
- The 2nd activity of the TOGAF10 Standard Reading Club continues wonderfully, and the highlights will be reviewed!
猜你喜欢

Different lower_case_table_names settings for server ('1') and data dictionary ('0') solution

使用docker搭建mysql主从

串的基本概念与操作

Docker practical experience: Deploy mysql8 master-slave replication on Docker

JVM 运行时数据区与JMM 内存模型详解

【OpenCV】-边缘检测汇总示例

Mysql环境变量的配置(详细图解)

kubernetes之服务发现

Acwing第 62 场周赛【未完结】

WebGL给Unity传递参数问题1: Cannot read properties of undefined (reading ‘SendMessage‘)
随机推荐
Qt鼠标穿透
Selenium自动化测试之Selenium IDE
vivado里那些看不懂的原语
立方体IV(暑假每日一题 10)
手撕Verilog PWM呼吸灯
Banyan Tree Loan GPU Hardware Architecture
anaconda虚拟环境安装pytorch gpu版本
行业案例 | 全面防护 赛宁助力能源工控安全建设
ASM module in SAP Ecommerce Cloud Spartacus UI and Accelerator UI
最长算术(暑假每日一题 11)
Docker practical experience: Deploy mysql8 master-slave replication on Docker
双非一本进字节了!!纯干货分享
在 Excel 里使用 ODBC 读取 SAP BTP 平台上 CDS view 的数据
线性表的基本概念
DCM middleware family welcomes a new member
通过斐波那契数再谈函数递归2.0
Markdown编辑器语法
Exploring Plain Vision Transformer Backbones for Object Detection Paper Reading Notes
PAT exam summary (exam experience)
Cognitive-exercise rehabilitation medical robot application design