# -*- coding: utf-8 -*-

"""
Django settings for DjangoTaskForSpark 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, ...)
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Use apps
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))

# 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 = 'vf2y_*p0z=l$kt##d=qyb@pjo7^b#v2xpi89)3u)%t!136_0&)'

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

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_celery_beat',
    'django_celery_results',
    'apps.taskmanager.apps.TaskmanagerConfig'
]

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

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

# Database
# https://docs.djangoproject.com/en/1.11/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/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 = '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/'

# celery setting config
CELERY_RABBIT_HOSTNAME = os.environ.get('AMQ_PORT_5672_TCP_PORT', 'rabbitmq')

if CELERY_RABBIT_HOSTNAME.startswith('tcp://'):
    CELERY_RABBIT_HOSTNAME = CELERY_RABBIT_HOSTNAME.split('//')[1]

# 设置消息中间人 - RabbitMQ
CELERY_BROKER_URL = 'amqp://{user}:{password}@{hostname}/{vhost}/'.format(
    user=os.environ.get('RABBIT_ENV_USER', 'guest'),
    password=os.environ.get('RABBIT_ENV_RABBITMQ_PASS', 'guest'),
    hostname='10.57.98.251:5674',
    vhost=os.environ.get('RABBIT_ENV_VHOST', ''))

# 设置消息中间人 - Redis
# CELERY_BROKER_URL = 'redis://redis:6379'

# 存储任务运行结果的数据库，一般不使用RabbitMQ，可以使用redis或者Django的数据库
# CELERY_RESULT_BACKEND = 'django-db'
# CELERY_RESULT_BACKEND = 'redis://username:password@redis:6379/0'
CELERY_RESULT_BACKEND = 'redis://10.57.98.251:6384/0'
# 由于使用redis作为任务的运行结果存储，所以设置结果的过期时间，过期自动清除
CELERY_TASK_RESULT_EXPIRES = 18000  # 5 hours.

# # 列出导入模块
# CELERY_IMPORTS=('myapp.tasks',)
# app.conf.CELERY_TASK_SERIALIZER = 'json'

# CELERY_IGNORE_RESULT = True
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']

CELERYD_TASK_SOFT_TIME_LIMIT = 300  # # Add a one-minute timeout to all Celery tasks.
CELERYD_MAX_TASKS_PER_CHILD = 200  # 每个任务执行多少任务后死掉，防止内存泄漏
CELERY_TIMEZONE = 'Asia/Shanghai'  # 定时任务需要
CELERY_ENABLE_UTC = False

# celery  beat
DJANGO_CELERY_BEAT_TZ_AWARE = False
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'

# 设置路由
# CELERY_ROUTES = {
#       'tasks.add': 'low-priority',
# }

# 限制任务的速率，这样每分钟只允许处理 10 个该类型的任务
# CELERY_ANNOTATIONS = {
#     'tasks.add': {
#         'rate_limit': '10/m'
#     }
# }

# CELERY_ANNOTATIONS={'*':{'rate_limit':'10/s'}}   #限制所有任务处理
# 如果你使用 RabbitMQ 或 Redis 作为中间人，那么你也可以在运行时直接在职程上设置速率限制：
# $ celery control rate_limit tasks.add 10/mworker@example.com: OK new rate limit set successfully

# [并发设置]
# CELERYD_CONCURRENCY = 8   # 默认是你的cpu可用数量

