zoukankan      html  css  js  c++  java
  • 基本配置(日志、异常处理、数据库)

    日志配置

    dev.py

    # 日志文件配置
    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", "renran.log"),
                # 日志文件的最大值,这里我们设置300M
                'maxBytes': 300 * 1024 * 1024,
                # 日志文件的数量,设置最大日志数量为10
                'backupCount': 100,
                # 日志格式:详细格式
                'formatter': 'verbose',
                # 文件内容编码
                'encoding': 'utf-8'
            },
        },
        # 日志对象
        'loggers': {
            'django': {    # 固定必须叫django,将来django内部也会有异常的处理,只会调用django下标的日志对象
                'handlers': ['console', 'file'],
                'propagate': True,  # 是否让日志信息继续冒泡给其他的日志处理系统
            },
        }
    }

    renranapi/renranapi/utils/logger.py

    from logging import getLogger
    from logging import config
    from renranapi.settings import dev
    
    config.dictConfig(dev.LOGGING)
    log = getLogger("django")

    renranapi/renranapi/utils/apiresponse.py

    from rest_framework.response import Response
    
    
    class APIResponse(Response):
        def __init__(self, status=100, msg='success', headers=None, exception=False, content_type=None,
                     **kwargs):
            data = {
                'status': status,
                'msg': msg
            }
            # 在外界数据可以用result和results来存储
            if kwargs:
                data.update(kwargs)
            super().__init__(data=data, headers=headers, exception=exception, content_type=content_type)

    异常处理

    renranapi/renranapi/utils/exceptions.py

    # 异常处理
    from rest_framework.views import exception_handler
    from django.db import DatabaseError
    from .apiresponse import APIResponse
    from .logger import log
    
    
    def custom_exception_handler(exc, context):
        response = exception_handler(exc, context)  # 调用一下原有方法,在原有基础上加处理
        # 两种情况,一个是None,drf没有处理
        # response是Response对象,django处理了,但是处理的不符合咱们的要求
        # print(type(exc))
    
        # 记录错误日志
        if response is None:
            view = context["view"]
            """当response的值为None,则有可能出现2种情况: 没有发生异常,或者本次异常没有被drf进行处理"""
            if isinstance(exc, DatabaseError):
                # 数据库异常
                log.error("数据库发生异常。view=%s,exc=%s" % (view, str(exc)))
                response = APIResponse(msg='服务器内部错误', status=507)
    
            if isinstance(exc, Exception):
                # 未知异常
                log.error("发生未知异常。view=%s,exc=%s" % (view, str(exc)))
                response = APIResponse(msg='服务器出现未知错误', status=500)
    
        return response

    创建数据库

    # mysql -uroot -p123
    # create database renran default charset=utf8mb4;

    为当前项目创建数据库用户[这个用户只能看到这个数据库

    # grant all privileges on renran.* to 'renran_user'@'%' identified by 'renran';
    # grant all privileges on renran.* to 'renran_user'@'localhost' identified by 'renran';
    # flush privileges;

    配置数据库连接

     dev.py

    # 连接Mysql数据库
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.mysql",
            "HOST": "127.0.0.1",
            "PORT": 3306,
            "USER": "renran_user",  # 登录账号
            "PASSWORD": "renran",  # 登录密码
            "NAME": "renran",  # 数据库名
        }
    }
    
    import pymysql
    pymysql.install_as_MySQLdb()

    调整错误

    数据库版本检测导致的错误

    数据库的版本检测代码注释掉。

    因为python3版本的原因,字符串的编码问题

    把146的代码从下面改动
    query = query.decode(errors='replace')
    改成:
    query = query.encode(errors='replace')
  • 相关阅读:
    1.27
    1.25
    Representation Learning with Contrastive Predictive Coding
    Learning a Similarity Metric Discriminatively, with Application to Face Verification
    噪声对比估计(负样本采样)
    Certified Adversarial Robustness via Randomized Smoothing
    Certified Robustness to Adversarial Examples with Differential Privacy
    Dynamic Routing Between Capsules
    Defending Adversarial Attacks by Correcting logits
    Visualizing Data using t-SNE
  • 原文地址:https://www.cnblogs.com/baicai37/p/13581943.html
Copyright © 2011-2022 走看看