Django开发之配置文件(二)
前言
一个合格的项目应该包含本地、测试、正式环境及日志文件输出,本文就如何区分环境进行数据库、日志、参数配置,本项目采用apollo方式实现环境动态配置
一、Django配置文件
1.配置文件设置
结合Django开发之目录结构(一)
配置文件所在路径如下:
xxxmanager/xxxmanager/settings.py
#系统设置环境变量,mac如下设置:在.bash_profile文件下追加
export PYTHON_ENV=local
#,然后更新
source ~/.bash_profile
from pathlib import Path
import time
import os
from apollo.apollo_client import ApolloClient
import ldap
from django_auth_ldap.config import LDAPSearch, PosixGroupType
ENV_PROFILE = os.getenv("PYTHON_ENV")
if ENV_PROFILE == "local":
client = ApolloClient(app_id="xxx", cluster="default", config_url="", start_hot_update=False)
else:
client = ApolloClient(app_id="xxx", cluster="default", config_url="http://xxxx/",start_hot_update=False)
BASE_DIR = Path(__file__).resolve().parent.parent
log_path = BASE_DIR / 'logs'
Path(log_path).mkdir(parents=True, exist_ok=True)
PROJECT_VERSION = client.get_value("project_version", default_val="v1", namespace="xxxx")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
DEBUG_VAL = client.get_value("debug", default_val=False, namespace="xxx")
if DEBUG_VAL == "True":
DEBUG = True
该文件开始需要配置如下内容:
- pathlib包,最新Django项目(python>=3.4)已经抛弃os.path使用,强烈建议使用pathlib
- apollo包,获取远程配置,当环境设置为local,默认取本地配置,配置文件默认在~/data/apollo/cache/,相关包见apollo-client
- log_path ,日志输出位置
- PROJECT_VERSION,项目版本,用以区分静态资源访问
- DEBUG = False,此参数十分关键,影响静态资源的访问,本地一般设置DEBUG = True,为什么会引入DEBUG_VAL,因为从Apollo远程获取的值均为字符串,需要转换
2.数据库配置
代码如下:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'xxxxx', # 数据库名称
'OPTIONS': {'charset': 'utf8mb4'},
'HOST': client.get_value("host", default_val="defaultVal", namespace="xxxx"), # 数据库地址,本机 ip 地址 127.0.0.1
'PORT': 3306, # 端口
'USER': client.get_value("user", default_val="defaultVal", namespace="xxxx"), # 数据库用户名
'PASSWORD': client.get_value("password", default_val="defaultVal", namespace="xxxx"), # 数据库密码
'TEST_CHARSET': 'utf8mb4',
'TEST_COLLATION': 'utf8mb4_general_ci',
}
}
3.日志配置
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
# 日志格式
'standard': {
'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] '
'[%(levelname)s]- %(message)s'},
'simple': { # 简单格式
'format': '%(levelname)s %(message)s'
},
},
# 过滤
'filters': {
},
# 定义具体处理日志的方式
'handlers': {
# 默认记录所有日志
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': log_path / 'all-{}.log'.format(time.strftime('%Y-%m-%d')),
'maxBytes': 1024 * 1024 * 5, # 文件大小
'backupCount': 5, # 备份数
'formatter': 'standard', # 输出格式
'encoding': 'utf-8', # 设置默认编码,否则打印出来汉字乱码
},
# 输出错误日志
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': log_path / 'error-{}.log'.format(time.strftime('%Y-%m-%d')),
'maxBytes': 1024 * 1024 * 5, # 文件大小
'backupCount': 5, # 备份数
'formatter': 'standard', # 输出格式
'encoding': 'utf-8', # 设置默认编码
},
# 控制台输出
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
# 输出info日志
'info': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': log_path / 'info-{}.log'.format(time.strftime('%Y-%m-%d')),
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8', # 设置默认编码
},
},
# 配置用哪几种 handlers 来处理日志
'loggers': {
# 类型 为 django 处理所有类型的日志, 默认调用
'django': {
'handlers': ['default', 'console'],
'level': 'INFO',
'propagate': False
},
# log 调用时需要当作参数传入
'log': {
'handlers': ['error', 'info', 'console', 'default'],
'level': 'INFO',
'propagate': True
},
"django_auth_ldap": {
"handlers": ['console', 'info', 'default'],
"level": 'DEBUG',
},
}
}
二、静态资源与DEBUG
- 在debug关闭情况下和打开情况下静态资源访问方式完全不一样,为避免页面缓存,setting文件作如下配置
STATIC_URL = '/static/'
STATIC_ROOT = Path(BASE_DIR, 'statics')
STATICFILES_DIRS = [
BASE_DIR / "static",
]
STATIC_ROOT为什么和其他不一样呢,是因为当设置中DEBUG为True时,django会自动为你静态文件代理,不过当DEBUG为False时,意味着你要进入生产环境,那么,你就必须使用STATIC_ROOT来指明你的静态文件在哪里,然后使用nginx等进行代理
- 创建templatetags/cache_bust.py 文件
说明:DEBUG为false(一般为线上环境),采用配置文件中的PROJECT_VERSION,如果DEBUG为true,资源文件参数随机生成(规避静态资源缓存),方便我们调试
import uuid
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(name='cache_bust')
def cache_bust():
if settings.DEBUG:
version = uuid.uuid1()
else:
version = settings.PROJECT_VERSION
if version is None:
version = '1'
return '__v__={version}'.format(version=version)
总结
以上就是今天要讲的内容,重点介绍了配置文件中DEBUG为false和true区别,及在本地开发中,如何让静态资源规避缓存,访问不生效问题