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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM