text: # -*- coding: utf-8 -*-
  """
  Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
  Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
  Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
  http://opensource.org/licenses/MIT
  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
  """ # noqa
  """
  Django settings for app-framework project.
  
  Generated by 'django-admin startproject' using Django 1.8.3.
  
  For more information on this file, see
  https://docs.djangoproject.com/en/1.8/topics/settings/
  
  For the full list of settings and their values, see
  https://docs.djangoproject.com/en/1.8/ref/settings/
  
  """
  
  import os
  import sys
  # Import global settings to make it easier to extend settings.
  from django.conf.global_settings import *  # noqa
  
  # 加载各个环境的环境变量
  
  # default settings
  LOG_LEVEL = 'DEBUG'
  
  # ==============================================================================
  # Django 项目配置
  # ==============================================================================
  TIME_ZONE = 'Asia/Shanghai'
  USE_TZ = True
  SITE_ID = 1
  
  # 项目路径
  PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
  PROJECT_ROOT, PROJECT_MODULE_NAME = os.path.split(PROJECT_PATH)
  BASE_DIR = os.path.dirname(os.path.dirname(PROJECT_PATH))
  PYTHON_BIN = os.path.dirname(sys.executable)
  
  # ==============================================================================
  # i18n
  # ==============================================================================
  USE_I18N = True
  USE_L10N = True
  # session失效 ->accept-language -> LANGUAGE_CODE
  # 故应设置LANGUAGE_CODE为基础语言(中文)，效果就是基础语言(中文)无需翻译，也就是zh_CN下的po文件可以保留msgstr为空
  # 若基础语言为中文，LANGUAGE_CODE设为英文，当某些中文翻译为空时，会导致django去LANGUAGE_CODE指定的文件中寻找翻译内容
  # 如果LANGUAGE_CODE指定为英文，则会出现中英文同时存在的情况
  LANGUAGE_CODE = 'zh-hans'
  # # 设定使用根目录的locale
  LOCALE_PATHS = (os.path.join(PROJECT_ROOT, 'locale'),)
  
  # 界面可选语言
  _ = lambda s: s
  
  LANGUAGES = (
      ('en', _(u'English')),
      ('zh-hans', _(u'简体中文')),
  )
  
  LANGUAGE_SESSION_KEY = 'blueking_language'
  LANGUAGE_COOKIE_NAME = 'blueking_language'
  
  # ===============================================================================
  # 各版本的配置信息
  # ===============================================================================
  try:
      from project.conf.settings_env import *  # noqa
  except Exception, e:
      print e
      # 手动创建软连接
      os.symlink('./bk_open', './project')
      from project.conf.settings_env import *  # noqa
  
  try:
      import pymysql
  
      pymysql.install_as_MySQLdb()
  except Exception:
      pass
  
  # ===============================================================================
  # 应用基本信息
  # ===============================================================================
  # CSRF的COOKIE域，默认使用当前域
  # CSRF_COOKIE_DOMAIN =''
  CSRF_COOKIE_PATH = SITE_URL
  
  ALLOWED_HOSTS = ['*']
  
  # ==============================================================================
  # Middleware and apps
  # ==============================================================================
  MIDDLEWARE_CLASSES = (
      'django.middleware.common.CommonMiddleware',
      'django.contrib.sessions.middleware.SessionMiddleware',
      'common.middlewares.TimezoneMiddleware',  # 时区切换中间件
      'django.middleware.locale.LocaleMiddleware',
      'django.middleware.csrf.CsrfViewMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.contrib.auth.middleware.AuthenticationMiddleware',
      'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
      'django.contrib.messages.middleware.MessageMiddleware',
      'django.middleware.security.SecurityMiddleware',
      'fta_utils.request_middlewares.RequestProvider',
  ) + MIDDLEWARE_CLASSES_ENV + (
      # 权限控制中间件
      'permission.middlewares.NotAcceptableMiddleware',
      'permission.middlewares.UnauthorizedMiddleware',
      'permission.middlewares.PermissionMiddleware',
      'common.middlewares.ApiExceptionMiddleware',
  )
  
  INSTALLED_APPS = (
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.sites',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'django.contrib.admin',
      'guardian',
  ) + INSTALLED_APPS_ENV + (
      # OTHER 3rd Party App
      'tastypie',
      'fta_solutions_app',
      'permission',
      'home_application',
      'project',
  
      # 审计日志
      'user_activity_log',
  )
  
  # ===============================================================================
  # 静态资源设置
  # ===============================================================================
  # 静态资源文件(js,css等）在应用上线更新后, 由于浏览器有缓存, 可能会造成没更新的情况.
  # 所以在引用静态资源的地方，都需要加上这个版本号，如：<script src="/a.js?v=${STATIC_VERSION}"></script>；
  # 如果静态资源修改了以后，上线前修改这个版本号即可
  STATICFILES_DIRS = (
      os.path.join(PROJECT_ROOT, 'static'),
  )
  STATIC_VERSION = 3.9
  # 应用本地静态资源目录
  STATIC_URL = '%sstatic/' % SITE_URL
  
  ROOT_URLCONF = 'urls'
  # ==============================================================================
  # Templates
  # ==============================================================================
  # mako template dir
  MAKO_TEMPLATE_DIR = os.path.join(PROJECT_ROOT, 'templates')
  MAKO_TEMPLATE_MODULE_DIR = os.path.join(BASE_DIR, 'templates_module', APP_ID)
  if RUN_MODE not in ['DEVELOP']:
      MAKO_TEMPLATE_MODULE_DIR = os.path.join(
          PROJECT_ROOT, 'templates_module', APP_ID)
  # Django TEMPLATES配置
  TEMPLATES = [
      {
          'BACKEND': 'django.template.backends.django.DjangoTemplates',
          'DIRS': [os.path.join(PROJECT_ROOT, 'templates')],
          'APP_DIRS': True,
          'OPTIONS': {
              'context_processors': [
                  # the context to the templates
                  'django.contrib.auth.context_processors.auth',
                  'django.template.context_processors.request',
                  'django.template.context_processors.csrf',
                  'django.template.context_processors.i18n',
                  'common.context_processors.mysetting',  # 自定义模版context，可在页面中使用STATIC_URL等变量
                  # 'bkweb.common.context_processors.mysetting',
              ],
          },
      },
  ]
  # ==============================================================================
  # session and cache
  # ==============================================================================
  # 默认为false,为true时SESSION_COOKIE_AGE无效
  SESSION_EXPIRE_AT_BROWSER_CLOSE = True
  # NOTE 不要改动，否则，可能会改成和其他app的一样，这样会影响登录
  SESSION_COOKIE_PATH = SITE_URL
  
  CACHES = {
      'default': {
          'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
          'LOCATION': 'django_cache',  # NOTE 不要改动，部署脚本会自动createcachetable这个表，写死了
          'OPTIONS': {
              'MAX_ENTRIES': 50000
          }
      },
      'memory': {
          'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
      }
  }
  
  CSRF_COOKIE_NAME = 'fta_csrftoken'
  
  # ===============================================================================
  # FIXTURES (初始数据)
  # ===============================================================================
  # 包含initial_data.json的所有目录列表
  # 如果有初始数据的需要, 请在initial_data.json中根据按格式加入
  # 测试环境：t_fixtures/intial_data.json,正式环境：o_fixtures/intial_data.json
  if RUN_MODE == 'PRODUCT':
      FIXTURE_FILE = os.path.join(
          PROJECT_ROOT, 'fixtures/o_fixtures/initial_data.json')
  else:
      FIXTURE_FILE = os.path.join(
          PROJECT_ROOT, 'fixtures/t_fixtures/initial_data.json')
  
  # ===============================================================================
  # CELERY 配置
  # ===============================================================================
  # 本地开发的 celery 的消息队列（RabbitMQ）信息
  BROKER_URL_DEV = 'amqp://guest:guest@127.0.0.1:5672/'
  # TOCHANGE 调用celery任务的文件路径, List of modules to import when celery starts.
  CELERY_IMPORTS = (
      'fta_solutions_app.backend.schedule',  # 定时任务
  )
  CELERY_IMPORTS += CELERY_IMPORTS_ENV
  
  if IS_USE_CELERY:
      try:
          import djcelery
  
          INSTALLED_APPS += (
              'djcelery',  # djcelery
          )
          djcelery.setup_loader()
          CELERY_ENABLE_UTC = False
          CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
          if "celery" in sys.argv:
              DEBUG = False
          # celery 的消息队列（RabbitMQ）信息
          BROKER_URL = os.environ.get('BK_BROKER_URL', BROKER_URL_DEV)
          if RUN_MODE == 'DEVELOP':
              from celery.signals import worker_process_init
  
              @worker_process_init.connect
              def configure_workers(*args, **kwargs):
                  import django
                  django.setup()
      except Exception:
          pass
  
  # ==============================================================================
  # logging
  # ==============================================================================
  LOGGING_DIR = os.path.join(BASE_DIR, 'logs', APP_ID)
  
  LOG_CLASS = 'logging.handlers.RotatingFileHandler'
  if RUN_MODE in ['TEST', 'PRODUCT']:
      LOGGING_DIR = os.path.join(BK_LOG_DIR, APP_ID)
  
  # 自动建立日志目录
  if not os.path.exists(LOGGING_DIR):
      try:
          os.makedirs(LOGGING_DIR)
      except Exception:
          pass
  
  LOGGING = {
      'version': 1,
      'disable_existing_loggers': False,
      'formatters': {
          'verbose': {
              'format': '%(levelname)s [%(asctime)s] %(pathname)s %(lineno)d %(funcName)s %(process)d %(thread)d \n \t '
                        '%(message)s \n',
              'datefmt': '%Y-%m-%d %H:%M:%S'
          },
          'simple': {
              'format': '%(levelname)s %(message)s \n'
          },
      },
      'handlers': {
          'null': {
              'level': 'DEBUG',
              'class': 'django.utils.log.NullHandler',
          },
          'mail_admins': {
              'level': 'ERROR',
              'class': 'django.utils.log.AdminEmailHandler'
          },
          'console': {
              'level': 'DEBUG',
              'class': 'logging.StreamHandler',
              'formatter': 'simple'
          },
          'default': {
              'class': LOG_CLASS,
              'formatter': 'verbose',
              'filename': os.path.join(LOGGING_DIR, '%s.log' % APP_ID),
              'maxBytes': 1024 * 1024 * 10,
              'backupCount': 5
          },
          'component': {
              'class': LOG_CLASS,
              'formatter': 'verbose',
              'filename': os.path.join(LOGGING_DIR, 'component.log'),
              'maxBytes': 1024 * 1024 * 10,
              'backupCount': 5
          },
          'wb_mysql': {
              'class': LOG_CLASS,
              'formatter': 'verbose',
              'filename': os.path.join(LOGGING_DIR, 'wb_mysql.log'),
              'maxBytes': 1024 * 1024 * 4,
              'backupCount': 5
          },
      },
      'loggers': {
          'django': {
              'handlers': ['default'],
              'level': 'ERROR',
              'propagate': True,
          },
          'django.request': {
              'handlers': ['console'],
              'level': 'ERROR',
              'propagate': True,
          },
          # the root logger ,用于整个project的logger
          'root': {
              'handlers': ['default', 'console'],
              'level': LOG_LEVEL,
              'propagate': True,
          },
          'fta_solutions_app': {
              'handlers': ['default', 'console'],
              'level': LOG_LEVEL,
              'propagate': True,
          },
          # 组件调用日志
          'component': {
              'handlers': ['component'],
              'level': 'ERROR',
              'propagate': True,
          },
          # other loggers...
          'django.db.backends': {
              'handlers': ['wb_mysql'],
              'level': 'ERROR',
              'propagate': True,
          },
      }
  }
  