django drf 统一Response格式
场景
需要将响应体按照格式规范返回给前端。
例如:
响应体中包含以下字段:
{
"result": true,
"data": {},
"code": 200,
"message": "ok",
"request_id": "20cadfe4-51cd-42f6-af81-016639232a66"
}
具体代码
工具类:
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)
视图类中使用:
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都可以