参考:https://www.jianshu.com/p/c0be24752584
原来的写法太繁琐,而且导致接口api界面没了,不是我想要的,就调整了如下
修改permissions.py
from rest_framework import permissions from rest_framework.renderers import JSONRenderer # 重新封装Response对象 def response_wrapper(code, msg, data): # 自定义一个返回字典 return {'code': code, 'msg': msg, 'data': data} class MyJSONRenderer(JSONRenderer): # 重构render方法 def render(self, data, accepted_media_type=None, renderer_context=None): code = renderer_context['response'].status_code if renderer_context and code == 200: ret = response_wrapper(code=code, msg='success', data=data) else: ret = response_wrapper(code=code, msg='fail', data=data) # 返回JSON数据 return super().render(ret, accepted_media_type, renderer_context)
修改settings.py
REST_FRAMEWORK = { ... # drf提供的渲染类 'DEFAULT_RENDERER_CLASSES': [ 'script1.permissions.MyJSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], }
标签:code,自定义,renderer,context,msg,数据格式,data,response,drf From: https://www.cnblogs.com/shijia/p/16940512.html