"""
Django settings for cms project.

Generated by 'django-admin startproject' using Django 2.2.24.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

"""
BASE_DIR       修改
LOG_DIR        新增
DATABASES      注释
TIME_ZONE      修改
USER_TZ        修改
LOGGING        新增
CORS_          CORS配置
"""

import os
from itertools import chain

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir))))

LOG_DIR = os.path.join(BASE_DIR, "logs")

if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '4&$tm1%z3cwf)b588*5fp=@*54oh5f(r7kv71vomsf60y*%fgg'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',  # 跨域'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # 跨域
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'cms.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_APPLICATION = 'cms.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

# USE_TZ = True
USE_TZ = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'


LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'loggers': {
        '': {
            'level': 'INFO',
            'handlers': ['console', 'info_file', 'error_file'],
            'propagate': False
        },
        'django': {
            'level': 'INFO',
            'handlers': ['console', 'info_file', 'error_file'],
            'propagate': False
        },
    },
    'formatters': {
        'default': {
            'format': '[%(asctime)s.%(msecs).3d] - [%(levelname)s] - [%(name)s:%(lineno)d] - [%(message)s]',
            'datefmt': '%Y-%m-%d %H:%M:%S',
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': 'INFO',
            'formatter': 'default',
        },
        'info_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_DIR, 'info.log'),
            'maxBytes': 5 * 1024 * 1024,
            'backupCount': 10,
            'encoding': 'utf8',
            'level': 'INFO',
            'formatter': 'default',
        },
        'error_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_DIR, 'error.log'),
            'maxBytes': 5 * 1024 * 1024,
            'backupCount': 10,
            'encoding': 'utf8',
            'level': 'ERROR',
            'formatter': 'default',
        },
    },
}

# 跨域
from corsheaders.defaults import default_methods, default_headers

# Set-Cookie: key=value; SameSite=None; Secure
# 允许COOKIE
CORS_ALLOW_CREDENTIALS = True
# 禁用Cookie SameSite属性
SESSION_COOKIE_SAMESITE = None
# 启用Cookie Secure属性，此时必须是https，chrome浏览器强制要求
SESSION_COOKIE_SECURE = True

CORS_ALLOW_ALL_ORIGINS = True
CORS_ORIGIN_WHITELIST = ()

# 允许的method
CORS_ALLOW_METHODS = tuple(chain(default_methods, (

)))

# 允许的header
CORS_ALLOW_HEADERS = tuple(chain(default_headers, (

)))

# from rest_framework.versioning import URLPathVersioning
# DRF
REST_FRAMEWORK = {
    # 全局认证类
    'DEFAULT_AUTHENTICATION_CLASSES': [],
    # 默认版本类
    'DEFAULT_VERSIONING_CLASS': 'core.drf.version.URLPathVersioning',
    # 默认版本
    'DEFAULT_VERSION': 'v1',
    # 允许的版本号
    'ALLOWED_VERSIONS': ('v1',),
    # 全局异常处理
    'EXCEPTION_HANDLER': 'core.drf.exception_handlers.handler',
    # 更改默认 request.user = None 原本为 'AnonymousUser'
    'UNAUTHENTICATED_USER': None,
    # 更改默认 request.auth = None
    'UNAUTHENTICATED_TOKEN': None,
}
