当前位置:网站首页>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
边栏推荐
- 电商rpa是什么意思?跟电商rpi是一个意思吗?
- 字符函数和字符串函数
- dosbox基础使用[通俗易懂]
- 连续变量离散化教程
- 0x80070570 The file or directory is damaged and cannot be deleted (how to delete 0x80070091)
- log4j2的使用
- Basic use of dosbox [easy to understand]
- 串的基本概念与操作
- 手撕Verilog PWM呼吸灯
- PyQt5 rapid development and actual combat 10.2 compound interest calculation && 10.3 refresh blog clicks
猜你喜欢
随机推荐
Structural controllability of switched linear systems with symmetry constraints
ASM module in SAP Ecommerce Cloud Spartacus UI and Accelerator UI
anaconda虚拟环境安装pytorch gpu版本
AMBA APB学习记录(AMBA 3/4)
0x80070570 The file or directory is damaged and cannot be deleted (how to delete 0x80070091)
函数递归1.0
Full GC (Ergonomics)排查分析
A Week of Wonderful Content Sharing (Issue 14)
列表页优化思路
五种数据提交方式的优化
Use ODBC in Excel to read data from CDS view on SAP BTP platform
深圳某游戏研发公司每个工位都装监控,网友:堪比“坐牢”!
三相PWM整流器预测直接功率控制
基于姿态估计的护具佩戴检测与动作识别
ESP8266-Arduino编程实例-MCP9808数字温度传感器驱动
Indoor real-time laser SLAM control method based on biological excitation neural network
立方体IV(暑假每日一题 10)
JVS低代码能力简介及功能清单
vb.net 画曲线
榕树贷款GPU 硬件架构