• 重构drf后的环境变量配置


    环境变量

    dev.py
    # 环境变量操作:小luffyapiBASE_DIR与apps文件夹都要添加到环境变量
    import sys
    sys.path.insert(0, BASE_DIR)
    APPS_DIR = os.path.join(BASE_DIR, 'apps')
    sys.path.insert(1, APPS_DIR)
    
    在写项目直接导入utils文件夹,如何使它不''错误提示'' 比如import utils会出现下划线
    (注意: 只有添加了环境变量的文件夹设置)

    配置media

    media配置:dev.py
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    
    media目录配置
        ├── luffyapi
            └──	luffyapi/
               	└──	media/  	
        			└──	icon 
        				└── default.png
    

    封装logger

    dev.py
    # 真实项目上线后,日志文件打印级别不能过低,因为一次日志记录就是一次文件io操作
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'verbose': {
                'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
            },
            'simple': {
                'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
            },
        },
        'filters': {
            'require_debug_true': {
                '()': 'django.utils.log.RequireDebugTrue',
            },
        },
        'handlers': {
            'console': {
                # 实际开发建议使用WARNING
                'level': 'DEBUG',
                'filters': ['require_debug_true'],
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
            'file': {
                # 实际开发建议使用ERROR
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                # 日志位置,日志文件名,日志保存目录必须手动创建,注:这里的文件路径要注意BASE_DIR代表的是小luffyapi
                'filename': os.path.join(os.path.dirname(BASE_DIR), "logs", "luffy.log"),
                # 日志文件的最大值,这里我们设置300M
                'maxBytes': 300 * 1024 * 1024,
                # 日志文件的数量,设置最大日志数量为10
                'backupCount': 10,
                # 日志格式:详细格式
                'formatter': 'verbose',
                # 文件内容编码
                'encoding': 'utf-8'
            },
        },
        # 日志对象
        'loggers': {
            'django': {
                'handlers': ['console', 'file'],
                'propagate': True, # 是否让日志信息继续冒泡给其他的日志处理系统
            },
        }
    }
    
    utils/logging.py
    import logging
    logger = logging.getLogger('django')
    

    封装项目异常处理

    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
    
    settings/dev.py
    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'utils.exception.exception_handler',
    }
    

    二次封装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)
    
  • 相关阅读:
    TriSun PDF to X v11.0 Build 061
    资源管理器 Q-Dir v8.09
    USB启动盘创建工具 Rufus
    Docker:网络模式详解
    rsync使用实践
    MySQL 8.0 防止暴力破解
    MySQL-8.0.19 优化日志及压测
    MySQL入门篇之mysqldump参数说明
    rest-framework之视图
    rest-framework之权限组件
  • 原文地址:https://www.cnblogs.com/demiao/p/11985511.html
Copyright © 2020-2023  润新知