import os
from Ansjer.config import BASE_DIR


SECRET_KEY = 'c7ki2_gkg4#sjfm-u1%$s#&n#szf01f*v69rwv2qsf#-zmm@tl'
DEBUG = True
# DEBUG = False
ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'imagekit',
    'Model',
    'PushModel',
    'SerialModel',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'Service.middleware.StatisticsUrlMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django_global_request.middleware.GlobalRequestMiddleware',
]

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',  # django default backend
    'guardian.backends.ObjectPermissionBackend',
)

ADDR_URL = []
ANONYMOUS_USER_ID = -1  # 支持匿名用户

STATIC_URL = '/static/'

# 上传路径根目录
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/Upgrate')
# 在浏览器上访问该上传文件的url的前缀
MEDIA_URL = '/static/Upgrate/'
ROOT_URLCONF = 'Ansjer.urls'
LOGIN_URL = '/account/login'
AUTH_USER_MODEL = 'Model.Device_User'  # 自定义Model
APPEND_SLASH = False

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 'DIRS': [BASE_DIR + '/static/templates', ],
        'DIRS': [BASE_DIR + '/templates', ],
        '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 = 'Ansjer.test_wsgi.application'


# 服务器类型
#业务数据库
DATABASE_DATA = 'AnsjerTest'
SERVER_HOST = 'database-2.clraczw4p0yj.us-west-1.rds.amazonaws.com'
DATABASES_USER = 'azrds'
DATABASES_PASS = 'azrds.x.x'

#推送数据库
DATABASE_DATA2 = 'AnsjerTest'
SERVER_HOST2 = 'ansjerpush.clraczw4p0yj.us-west-1.rds.amazonaws.com'
DATABASES_USER2 = 'azrds'
DATABASES_PASS2 = 'azrds.x.x'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DATABASE_DATA,
        'USER': DATABASES_USER,
        'PASSWORD': DATABASES_PASS,
        'HOST': SERVER_HOST,
        'PORT': '3306',
        'OPTIONS': {'charset': 'utf8mb4', 'use_unicode': True, 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"},
        'AUTOCOMMIT': True
    },
    'mysql02': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DATABASE_DATA2,
        'USER': DATABASES_USER2,
        'PASSWORD': DATABASES_PASS2,
        'HOST': SERVER_HOST2,
        'PORT': '3306',
        'OPTIONS': {'charset': 'utf8mb4', 'use_unicode': True, 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"},
        'AUTOCOMMIT': True
    },
}

DATABASE_ROUTERS = ['Ansjer.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
    'Model': 'default',
    'db2': 'mysql02',
}

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',
    },
]

LANGUAGE_CODE = 'en-us'
# TIME_ZONE = 'Asia/Shanghai'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# 跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
# CORS_ORIGIN_WHITELIST = ('*')

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)

#########################################
'''
增加错误信息推送到管理员邮箱
'''
# 管理员邮箱
ADMINS = (
    ('admin', 'sonalh@foxmail.com'),
)

# 非空链接，却发生404错误，发送通知MANAGERS
SEND_BROKEN_LINK_EMAILS = True
MANAGERS = ADMINS

# Email设置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com'  # QQ邮箱SMTP服务器(邮箱需要开通SMTP服务)
EMAIL_PORT = 25  # QQ邮箱SMTP服务端口
EMAIL_HOST_USER = 'chanjunkai@163.com'  # 我的邮箱帐号
EMAIL_HOST_PASSWORD = 'cjk1234'  # 授权码
EMAIL_SUBJECT_PREFIX = 'website'  # 为邮件标题的前缀,默认是'[django]'
EMAIL_USE_TLS = True  # 开启安全链接
DEFAULT_FROM_EMAIL = SERVER_EMAIL = EMAIL_HOST_USER  # 设置发件人

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'error_format': {
            # 'format': '{"asctime":"%(asctime)s","thread":"%(threadName)s:%(thread)d","errorline":"%(lineno)d","errorlevel":"%(levelname)s","errorcontent":"%(message)s"}'
            'format': '%(asctime)s %(threadName)s %(thread)d %(lineno)d %(levelname)s %(message)s'
        },
        'standard': {
            'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] '
                      '[%(levelname)s]- %(message)s'},

    },
    'filters': {
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True,
        },
        'default': {
            'level': 'ERROR',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': BASE_DIR + '/static/log/error/error.log',
            'backupCount': 30,
            'when': 'D',
            'formatter': 'error_format',
        },
        'console': {
            'level': 'ERROR',
            'class': 'logging.StreamHandler',
            'formatter': 'error_format'
        },
        'info': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': BASE_DIR + '/static/log/info/info.log',
            'backupCount': 30,
            'when': 'D',
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['default', 'console'],
            # 'handlers': ['mail_admins','default','console'],
            # 'level': 'ERROR',
            'level': 'ERROR',
            'propagate': False
        },
        # log 调用时需要当作参数传入
        'info': {
            'handlers': ['info'],
            'level':'INFO',
            'propagate': False
        }
        # 'django.db.backends': {
        #     'handlers': ['console'],
        #     'propagate': True,
        #     'level': 'DEBUG',
        # },
    }
}