Django 配置信息


配置是django 的灵魂伴侣

在DJANGO 中配置信息会很重要 因为官方工具以及插件的使用基本哦都是通过配置项导入的

其中比较重要的信息 如 秘钥 根目录 数据库 这些django 都是开箱即配好的

主要是要注意自己的应用和第三方应用的注册 以及一些配置的修改

DRF 的配置项同样写在 Django 默认的sttings 里面 而DRF 中简单的业务逻辑已经自动化实现了,整个代码实现更像是在配置文件那配置项就更加重要了

-------settings 中加入REST_FRAMEWORK ----------------
# 项目名称
PROJECT_NAME 
# 项目根目录位置 这个很重要很多项目启动问题都和这个有关,一般默认这样写
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 密钥 一般是系统自动生成的
SECRET_KEY 

# bool 值 代表调试或者开发模式 开启模式下会自动更新代码重启服务 线上环境关闭
DEBUG = True

# 代表 允许访问的ip * 代表任何
ALLOWED_HOSTS = ["*"]

# 本机ip
HOST ='http://127.0.0.1'

# redis 配置信息
REDIS_HOST
REDIS_PORT
# 已安装应用 应用注册中学 包括内置的一些应用 自己创建的应用 和第三方应用 如DRF 等
INSTALLED_APPS = [
.......
     'user',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    .....

]
# 中间键注册 中间键会在在请求前后自动做一些处理 DJANGO 自带一些也可以自己写一些创建进去
MIDDLEWARE

# 根路由位置 一般默认在这
ROOT_URLCONF = 'prjectname.urls'

# 一些模板信息, 前后端分离的话用不上
TEMPLATES =  [
    {   # 模板后端
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 目录
        'DIRS': [],
        'APP_DIRS': True,
        # 其他配置项
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
# wsgi 应用位置  Django 是基于 wsgi 协议的这个也很重要
WSGI_APPLICATION = 'projectname.wsgi.application'

# 数据库配置信息这个相当重要
DATABASES = {
    # 默认数据库不指定情况下就自动用它
    'default': {
        'ENGINE':'django.db.backends.sqlite3', # Django 自带一个sqlite3数据库也可以配置其他的
        'NAME': os.path.join(BASE_DIR, 'dft.sqlite3'), # 库名
        # 用户密码ip 端口
        'USER': 'username', 
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': 3306,
        # 一些其他信息 如字符集数据库引擎等
        'OPTIONS': {'charset': 'utf8mb4'},
    },
    # 其他数据库名字可以随便起 信息同上
    'other': {
        ....
        ....
    }
}

# app数据库指定 appname: DATABASES-key 不指定默认 default
DATABASE_APPS_MAPPING = {
    'store': "other"
}

# 缓存
CACHES = {
    # 这就和DATABASES 很像了
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION':'redis://host:port/'),
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        },
        'KEY_PREFIX': PROJECT_NAME.replace('_', '-'),
        'VERSION': default='1',
        'TIMEOUT':300
    },
}
# 这里的都属于全局配置也可以对类对象 或类方法 针对性配置
# 配置优先级 为 类方法>类对象>全局配置
REST_FRAMEWORK = {
    # DRF 认证配置
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'vivoapi.authentication.CustomSessionAuthentication',
        'vivoapi.authentication.CustomTokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ],
    # DRF 渲染器配置
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',  # 开发模式
    ],
    # 'EXCEPTION_HANDLER': 'backend.util.exceptions.custom_exception_handler',

     # DRF 第三方组件配置
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',  # coreapi

}
# 时区和语言配置 这个一般默认是国外的要改
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
LANGUAGES = (
    ('zh-hans', '简体中文'),
    ('en-us', 'English'),
)

# 日志信息配置
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'default': {
            '()': 'colorlog.ColoredFormatter',
            'format': '%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(asctime)s %(bold_white)s%(name)s %(green)s%(message)s',
            'log_colors': {
                'DEBUG': 'bold_cyan',
                'INFO': 'bold_green',
                'WARNING': 'bold_yellow,bg_red',
                'ERROR': 'bold_red',
                'CRITICAL': 'bold_red,bg_yellow',
            },
            'datefmt': '%Y-%m-%d %H:%M:%S',
            'style': '%',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'default',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'WARNING',
        },
        'django.request': {
            'handlers': ['console'],
            'level': 'ERROR',
            'propagate': False,
        },
        'django.server': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'django.db.backends': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'django.template': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': True,
        },
        'celery': {
            'handlers': ['console'],
            'level': 'INFO',
        },

        'user': {
            'handlers': ['console'],
            'level': 'INFO'
        },

    }
}

# DRF 扩展框架配置信息
REST_FRAMEWORK = {
    # 时间日期格式
    'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S",
    # 时间格式
    'TIME_FORMAT': "%H:%M:%S",
    # 默认过滤器后端
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
        'rest_framework.filters.SearchFilter',
        'rest_framework.filters.OrderingFilter',
    ),
    # 未授权的用户
    'UNAUTHENTICATED_USER': None,
    # 默认请求解析器
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.MultiPartParser',
        'rest_framework.parsers.FileUploadParser',
    ),
    # 默认授权校验器
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'ai_site_server.authentication.CustomSessionAuthentication',
        'ai_site_server.authentication.CustomTokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    # 数据渲染器
    'DEFAULT_RENDERER_CLASSES': (
        'ai_site_server.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    # 默认节流器
    'DEFAULT_THROTTLE_RATES': {
        'custom_anon': '5/minute'
    },
    # 默认分页器
    'DEFAULT_PAGINATION_CLASS': 'ai_site_server.pagination.CustomizationPagination',
    # 每页尺寸
    'PAGE_SIZE': 10,
    # 代理信息
    'NUM_PROXIES': 1)
}

# SSO configure
AUTH_USER_MODEL = 'user.User'
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
]

# celery
CELERY_BROKER_URL = 'redis://{host}:{port}/0'

# sms config
SMS_CONFIG = {
    'SMS_GATEWAY': ,
    'TARGET': ,
    'KEY': ,
    'IP': "127.0.0.1"
}

# aes 
AES_CBC_CONFIG = {
    'KEY': "KEY",
    'IV': "IV"
}