# 开发时使用的配置文件
"""
Django settings for meiduo_mail project.

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

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,sys
# os.path拼接路径　sys.path查询导包路径　是一个列表
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# print(sys.path)  # 我这里是没有那些导包路径的　至于为什么还不知道
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# print('hahaha')
# print(BASE_DIR) # 这个是正确的
# print(PROJECT_DIR) # 这个是正确的
#追加系统的导包路径（两个目的１．注册子应用时写的更方便点２．修改django认证模型类时，必须以应用名．模型名）
# sys.path.insert(0,  BASE_DIR)
sys.path.append(BASE_DIR)
sys.path.append(PROJECT_DIR)
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
# print(sys.path)
"""
['/home/frank/Desktop/pycharm/projects/meiduo2/meiduo_mail/meiduo_mail/apps', '/home/frank/Desktop/pycharm/projects/meiduo2/meiduo_mail/meiduo_mail/settings', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/frank/.virtualenvs/meiduo/lib/python3.6/site-packages']
"""

# 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 = 'g%35e@@ggx8df)(apguskcn#w$b%jwxg#p_k5spe%pjc$&=ek8'

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

# 允许哪些域名访问django
ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'www.meiduo.site', 'api.meiduo.site']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',  #  drf　　第三方的应用写在中间并用空行隔起来
    'corsheaders',  # 解决跨域问题
    'ckeditor',  # 富文本编辑器
    'ckeditor_uploader',  # 富文本编辑器上传图片模块
    'django_crontab',  # 定时任务

    'users.apps.UsersConfig',  # 用户模块　自己的应用写在最下面
    'oauth.apps.OauthConfig',  # QQ模块　发短信应用没有模型什么的就不用注册
    'areas.apps.AreasConfig',  #省市区模块
    'goods.apps.GoodsConfig',  #商品模块
    'contents.apps.ContentsConfig',#广告模块
]

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        # 'NAME': BASE_DIR / 'db.sqlite3',
        'NAME':'meiduo',
        'USER':'zhangsan',
        'PASSWORD':'123456',
        'HOST':'localhost',
        'PORT':3306,
    }
}


# 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'
LANGUAGE_CODE = 'zh-hans'

# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

#配置redis数据库作为缓存后端
CACHES = {
    "default": {  # 缓存省市区数据
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "session": {  # 缓存session
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "verify_codes": {  # 存储验证码
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/2",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    "history": {  # 存储商品浏览记录
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/3",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "session"
# 日志输出器
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,  # 是否禁用已经存在的日志器
    'formatters': {  # 日志信息显示的格式
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
        },
    },
    'filters': {  # 对日志进行过滤
        'require_debug_true': {  # django在debug模式下才输出日志
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {  # 日志处理方法
        'console': {  # 向终端中输出日志
            'level': 'INFO',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {  # 向文件中输出日志
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(os.path.dirname(BASE_DIR), "logs/meiduo.log"),  # 日志文件的位置
            'maxBytes': 300 * 1024 * 1024,
            'backupCount': 10,
            'formatter': 'verbose'
        },
    },
    'loggers': {  # 日志器
        'django': {  # 定义了一个名为django的日志器
            'handlers': ['console', 'file'],  # 可以同时向终端与文件中输出日志
            'propagate': True,  # 是否继续传递日志信息
            'level': 'INFO',  # 日志器接收的最低日志级别
        },
    }
}

#DRF配置
REST_FRAMEWORK = {
    # 异常处理
    'EXCEPTION_HANDLER': 'utils.exceptions.exception_handler',  # 问题出在这里？？？我的路径是直接到内层的meiduo_mail
    # 认证
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',  # JWT认证类　放在第一位是默认项　前端传了token就走这里的校验逻辑
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    # 分页
    'DEFAULT_PAGINATION_CLASS': 'meiduo_mail.utils.pagination.StandardResultsSetPagination',
}

#修改django认证系统的用户模型类
AUTH_USER_MODEL =  'users.User'  #  应用.模型名 users.models.user自动加了models

# CORS
CORS_ORIGIN_WHITELIST = (
    '127.0.0.1:8080',
    'localhost:8080',
    'www.meiduo.site:8080',
    'api.meiduo.site:8000'  # 后端的也要加上
)
CORS_ALLOW_CREDENTIALS = True  # 允许跨域时携带cookie

#JWT的有效期
import datetime
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
    # 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=60),
    # 修改构造JWT视图响应数据的函数位置
    'JWT_RESPONSE_PAYLOAD_HANDLER':'users.utils.jwt_response_payload_handler',
}

# 修改django后端用户认证类
# AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']　默认的
AUTHENTICATION_BACKENDS = ['users.utils.UsernameMobileAuthBackend']

# QQ登录参数
QQ_CLIENT_ID = '101474184'  # appid
QQ_CLIENT_SECRET = 'c6ce949e04e12ecc909ae6a8b09b637c'  # appkey
QQ_REDIRECT_URI = 'http://www.meiduo.site:8080/oauth_callback.html'  # 回调域名

# 以下是邮件配置
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'  # 默认配置的也是这个
EMAIL_HOST = 'smtp.163.com'
# EMAIL_PORT = 25　默认配置的也是这个
#发送邮件的邮箱
EMAIL_HOST_USER = '18288650698@163.com'
#在邮箱中设置的客户端授权密码
EMAIL_HOST_PASSWORD = 'QNBVBXLJCBFGQPTV'
#收件人看到的发件人
EMAIL_FROM = 'joey<18288650698@163.com>'

# DRF扩展　配置省市区数据缓存　一个小时内同一个数据只会查一次　过了一小时缓存就会清理掉数据
REST_FRAMEWORK_EXTENSIONS = {
    # 缓存时间
    'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 60,
    # 缓存存储
    'DEFAULT_USE_CACHE': 'default',
}


# django文件存储
DEFAULT_FILE_STORAGE = 'meiduo_mail.utils.fastdfs.fdfs_storage.FastDFSStorage'



# FastDFS
# FDFS_URL = 'http://image.meiduo.site:8888/'  
# FDFS_URL = 'http://192.168.0.103:8888/'  
# FDFS_BASE_URL = 'http://192.168.0.103:8888/'  
FDFS_BASE_URL = 'http://image.meiduo.site:8888/' 
FDFS_CLIENT_CONF = os.path.join(BASE_DIR, 'utils/fastdfs/client.conf')

# 富文本编辑器ckeditor配置
CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'full',  # 工具条功能
        'height': 300,  # 编辑器高度
        # 'width': 300,  # 编辑器宽
    },
}
CKEDITOR_UPLOAD_PATH = ''  # 上传图片保存路径，使用了FastDFS，所以此处设为''

# 生成的静态html文件保存目录
GENERATED_STATIC_HTML_FILES_DIR = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), 'front_end_pc')
# 解决crontab中文问题
CRONTAB_COMMAND_PREFIX = 'LANG_ALL=zh_cn.UTF-8'
# 定时任务
CRONJOBS = [
    # 每5分钟执行一次生成主页静态文件
    # ('*/5 * * * *', 'contents.crons.generate_static_index_html', '>> /Users/delron/Desktop/meiduo_mall/logs/crontab.log')
    ('*/1 * * * *', 'contents.crons.generate_static_index_html', '>> /home/frank/Desktop/pycharm/projects/meiduo2/meiduo_mail/logs/crontab.log')
]