# coding=utf-8
"""
Django settings for CaliperServer project.

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

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
import sys

reload(sys)
sys.setdefaultencoding('utf8')

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 日志文件路径
logPath = os.path.join(BASE_DIR, 'log')
print logPath
if not os.path.exists(logPath):
    os.mkdir(logPath)

# caliper 下载路径
parentPath = os.path.abspath(os.path.join(BASE_DIR, os.pardir))
downloadPath = os.path.join(parentPath, 'data', 'download')
if not os.path.exists(downloadPath):
    os.makedirs(downloadPath)
print downloadPath
# caliper 上传路径
uploadPath = os.path.join(parentPath, 'data', 'upload')
if not os.path.exists(uploadPath):
    os.makedirs(uploadPath)
print uploadPath

# 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 = 'x6=vjz#1)p9^$dxl(8_hw5xy&8#2dv=^q(^n!89xh8509@65!d'

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

ALLOWED_HOSTS = ['*']

# Application definition
AUTH_USER_MODEL = "account.UserProfile"

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'shared',
    'account',
    'task',
    'data',
]

MIDDLEWARE = [
    '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',
    'shared.ExceptionHandler.ExceptionMiddleware',
]

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

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'caliper',
        'USER': 'root',
        'PASSWORD': 'root',
        # 'HOST': 'localhost',
        'HOST': '192.168.64.97',
        'PORT': '3306',
        'OPTIONS': {
            'init_command': 'SET sql_mode=STRICT_TRANS_TABLES',
        },
    }
}

# 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 = 'en-us'

#TIME_ZONE = 'UTC'
# 东八区
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

# 不转换成UTCBASE_DIR
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"),
)

MEDIA_URL = '/upload/'
# MEDIA_ROOT = os.path.join(BASE_DIR, "static"),
MEDIA_ROOT = os.path.join(parentPath,"data","upload")
print "============="
print MEDIA_ROOT

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },  # 针对 DEBUG = True 的情况
    },
    'formatters': {
        'standard': {
            # 'format': '%(levelname)s %(asctime)s %(pathname)s %(filename)s %(module)s %(funcName)s %(lineno)d: %(message)s'
            'format': '%(levelname)s %(asctime)s %(filename)s  methodName：%(funcName)s %(lineno)d: %(message)s'
        },  # 对日志信息进行格式化，每个字段对应了日志格式中的一个字段，更多字段参考官网文档，我认为这些字段比较合适，输出类似于下面的内容
        # INFO 2016-09-03 16:25:20,067 /home/ubuntu/mysite/views.py views.py views get 29: some info...
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'formatter': 'standard'
        },
        'file_handler': {
            'level': 'DEBUG',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'log/sys.log'),
            'formatter': 'standard'
        },  # 用于文件输出
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'standard'
        },
    },

    'loggers': {
        # 'django': {
        #     'handlers': ['console'],
        #     'level': 'DEBUG',
        #     'propagate': False  # 是否继承父类的log信息(是否显示这一层以上的所有日志）
        # },  # 'django' 是django系统默认的日志输出tag(这边默认不显示系统日志,所以把名字改掉，或者把‘file_handler’去掉)
        #  handlers 来自于上面的 handlers 定义的内容
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        },
        'custom': {
            'handlers': ['file_handler', 'console'],
            'level': 'DEBUG',
            'propagate': True
        }
    }
}

# sso相关 begin
SSO_API_AUTH_SETTING = {
    "apikey": "ff205290",
    "seckey": "ceb59112354f4599bd2af9b4bf5ab70a",
    # "url": "http://106.12.27.16:9000",
    "url": "http://ssoserver.com:7000",
}

AUTHENTICATION_BACKENDS = ("account.sso.authbackend.SSOAuthBackend",)

LOGIN_REDIRECT_URL = "/task/list"
USER_REDIRECT_URL = '/user/userinfo/'
# sso相关 end
