您的位置:首页 > 游戏 > 手游 > 唐山seo排名优化_网站色哦优化8888_seo工作职责_百度推广优化中心

唐山seo排名优化_网站色哦优化8888_seo工作职责_百度推广优化中心

2024/11/17 9:21:23 来源:https://blog.csdn.net/qq_29518275/article/details/142551505  浏览:    关键词:唐山seo排名优化_网站色哦优化8888_seo工作职责_百度推广优化中心
唐山seo排名优化_网站色哦优化8888_seo工作职责_百度推广优化中心

场景

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

例如:

响应体中包含以下字段:

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

具体代码

工具类:

import loggingfrom rest_framework import status
from rest_framework.response import Responsefrom django_middleware_global_request import get_requestlogger = 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_idreturn 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_OKresponse.is_log_resp = Truereturn super().finalize_response(request, response, *args, **kwargs)

视图类中使用:

from common.drf.mixins import ResponseMixin
from rest_framework.viewsets import GenericViewSet, ModelViewSetclass TestViewSet(ResponseMixin,  # 继承工具类ModelViewSet):  # 必须继承viewset, GenericViewSet和ModelViewSet都可queryset = models.TestModel.objects.all()serializer_class = serializers.TestSerializer

注意:

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com