当前位置:网站首页>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
边栏推荐
猜你喜欢
![LRU缓存[线性表 -> 链表 -> hash定位 -> 双向链表]](/img/ad/dd80541514d6fedde8c730218fdf5a.png)
LRU缓存[线性表 -> 链表 -> hash定位 -> 双向链表]

基于C51实现按键控制

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

anaconda虚拟环境安装pytorch gpu版本

busybox之reboot命令流程分析

学习爬虫之Scrapy框架学习(1)---Scrapy框架初学习及豆瓣top250电影信息获取的实战!

手撕Verilog PWM呼吸灯

三六零与公安部三所发布报告:关基设施保护成为网络安全博弈关键

The 2nd activity of the TOGAF10 Standard Reading Club continues wonderfully, and the highlights will be reviewed!

生信周刊第38期
随机推荐
消息队列面试题(2022最新整理)
Data Persistence Technology - MP
Wearing detection and action recognition of protective gear based on pose estimation
A40i/T3 uboot启动时对PMU部分初始化
Comparison of ipv4 and ipv6 (IPV4)
立方体IV(暑假每日一题 10)
尚硅谷–MySQL–基础篇(P1~P95)
数据湖(十九):SQL API 读取Kafka数据实时写入Iceberg表
JVS应用中心
CWE4.8 -- 2022年危害最大的25种软件安全问题
Obsidian设置图床
mysql根据多字段分组——group by带两个或多个参数
机器学习基本概念
kernel syscore
file contains vulnerabilities
jmeter性能测试步骤入门(性能测试工具jmeter)
Quickly learn database management
关于Mysql数据库的介绍
PAT exam summary (exam experience)
深度学习基本概念