zoukankan      html  css  js  c++  java
  • 异常响应配置

    异常响应配置

    封装项目异常处理

    utils/exception.py

    from rest_framework.views import exception_handler as drf_exception_handler
    from rest_framework.views import Response
    from rest_framework import status
    from utils.logging import logger
    def exception_handler(exc, context):
        response = drf_exception_handler(exc, context)
        # 异常模块就是记录项目的错误日志
        logger.error('%s - %s - %s' % (context['view'], context['request'].method, exc))
        if response is None:
            return Response({
                'detail': '%s' % exc
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
        return response
    

    dev.py配置

    # drf配置
    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'utils.exception.exception_handler',
        #渲染模块的全局配置:开发一般只配置json,为了安全和保密技术
        'DEFAULT_RENDERER_CLASSES':[
            'rest_framework.renderers.JSONRenderer',
        ]
    }
    
    

    二次封装Response模块

    utils/response.py

    from rest_framework.response import Response
    
    class APIResponse(Response):
        def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False, **kwargs):
            data = {
                'status': data_status,
                'msg': data_msg,
            }
            if results is not None:
                data['results'] = results
            data.update(kwargs)
    
            super().__init__(data=data, status=http_status, headers=headers, exception=exception)
    
  • 相关阅读:
    sun.misc.Unsafe的理解
    线程同步工具类
    HashMap源码分析
    【设计模式】GoF设计模式学习总结
    基于ARM处理器的反汇编器软件简单设计及实现
    HashMap内存泄露
    基于Spring cloud Ribbon和Eureka实现客户端负载均衡
    ReentrantLock
    数据库自增主键
    排序
  • 原文地址:https://www.cnblogs.com/chanyuli/p/11966220.html
Copyright © 2011-2022 走看看