django-drf 全局封装

封装全局异常

common_exceptions.py

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

def common_exception_handler(exc, context):
      # 记录日志
    request = context.get('request')
    view = context.get('view')
    ip = request.META.get('REMOTE_ADDR')
    path = request.get_full_path()
    method = request.method
    user_id = request.user.id or '【匿名用户】'
    logger.error(
        f'操作出错:{str(exc)},ip地址为:{ip},请求方式是:{method},请求地址是:{path},用户为:{user_id},视图类为:{str(view)}')
    
    view_name =view.__class__.__name__
    response = exception_handler(exc, context)
    if response:
        if isinstance(response.data,list):
            err=response.data[0]
        elif isinstance(response.data, dict):
            err = response.data.get('detail', f'{view_name}视图出错了,错误信息:系统错误,请联系系统管理员')
        else:
            err='系统错误,请联系系统管理员'
        return Response({'code':901,'msg': f'{view_name}视图出错了,drf的异常:{err}'})
    else:
        if isinstance(exc,ZeroDivisionError):
            return Response({'code':950,'msg': f'{view_name}视图出错了,错误信息:不能除以0'})
        elif isinstance(exc, TypeError):
            return Response({'code':951,'msg': f'{view_name}视图出错了,错误信息:类型错误,不同类型不能操作'})
        elif isinstance(exc, KeyError):
            return Response({'code': 952, 'msg': f'{view_name}视图出错了,错误信息:字典键错误,不存在键'})
        elif isinstance(exc, ValueError):
            return Response({'code': 953, 'msg': f'{view_name}视图出错了,错误信息:值错误,类型不对'})
        elif isinstance(exc, NameError):
            return Response({'code': 954, 'msg': f'{view_name}视图出错了,错误信息:变量名错误,变量未被定义'})
        elif isinstance(exc, IndexError):
            return Response({'code': 956, 'msg': f'{view_name}视图出错了,错误信息:索引错误,超出范围'})
        else:
            return Response({'code': 957, 'msg': f'{view_name}视图出错了,错误信息:其他错误'})

setting.py

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'utils.common_exceptions.exception_handler',
}

封装Response

common_response.py

from rest_framework.response import Response

class APIResponse(Response):

    def __init__(self,code=100,msg='成功', status=None, headers=None, **kwargs):
        data={'code':code,'msg':msg}
        if kwargs:
            data.update(kwargs)
         		      super().__init__(data=data,status=status,headers=headers)

封装model

common_model.py

from django.db import models

class BaseModel(models.Model):
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_time = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')
    is_delete = models.BooleanField(default=False, verbose_name='是否删除')
    is_show = models.BooleanField(default=True, verbose_name='是否上架')
    orders = models.IntegerField(verbose_name='优先级')

    class Meta:
        abstract = True  # 只用来继承,不在数据库中生成表

封装 五个视图子类

common_mixin.py

from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin

from utils.common_response import APIResponse


class APIListModelMixin(ListModelMixin):
    def list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        return APIResponse(results=res.data)

class APICreateModelMixin(CreateModelMixin):
    def create(self, request, *args, **kwargs):
        res = super().create(request, *args, **kwargs)
        return APIResponse(data=res.data)

class APIRetrieveModelMixin(RetrieveModelMixin):
    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(request, *args, **kwargs)
        return APIResponse(data=res.data)

class APIDestroyModelMixin(DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        res = super().destroy(request, *args, **kwargs)
        return APIResponse(data=res.data)

class APIUpdateModelMixin(UpdateModelMixin):
    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        return APIResponse(data=res.data)
posted @ 2024-05-15 19:46  蓝幻ﹺ  阅读(8)  评论(0编辑  收藏  举报