Django-DRF全局异常捕获,响应封装,自动生成接口文档

一、全局异常

1 统一接口的返回方式,即便视图函数执行出错
2 使用方式,写一个函数,并在setting中配置

from rest_framework import status
from rest_framework.views import exception_handler
from rest_framework.response import Response


def common_exception_handler(exc, context):
        response = exception_handler(exc, context)
        if response is None:
            response = Response({'code':999,'detail': '未知错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return response

    
# setting
    	REST_FRAMEWORK = {
    		'EXCEPTION_HANDLER':'app01.utils.common_exception_handler'
		}

二、封装Response对象

自己封装一个response,可以简化我们views中的代码

class APIResponse(Response):
    def __init__(self, code=100, msg='成功', data=None, status=None, headers=None, content_type=None, **kwargs):
        dic = {'code': code, 'msg': msg}
        if data:
            dic['data'] = data

        dic.update(kwargs) # 这里使用update
        super().__init__(data=dic, status=status,
                         template_name=None, headers=headers,
                         exception=False, content_type=content_type)
        
        
# 2 视图中使用方式:
	return APIResponse(code=100,msg='查询成功',data=ser.data,count=200,next='http://wwwa.asdfas')

三、自动生成接口文档

1 借助于第三方:coreapi,swagger
2 在路由中
    from rest_framework.documentation import include_docs_urls
    path('docs/', include_docs_urls(title='图书管理系统api'))
3 在配置文件中
	REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
	}
4 写视图类(需要加注释)
    class BookListCreateView(ListCreateAPIView):
        """
        get:
        返回所有图书信息

        post:
        新建图书.
        """
        queryset = Student.objects.all()
        serializer_class = StudentSerializer
5 只需要在浏览器输入,就可以看到自动生成的接口文档()
	http://127.0.0.1:8000/docs/
posted @ 2020-12-01 10:36  王寄鱼  阅读(694)  评论(0编辑  收藏  举报