美文网首页
renderclass设置

renderclass设置

作者: lkning | 来源:发表于2018-03-02 15:37 被阅读0次

直接上代码
重写JSONRenderer类,类似于django的中间件,在response返回中viewset和试图就会穿过render方法,封装了code和msg参数

from rest_framework.renderers import JSONRenderer
class CustomJsonRender(JSONRenderer):
    """ 自定义返回数据 Json格式
    {
        "code": 0,
        "msg": "success",
        "data": { ... }
    }
    """

    def render(self, data, accepted_media_type=None, renderer_context=None):
        if renderer_context:
            response = renderer_context['response']
            code = 0 if int(response.status_code / 100) == 2 else response.status_code
            msg = 'success'
            if isinstance(data, dict):
                msg = data.pop('msg', msg)
                code = data.pop('code', code)
                data = data.pop('data', data)
            if code != 0 and data:
                msg = data.pop('detail', 'failed')
            response.status_code = 200
            res = {
                'code': code,
                'msg': msg,
                'data': data,
            }
            print(res)
            return super().render(res, accepted_media_type, renderer_context)
        else:
            return super().render(data, accepted_media_type, renderer_context)
  • 使用
class RouteView(ModelViewSet):
    queryset = models.UserInfo.objects.all()
    serializer_class = RouteSerializer
    renderer_classes = (CustomJsonRender,)
    search_fields = ['user']
  • setting中的配置
REST_FRAMEWORK = {
    'UNAUTHENTICATED_USER': None,
    'UNAUTHENTICATED_TOKEN': None,
    "DEFAULT_THROTTLE_RATES": {
        'luffy_anon': '5/m',
        'luffy_user': '10/m'
    },
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend','rest_framework.filters.SearchFilter'),
    'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',)
}

相关文章

网友评论

      本文标题:renderclass设置

      本文链接:https://www.haomeiwen.com/subject/arpaxftx.html