当前位置:网站首页>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
边栏推荐
- Banyan Tree Loan GPU Hardware Architecture
- 带有对称约束切换线性系统的结构可控性
- golang八股文整理(持续搬运)
- 0x80070570 The file or directory is damaged and cannot be deleted (how to delete 0x80070091)
- ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)解决办法
- 集群的安全模式
- Standard SQL/JSON - the sobering part
- Getting started with jmeter performance testing steps (performance testing tool jmeter)
- JVS轻应用的组成与配置
- FastAPI 封装一个通用的response
猜你喜欢
Anaconda安装labelImg图像标注软件
字符函数和字符串函数
chroot命令
CentOS7 - yum install mysql
JVS应用中心
【OpenCV】-边缘检测汇总示例
Error EPERM operation not permitted, mkdir ‘Dsoftwarenodejsnode_cache_cacach两种解决办法
ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your
订song餐系统
纷享销客罗旭对话元气森林黄晓枫:零售数字化的终点不是创新,而是数据
随机推荐
How to correctly write the binary stream of the file returned by the server to the local file and save it as a file
亲测可用!!!WPF中遍历整个窗口的所有TextBox组件,对每个输入框做非空判断。
Spark GC日志分析
Getting started with jmeter performance testing steps (performance testing tool jmeter)
全动力学约束的机器人高效时间最优轨迹规划
PyQt5快速开发与实战 9.7 UI层的自动化测试
函数递归1.0
一周精彩内容分享(第14期)
Basic use of dosbox [easy to understand]
Json和对象之间转换的封装(Gson)
字符函数和字符串函数
PyQt5快速开发与实战 10.1 获取城市天气预报
Hybrid brain-computer interface system based on steady-state visual evoked potentials and attentional EEG
log4j2的使用
PAT考试总结(考试心得)
JVS低代码能力简介及功能清单
最近两个月谷歌 ad 掉的厉害
Indoor real-time laser SLAM control method based on biological excitation neural network
一文吃透哈希表
攻防演练丨赛宁红方管控平台走进广东三地 助力数字政府网络安全建设