"""
Django settings for django_app project.

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

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

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

import os
import sys

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

sys.path.insert(0, BASE_DIR)
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd@r5bqy_0--@mz0*!(^$0^81sp+c*$__)ado&r3$!2t+h(rf%p'

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

ALLOWED_HOSTS = ["*"]

# Application definition

INSTALLED_APPS = [
    'coreschema',  # 解决跨域问题
    'simpleui',  # 更换后台框架
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'apps.users.apps.UsersConfig',
    'apps.users',
    'apps.goods',
    'apps.user_operation',
    'apps.trade',
    'rest_framework',
    'crispy_forms',
    'extra_apps.DjangoUeditor',
    'django_filters',
    'djcelery',

]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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 = 'django_app.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 = 'django_app.wsgi.application'

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

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.mysql',
#         'NAME': '',        #数据库名字
#         'USER': '',          #账号
#         'PASSWORD': '',    #密码
# 
#         'HOST': '45.77.189.214',     #IP
#         'PORT': '3306',          #端口
#         "OPTIONS":{"init_command":"SET default_storage_engine=INNODB;"}
#     }
# }


DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}




# Password validation
# https://docs.djangoproject.com/en/2.0/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/2.0/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/2.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static')
# 重载系统用户
AUTH_USER_MODEL = 'users.UserProfile'

# media保存路径
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

# 跨域问题
CORS_ORIGIN_ALLOW_ALL = True

# Token认证
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    )
}

# 自定义用户认证
AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',

)

import datetime

# 设置JWT有效时间
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
}



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



# 如下配置celery等信息

import djcelery
# 当settings.py中的djcelery.setup_loader()运行时,
# Celery便会查看所有INSTALLED_APPS中app目录中的tasks.py文件, 找到标记为task的function,
# 并将它们注册为celery task.
djcelery.setup_loader()     #加载djcelery

#并没有北京时区，与下面TIME_ZONE应该一致
CELERY_TIMEZONE = 'Asia/Shanghai'
# 消息队列
BROKER_URL = 'redis://45.77.189.214:6379'
# 配置backend
# CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend'

# 设置worker的并发数量为2
CELERY_CONCURRENCY = 2
# 结果存储位置
CELERY_RESULT_BACKEND = 'redis://45.77.189.214:6379'
# 任务序列化和反序列化为json
CELERY_TASK_SERIALIZER = 'json'
# 存储结果序列化为json
CELERY_RESULT_SERIALIZER = 'json'


from celery.schedules import crontab
from celery.schedules import timedelta

CELERYBEAT_SCHEDULE = {    #定时器策略
    #定时任务一：　每隔30s运行一次
    u'测试定时器1': {
        "task": "apps.utils.tasks.add",
        #"schedule": crontab(minute='*/2'),  # or 'schedule':   timedelta(seconds=3),
        "schedule":timedelta(seconds=666),
        "args": (3,8),
    },
}


# CELERY_BEAT_SCHEDULE = {
#     # 'add-every-xx-seconds': {
#     #     'task': 'app_blog.blog.tasks.print_info',
#     #     'schedule': timedelta(seconds=2),  # 每 30 秒一次
#     #     # 'schedule': timedelta(minutes=1),         # 每 1 分钟一次
#     #     # 'schedule': timedelta(hours=4),           # 每 4 小时一次
#     #     'args': ('settings中的定时任务',)  # 任务函数参数，如果只有一个参数，一定要加逗号
#     # },
#     'send_qq_blog_request_count': {
#         'task': 'app_blog.blog.tasks.count_blog_everyday_request',
#         'schedule': crontab(hour=23, minute=30),  # 每天晚上 23 点 30 分执行一次
#     }
# }

#############################
# celery 配置信息 end
#############################