当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
[Shader] Shader official example [easy to understand]
Hybrid brain-computer interface system based on steady-state visual evoked potentials and attentional EEG
【OpenCV】-边缘检测汇总示例
A Week of Wonderful Content Sharing (Issue 14)
立方体IV(暑假每日一题 10)
LRU缓存[线性表 -> 链表 -> hash定位 -> 双向链表]
Docker build Mysql master-slave replication
Wearing detection and action recognition of protective gear based on pose estimation
消息队列面试题(2022最新整理)
深圳某游戏研发公司每个工位都装监控,网友:堪比“坐牢”!
建情人节表白网站(超详细过程,包教包会)
Comparison of ipv4 and ipv6 (IPV4)
【核心概念】图像分类和目标检测中的正负样本划分以及架构理解
JVS低代码能力简介及功能清单
订song餐系统
anaconda虚拟环境安装pytorch gpu版本
第十二章 使用中的 OpenAPI 属性
基于C51实现按键控制
Use docker to build mysql master-slave
字符函数和字符串函数