Django配置配置文件详解

import datetime
import os

根目录

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

os.path.abspath(file)指的是当前文件的绝对路径,包括文件名。
os.path.dirname(file)指的是当前文件所在目录

密钥

SECRET_KEY = ‘_30c!q15pp ) i 3 f w 6 x a a @ h 1 p x x h n ( + 89 v )i3f^w6x^aa@h1pxxh_n(+89v )i3fw6xaa@h1pxxhn(+89vwb)b9tc%bv0+1’

开启调式模式

DEBUG = True

允许任意ip访问

ALLOWED_HOSTS = [’*’]

配置导包路径

import sys
sys.path.insert(0,os.path.join(BASE_DIR,‘apps’))

Application definition 注册应用

INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
# ‘meiduo_mall.apps.users.apps.UsersConfig’
‘users.apps.UsersConfig’,
‘oauth.apps.OauthConfig’,
‘addresses.apps.AddressesConfig’,
‘contents.apps.ContentsConfig’,
‘goods.apps.GoodsConfig’,
‘orders.apps.OrdersConfig’,
‘payments.apps.PaymentsConfig’,
# ES搜索
‘haystack’,
‘django_crontab’, # 定时任务
‘corsheaders’, # CORS跨域
‘rest_framework’,
]

注册中间件

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’,
# ‘meiduo_mall.utils.middleware.myview’
]

指定总路由文件

ROOT_URLCONF = ‘meiduo_mall.urls’

指定模板

TEMPLATES = [
# {
# ‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
# ‘DIRS’: [],
# ‘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’,
# ],
# },
# },
{
‘BACKEND’: ‘django.template.backends.jinja2.Jinja2’, # jinja2模板引擎
‘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’,
],
# 补充Jinja2模板引擎环境
‘environment’: ‘meiduo_mall.utils.jinja2_env.jinja2_environment’,
},
},
]

指明wsgi应用

WSGI_APPLICATION = ‘meiduo_mall.wsgi.application’

Database 数据库配置、可配置主从

DATABASES = {
‘default’: { # 写 (主机)
‘ENGINE’: ‘django.db.backends.mysql’, # 数据库引擎
‘PORT’: 3306, # 数据库端口
‘HOST’: ‘127.0.0.1’, # 数据库主机
‘USER’: ‘meiduo’, # 数据库用户名
‘PASSWORD’: ‘123456’, # 数据库用户密码
‘NAME’: ‘meiduo_mall’ # 数据库名字
},
# ‘slave’: { # 读(从机)
# ‘ENGINE’: ‘django.db.backends.mysql’,
# ‘HOST’: ‘10.211.55.30’,
# ‘PORT’: 8848,
# ‘USER’: ‘root’,
# ‘PASSWORD’: ‘mysql’,
# ‘NAME’: ‘meiduo_mall’
# }
}

Password validation 用户认证

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’,
},
]

指定语言可选

LANGUAGE_CODE = ‘en-us’ #‘zh-hans’

指定时区可选

TIME_ZONE = ‘UTC’ # ‘Asia/Shanghai’

USE_I18N = True

USE_L10N = True

USE_TZ = True

静态文件

STATIC_URL = ‘/static/’

配置静态文件加载路径

STATICFILES_DIRS = [os.path.join(BASE_DIR, ‘static’)]

缓存配置

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”,
}
}
}
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’, # 日志器接收的最低日志级别
},
}
}

指定本项目用户模型类

AUTH_USER_MODEL = ‘users.User’

指定自定义的用户认证后端

AUTHENTICATION_BACKENDS = [‘users.utils.UserUtils’]

QQ的配置连接信息

QQ_CLIENT_ID = ‘101518219’
QQ_CLIENT_SECRET = ‘418d84ebdc7241efb79536886ae95224’
QQ_REDIRECT_URI = ‘http://www.meiduo.site:8000/oauth_callback’

login_requiredh装饰器指定验证用户未登录引导跳转的路径

LOGIN_URL = ‘/login/’

邮箱服务配置

EMAIL_BACKEND = ‘django.core.mail.backends.smtp.EmailBackend’ # 指定邮件后端
EMAIL_HOST = ‘smtp.163.com’ # 发邮件主机
EMAIL_PORT = 25 # 发邮件端口
EMAIL_HOST_USER = ‘[email protected]’ # 授权的邮箱
EMAIL_HOST_PASSWORD = ‘meiduo45’ # 邮箱授权时获得的密码,非注册登录密码
EMAIL_FROM = ‘美多商城[email protected]’ # 发件人抬头

邮箱验证链接

EMAIL_VERIFY_URL = ‘http://www.meiduo.site:8000/emails/verification/’

指定自定义的Django文件存储类

DEFAULT_FILE_STORAGE = ‘meiduo_mall.utils.fasfdfs.fastdfsstorage.FastDFSStorage’

Haystack 搜索引擎

HAYSTACK_CONNECTIONS = {
‘default’: {
‘ENGINE’: ‘haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine’,
‘URL’: ‘http://10.211.55.30:9200/’, # Elasticsearch服务器ip地址,端口号固定为9200
‘INDEX_NAME’: ‘meiduo_mall’, # Elasticsearch建立的索引库的名称
},
}

当添加、修改、删除数据时,自动生成索引

HAYSTACK_SIGNAL_PROCESSOR = ‘haystack.signals.RealtimeSignalProcessor’

支付宝配置

ALIPAY_APPID = ‘2016082100308405’
ALIPAY_DEBUG = True
ALIPAY_URL = ‘https://openapi.alipaydev.com/gateway.do?’
ALIPAY_RETURN_URL = ‘http://www.meiduo.site:8000/payment/status/’

定时任务

CRONJOBS = [
# 每1分钟生成一次首页静态文件
(’*/1 * * * *’, ‘Users.august.Desktop.python45.meiduo.meiduo_mall.meiduo_mall.utils.static_html.get_index_static’, '>> ’ + os.path.join(os.path.dirname(BASE_DIR), ‘logs/crontab.log’))
]

DATABASE_ROUTERS = [‘meiduo_mall.utils.db_router.MasterSlaveDBRouter’]

CORS 解决跨域

CORS_ORIGIN_WHITELIST = (
‘127.0.0.1:8080’,
‘localhost:8080’,
‘www.meiduo.site:8080’,
‘www.meiduo.site:8000’
)
CORS_ALLOW_CREDENTIALS = True # 允许携带cookie

DRF框架配置

REST_FRAMEWORK = {
‘DEFAULT_AUTHENTICATION_CLASSES’: (
‘rest_framework_jwt.authentication.JSONWebTokenAuthentication’,
‘rest_framework.authentication.SessionAuthentication’,
‘rest_framework.authentication.BasicAuthentication’,
),
}

JWT配置

JWT_AUTH = {
# 指定有效期
‘JWT_EXPIRATION_DELTA’: datetime.timedelta(days=1),
‘JWT_RESPONSE_PAYLOAD_HANDLER’:‘meiduo_admin.utils.jwt_response_payload_handler’
}

你可能感兴趣的:(Django配置详解)