django drf 统一Response格式

场景

需要将响应体按照格式规范返回给前端。

例如:

响应体中包含以下字段:

python 复制代码
{
    "result": true,
    "data": {},
    "code": 200,
    "message": "ok",
    "request_id": "20cadfe4-51cd-42f6-af81-016639232a66"
}

具体代码

工具类:

python 复制代码
import logging

from rest_framework import status
from rest_framework.response import Response

from django_middleware_global_request import get_request

logger = logging.getLogger("app")


class ResponseMixin:
   def finalize_response(self, request, response, *args, **kwargs):
       """
       异常处理函数,搭配custom_exception_handler进行处理
       :param request:
       :param response:
       :param args:
       :param kwargs:
       :return:
       """
       global_request = get_request()
       current_reqeust_id = getattr(global_request, "current_request_id", None)
       if not getattr(request, "_wrapper_response", True):
           if isinstance(response, Response) and isinstance(response.data, dict):
               response.data["request_id"] = current_reqeust_id
           return super().finalize_response(request, response, *args, **kwargs)
       if isinstance(response, Response):
           if not response.exception:
               response.data = {
                   "result": True,
                   "data": response.data,
                   "code": 200,
                   "message": "ok",
                   "request_id": current_reqeust_id,
               }
           else:
               response.data = {
                   "result": False,
                   "data": response.data,
                   "code": response.status_code,
                   "message": str(response.data),
                   "error": str(response.data),
                   "request_id": current_reqeust_id,
               }
           response.status_code = status.HTTP_200_OK
           response.is_log_resp = True
       return super().finalize_response(request, response, *args, **kwargs)

视图类中使用:

python 复制代码
from common.drf.mixins import ResponseMixin
from rest_framework.viewsets import GenericViewSet, ModelViewSet

class TestViewSet(ResponseMixin,  # 继承工具类
                  ModelViewSet):  # 必须继承viewset, GenericViewSet和ModelViewSet都可
   queryset = models.TestModel.objects.all()
   serializer_class = serializers.TestSerializer

注意:

视图类必须继承viewset,无论是GenericViewSet和ModelViewSet都可以

相关推荐
SelectDB10 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码18 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi3 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi3 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab