"""
Django settings for mysite project.

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

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

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

import os


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


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'jw4f%am^w47or#dty2d(b*w$+f50n-w4-qy3ok#2*ds00i=d%&'

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

ALLOWED_HOSTS = ["*"]


# Application definition

INSTALLED_APPS = [
    'simpleui',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_python3_ldap',
    'polls.apps.PollsConfig',
    'rest_framework',
    'django_crontab',
    'crispy_forms',
]


REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        # 适用于添加身份验证和权限以后
        'rest_framework.permissions.IsAuthenticated'
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

MIDDLEWARE = [
    # 配置全站redis缓存
    # 'django.middleware.cache.UpdateCacheMiddleware',
    # 'django.middleware.cache.FetchFromCacheMiddleware',

    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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 = 'mysite.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': 'Pass@word',
        'HOST': '127.0.0.1',
        'PORT': '32768',
    }
}


CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://172.20.10.9:9862',
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
             #"PASSWORD": "yoursecret",
        },
    },
}


# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False


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

STATIC_URL = '/static/'


STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static/'),
]

STATIC_ROOT = os.path.join(BASE_DIR, 'polls/static/')

CRONJOBS = [
    ('*/1 * * * *', 'polls.tasks.get_redis_ins_qps'),
    # ('* * * * *', 'polls.tasks.get_redis_ins_qps', '2>&1 >> {0}/redis_qps.log'.format(BASE_DIR)),
]

# 关闭simpleui统计分析上报信息。
SIMPLEUI_ANALYSIS = False

# 离线模式
SIMPLEUI_STATIC_OFFLINE = True

# 关闭simpleui的版本信息展示
SIMPLEUI_HOME_INFO = False

CRISPY_TEMPLATE_PACK = 'bootstrap3'


# LDAP server的URL
LDAP_AUTH_URL = "ldap://127.0.0.1:389"
# 公司内部不使用 TLS 连接
LDAP_AUTH_USE_TLS = False

# LDAP 搜索域，这里请根据实际修改
LDAP_AUTH_SEARCH_BASE = "dc=ihopeit,dc=com"

# 表示用户的LDAP类.
LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson"

# LDAP和django用户表字段的对应关系.
LDAP_AUTH_USER_FIELDS = {
    "username": "cn",
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail",
}

# 用于唯一标识用户的django模型字段的元组
LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",)

LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data"

# LDAP中用户名及密码，这里请根据实际修改
LDAP_AUTH_CONNECTION_USERNAME = "admin"
LDAP_AUTH_CONNECTION_PASSWORD = "admin_passwd_4_ldap"

# LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory"

AUTHENTICATION_BACKENDS = {"django_python3_ldap.auth.LDAPBackend",
                           "django.contrib.auth.backends.ModelBackend", }

# logging的配置
LOGGING = {
    'version': 1,                       # 指明dictConnfig的版本
    'disable_existing_loggers': True,   # 表示是否禁用所有的已经存在的日志配置
    'formatters': {
        # 日志格式器
        'verbose': {  # 详细
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'standard': {  # 标准
            'format': '[%(asctime)s] [%(levelname)s] %(message)s'
        },
    },
    # handlers：用来定义具体处理日志的方式，可以定义多种，"default"就是默认方式，"console"就是打印到控制台方式。file是写入到文件的方式，注意使用的class不同
    'handlers': {
        # 处理器，在这里定义了两个个处理器
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stdout',   # 文件重定向的配置，将打印到控制台的信息都重定向出去
            'formatter': 'standard'         # 制定输出的格式，注意 在上面的formatters配置里面选择一个，否则报错
        },
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': '{0}/repoll.log'.format(BASE_DIR),  # 这是将普通日志写入到日志文件中的方法，
            'formatter': 'standard'
        },
        'monitor': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': '{0}/monitor.log'.format(BASE_DIR),  # 这是将普通日志写入到日志文件中的方法，
            'formatter': 'standard'
        },
        'default': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': '{0}/repoll.log'.format(BASE_DIR),      # 日志输出文件
            'maxBytes': 1024*1024*5,                            # 文件大小
            'backupCount': 5,                                   # 备份份数
            'formatter': 'standard',                            # 使用哪种formatters日志格式
        },
    },
    'loggers': {  # log记录器，配置之后就会对应的输出日志
        'django': {
            'handlers': ['console', 'file'],
            'level': 'INFO',
            'propagate': True,
        },
        'redis.monitor': {
            'handlers': ['monitor'],
            'level': 'INFO',
            'propagate': True,
        },
        'django.request ': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'django.db.backends': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}