如果您使用基于类的视图,比如APIView 或通用视图,编写您自己的响应函数将无济于事。我认为更好的方法是写custom renderer 格式化成功的响应和custom exception handler 用于错误的响应。此实现为您提供了一个单点来控制所有响应,而无需更改您已经存在的视图。这是我的一个项目的示例代码。您需要根据您的要求对其进行修改。
自定义渲染器
#renderers.py
class CustomJSONRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
response_data = {'message': '', 'errors': [], 'data': data, 'status': 'success'}
getattr(renderer_context.get('view').get_serializer().Meta,'resource_name', 'objects')
# call super to render the response
response = super(CustomJSONRenderer, self).render(response_data, accepted_media_type, renderer_context)
return response
自定义异常处理程序
# custom_exception_handler.py
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
errors = []
message = response.data.get('detail')
if not message:
for field, value in response.data.items():
errors.append("{} : {}".format(field, " ".join(value)))
response.data = {'data': [], 'message': 'Validation Error', 'errors': errors, 'status': 'failure'}
else:
response.data = {'data': [], 'message': message, 'error': [message], 'success': 'failure'}
return response
覆盖REST_FRAMEWORK 设置以使用这些渲染器和异常处理程序。
REST_FRAMEWORK = {
# Add custom renderer.
'DEFAULT_RENDERER_CLASSES'=(
'path.to.CustomJSONRenderer',
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer'),
# Add cutom exception handler
'EXCEPTION_HANDLER': 'path.to.custom_exception_handler'
}