!20 优化settings配置结构

* 优化settings配置结构
This commit is contained in:
剑子仙机 2022-01-18 12:32:37 +00:00 committed by 剑子仙机
parent 558e2c9619
commit a80ee8795b
10 changed files with 218 additions and 307 deletions

2
.gitignore vendored
View File

@ -15,5 +15,3 @@ sysom_api/logs/
*/src/.umi-production/
dist/
sysom_api/uploads/*
sysom_api/conf/
sysom_api/doc/

View File

@ -1,140 +0,0 @@
# -*- encoding: utf-8 -*-
"""
@File : __init__.py.py
@Time : 2021/11/3 11:21
@Author : DM
@Email : smmic@isoftstone.com
@Software: PyCharm
"""
import os
import socket
from pathlib import Path
def get_ip_address():
"""ip address"""
hostname = socket.gethostname()
return socket.gethostbyname(hostname)
class BaseConstant:
SERVER_IP = get_ip_address()
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'sysom', # Or path to database file if using sqlite3.
'USER': 'sysom', # Not used with sqlite3.
'PASSWORD': 'sysom_admin',
'HOST': '127.0.0.1',
'PORT': '3306',
},
}
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'index/status')
CLIENT_DEPLOY_CMD = 'ls /root'
# 日志
SERVER_LOGS_FILE = os.path.join(BASE_DIR, 'logs', 'sys_om_info.log')
ERROR_LOGS_FILE = os.path.join(BASE_DIR, 'logs', 'sys_om_error.log')
if not os.path.exists(os.path.join(BASE_DIR, 'logs')):
os.makedirs(os.path.join(BASE_DIR, 'logs'))
# 格式:[2020-04-22 23:33:01][micoservice.apps.ready():16] [INFO] 这是一条日志:
# 格式:[日期][模块.函数名称():行号] [级别] 信息
STANDARD_LOG_FORMAT = '[%(levelname).4s] -- %(asctime)s -- P_%(process) -- d_T_%(thread)d ' \
'- <%(module)s:%(lineno)d>: %(message)s'
CONSOLE_LOG_FORMAT = '[%(levelname).4s] -- %(asctime)s -- P_%(process) -- d_T_%(thread)d ' \
'- <%(module)s:%(lineno)d>: %(message)s'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': STANDARD_LOG_FORMAT
},
'console': {
'format': CONSOLE_LOG_FORMAT,
'datefmt': '%Y-%m-%d %H:%M:%S',
},
'file': {
'format': CONSOLE_LOG_FORMAT,
'datefmt': '%Y-%m-%d %H:%M:%S',
},
},
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': SERVER_LOGS_FILE,
'maxBytes': 1024 * 1024 * 100, # 100 MB
'backupCount': 5, # 最多备份5个
'formatter': 'standard',
'encoding': 'utf-8',
},
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': ERROR_LOGS_FILE,
'maxBytes': 1024 * 1024 * 100, # 100 MB
'backupCount': 3, # 最多备份3个
'formatter': 'standard',
'encoding': 'utf-8',
},
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'console',
}
},
'loggers': {
# default日志
'': {
'handlers': ['console', 'error', 'file'],
'level': 'INFO',
},
'django': {
'handlers': ['console', 'error', 'file'],
'level': 'INFO',
},
'scripts': {
'handlers': ['console', 'error', 'file'],
'level': 'INFO',
},
# 数据库相关日志
'django.db.backends': {
'handlers': [],
'propagate': True,
'level': 'INFO',
},
}
}
env = os.environ.get("env", "testing")
Constant = None
if env == "develop":
from .dev_constant import DevConstant
Constant = DevConstant
print(f"加载了环境 >> {env}")
elif env == "testing":
from .test_constant import TestConstant
Constant = TestConstant
print(f"加载了环境 >> {env}")
elif env == "produce":
from .pro_constant import ProConstant
Constant = ProConstant
print(f"加载了环境 >> {env}")
__all__ = ['Constant']

188
sysom_api/conf/common.py Normal file
View File

@ -0,0 +1,188 @@
import os
import socket
import datetime
from pathlib import Path
def get_ip_address():
"""ip address"""
hostname = socket.gethostname()
return socket.gethostbyname(hostname)
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-^d8b9di9w&-mmsbpt@)o#e+2^z+^m4nhf+z8304%9@8y#ko46l'
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'apps.accounts',
'apps.host',
'apps.monitor',
'apps.task',
'apps.vmcore',
'consumer',
'rest_framework',
'corsheaders',
'drf_yasg', # 在线API文档
'channels',
'django_filters',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
]
DEBUG = True
# Mysql数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'sysom',
'USER': 'sysom',
'PASSWORD': 'sysom_admin',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
ROOT_URLCONF = 'sysom.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
},
]
WSGI_APPLICATION = 'sysom.wsgi.application'
ASGI_APPLICATION = 'sysom.asgi.application'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'index/status')
# rest_framework settings
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.IsAuthenticated'
),
'DEFAULT_AUTHENTICATION_CLASSES': [
'apps.accounts.authentication.Authentication'
],
'UNAUTHENTICATED_USER': None,
'DEFAULT_VERSIONING_CLASS': "rest_framework.versioning.URLPathVersioning",
'DEFAULT_VERSION': 'v1', # 默认版本
'ALLOWED_VERSIONS': ['v1', 'v2'], # 允许的版本
'VERSION_PARAM': 'version',
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_PAGINATION_CLASS': 'lib.paginations.Pagination',
'UNICODE_JSON': False,
'EXCEPTION_HANDLER': 'lib.exception.exception_handler'
}
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
}
SERVICE_SVG_PATH = os.path.join(BASE_DIR, 'netinfo')
# upload file
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
SCRIPTS_DIR = os.path.join(BASE_DIR, 'service_scripts')
SERVER_IP = get_ip_address()
CLIENT_DEPLOY_CMD = 'ls /root'
SERVER_LOGS_FILE = os.path.join(BASE_DIR, 'logs', 'sys_om_info.log')
ERROR_LOGS_FILE = os.path.join(BASE_DIR, 'logs', 'sys_om_error.log')
if not os.path.exists(os.path.join(BASE_DIR, 'logs')):
os.makedirs(os.path.join(BASE_DIR, 'logs'))
# 格式:[2020-04-22 23:33:01][micoservice.apps.ready():16] [INFO] 这是一条日志:
# 格式:[日期][模块.函数名称():行号] [级别] 信息
STANDARD_LOG_FORMAT = '[%(levelname).4s] -- %(asctime)s -- P_%(process) -- d_T_%(thread)d ' \
'- <%(module)s:%(lineno)d>: %(message)s'
CONSOLE_LOG_FORMAT = '[%(levelname).4s] -- %(asctime)s -- P_%(process) -- d_T_%(thread)d ' \
'- <%(module)s:%(lineno)d>: %(message)s'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': STANDARD_LOG_FORMAT
},
'console': {
'format': CONSOLE_LOG_FORMAT,
'datefmt': '%Y-%m-%d %H:%M:%S',
},
'file': {
'format': CONSOLE_LOG_FORMAT,
'datefmt': '%Y-%m-%d %H:%M:%S',
},
},
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': SERVER_LOGS_FILE,
'maxBytes': 1024 * 1024 * 100, # 100 MB
'backupCount': 5, # 最多备份5个
'formatter': 'standard',
'encoding': 'utf-8',
},
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': ERROR_LOGS_FILE,
'maxBytes': 1024 * 1024 * 100, # 100 MB
'backupCount': 3, # 最多备份3个
'formatter': 'standard',
'encoding': 'utf-8',
},
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'console',
}
},
'loggers': {
# default日志
'': {
'handlers': ['console', 'error', 'file'],
'level': 'INFO',
},
'django': {
'handlers': ['console', 'error', 'file'],
'level': 'INFO',
},
'scripts': {
'handlers': ['console', 'error', 'file'],
'level': 'INFO',
},
# 数据库相关日志
'django.db.backends': {
'handlers': [],
'propagate': True,
'level': 'INFO',
},
}
}

View File

@ -1,22 +0,0 @@
# -*- encoding: utf-8 -*-
"""
@File : dev_constant.py
@Time : 2021/11/3 14:18
@Author : DM
@Software: PyCharm
"""
from . import BaseConstant
class DevConstant(BaseConstant):
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'sysom', # Or path to database file if using sqlite3.
'USER': 'sysom', # Not used with sqlite3.
'PASSWORD': 'sysom_admin',
'HOST': '127.0.0.1',
'PORT': '3306',
},
}

View File

@ -0,0 +1,7 @@
from .common import *
'''
开发环境配置项
'''
DEBUG = True

View File

@ -1,12 +0,0 @@
# -*- encoding: utf-8 -*-
"""
@File : pro_constant.py
@Time : 2021/11/3 14:17
@Author : DM
@Software: PyCharm
"""
from . import BaseConstant
class ProConstant(BaseConstant):
DEBUG = False

View File

@ -0,0 +1,7 @@
from .common import *
'''
生产环境配置项
'''
DEBUG = False

View File

@ -1,22 +0,0 @@
# -*- encoding: utf-8 -*-
"""
@File : test_constant.py
@Time : 2021/11/3 14:22
@Author : DM
@Software: PyCharm
"""
from . import BaseConstant
class TestConstant(BaseConstant):
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'sysom', # Or path to database file if using sqlite3.
'USER': 'sysom', # Not used with sqlite3.
'PASSWORD': 'sysom_admin',
'HOST': '127.0.0.1',
'PORT': '3306',
},
}

View File

@ -0,0 +1,7 @@
from .common import *
'''
测试环境配置项
'''
DEBUG = True

View File

@ -1,115 +1,15 @@
"""
Django settings for sysom project.
Generated by 'django-admin startproject' using Django 3.2.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import datetime
import os
from pathlib import Path
env = os.environ.get("env", "testing")
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-^d8b9di9w&-mmsbpt@)o#e+2^z+^m4nhf+z8304%9@8y#ko46l'
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'apps.accounts',
'apps.host',
'apps.monitor',
'apps.task',
'apps.vmcore',
'consumer',
'rest_framework',
'corsheaders',
'drf_yasg', # 在线API文档
'channels',
'django_filters',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
]
from conf import Constant as constant
DEBUG = constant.DEBUG
if env == "develop":
from conf.develop import *
elif env == "testing":
from conf.testing import *
elif env == "produce":
from conf.product import *
# 跨域允许
if DEBUG:
CORS_ORIGIN_ALLOW_ALL = True
# Mysql数据库
DATABASES = constant.DATABASES
ROOT_URLCONF = 'sysom.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
},
]
WSGI_APPLICATION = 'sysom.wsgi.application'
ASGI_APPLICATION = 'sysom.asgi.application'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LANGUAGE_CODE = constant.LANGUAGE_CODE
TIME_ZONE = constant.TIME_ZONE
USE_I18N = constant.USE_I18N
USE_L10N = constant.USE_L10N
USE_TZ = constant.USE_TZ
STATIC_URL = constant.STATIC_URL
STATIC_ROOT = constant.STATIC_ROOT
# rest_framework settings
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.IsAuthenticated'
),
'DEFAULT_AUTHENTICATION_CLASSES': [
'apps.accounts.authentication.Authentication'
],
'UNAUTHENTICATED_USER': None,
'DEFAULT_VERSIONING_CLASS': "rest_framework.versioning.URLPathVersioning",
'DEFAULT_VERSION': 'v1', # 默认版本
'ALLOWED_VERSIONS': ['v1', 'v2'], # 允许的版本
'VERSION_PARAM': 'version',
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_PAGINATION_CLASS': 'lib.paginations.Pagination',
'UNICODE_JSON': False,
'EXCEPTION_HANDLER': 'lib.exception.exception_handler'
}
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
}
LOGGING = constant.LOGGING
SERVICE_SVG_PATH = os.path.join(BASE_DIR, 'netinfo')
# upload file
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
SCRIPTS_DIR = os.path.join(BASE_DIR, 'service_scripts')
SERVER_IP = constant.SERVER_IP
CLIENT_DEPLOY_CMD = constant.CLIENT_DEPLOY_CMD
CORS_ORIGIN_ALLOW_ALL = True