Конфигурация приложения перенесена в библиотеку
This commit is contained in:
238
net/xeaf/rack/utils/settings/setting_utils.py
Normal file
238
net/xeaf/rack/utils/settings/setting_utils.py
Normal file
@@ -0,0 +1,238 @@
|
||||
# DRF Rack
|
||||
# Библиотека классов расширений для Django REST Framework
|
||||
#
|
||||
# Автор: Николай В. Анохин <n.anokhin@xeaf.net>
|
||||
# Все права защищены. Лицензия: MIT
|
||||
|
||||
"""
|
||||
Описание класса SettingUtils
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
|
||||
from .environment import Environment
|
||||
|
||||
|
||||
class SettingUtils:
|
||||
"""
|
||||
Содержит методы работа с параметрами настройки приложения
|
||||
"""
|
||||
|
||||
__base_dir: str
|
||||
""" Путь к корневой директории приложения """
|
||||
|
||||
__debug_mode: bool
|
||||
""" Признак режима отладки приложения """
|
||||
|
||||
__app_name: str
|
||||
""" Имя приложения """
|
||||
|
||||
__app_version: str
|
||||
""" Имя приложения """
|
||||
|
||||
__url_root: str
|
||||
""" Корневой URL приложения """
|
||||
|
||||
__wsgi_application: str
|
||||
""" Имя WSGI-приложения """
|
||||
|
||||
__is_initialized: bool
|
||||
""" Признак инициализации конфигурации """
|
||||
|
||||
__config_files: dict[str, str | None] = {}
|
||||
""" Словарь файлов параметров конфигурации """
|
||||
|
||||
@classmethod
|
||||
def initialize(cls, base_dir: Path, app_name: str, env_prefix: str, url_root: str, wsgi_application: str):
|
||||
"""
|
||||
Инициализирует конфигурацию приложения
|
||||
|
||||
|
||||
:param base_dir: Базовая директория приложения
|
||||
:param app_name: Имя приложения
|
||||
:param env_prefix: Префикс для переменных окружения
|
||||
:param url_root: Корневой URL приложения
|
||||
:param wsgi_application: Имя WSGI-приложения
|
||||
"""
|
||||
|
||||
cls.__base_dir = str(base_dir)
|
||||
cls.__url_root = url_root
|
||||
cls.__wsgi_application = wsgi_application
|
||||
|
||||
cls.__app_name = app_name
|
||||
cls.__app_version = cls.version_from_toml()
|
||||
|
||||
Environment.initialize(cls.__base_dir, env_prefix)
|
||||
cls.__debug_mode = Environment.get_bool('DEBUG', False)
|
||||
cls._init_configuration_files()
|
||||
|
||||
cls.__is_initialized = True
|
||||
|
||||
@classmethod
|
||||
def get_app_name(cls) -> str:
|
||||
"""
|
||||
Возвращает имя приложения
|
||||
|
||||
:return: Имя приложения
|
||||
"""
|
||||
|
||||
cls._check_initialization()
|
||||
return cls.__app_name
|
||||
|
||||
@classmethod
|
||||
def get_app_version(cls) -> str:
|
||||
"""
|
||||
Возвращает версию приложения
|
||||
|
||||
:return: Версия приложения
|
||||
"""
|
||||
|
||||
cls._check_initialization()
|
||||
return cls.__app_version
|
||||
|
||||
@classmethod
|
||||
def get_url_root(cls) -> str:
|
||||
"""
|
||||
Возвращает корневой URL приложения
|
||||
|
||||
:return: Корневой URL приложения
|
||||
"""
|
||||
|
||||
cls._check_initialization()
|
||||
return cls.__url_root
|
||||
|
||||
@classmethod
|
||||
def get_wsgi_application(cls) -> str:
|
||||
"""
|
||||
Возвращает WSGI-приложение приложения
|
||||
|
||||
:return: WSGI-приложение приложения
|
||||
"""
|
||||
|
||||
cls._check_initialization()
|
||||
return cls.__wsgi_application
|
||||
|
||||
@classmethod
|
||||
def get_base_dir(cls) -> str:
|
||||
"""
|
||||
Возвращает путь к корневой директории приложения
|
||||
|
||||
:return: Путь к корневой директории приложения
|
||||
"""
|
||||
|
||||
cls._check_initialization()
|
||||
return cls.__base_dir
|
||||
|
||||
@classmethod
|
||||
def get_debug_mode(cls) -> bool:
|
||||
"""
|
||||
Возвращает признак режима отладки приложения
|
||||
|
||||
:return: Признак режима отладки
|
||||
"""
|
||||
|
||||
cls._check_initialization()
|
||||
return cls.__debug_mode
|
||||
|
||||
@classmethod
|
||||
def is_test_mode(cls) -> bool:
|
||||
"""
|
||||
Возвращает признак режима тестирования приложения
|
||||
|
||||
:return: Признак режима тестирования приложения
|
||||
"""
|
||||
|
||||
cls._check_initialization()
|
||||
return 'test' in sys.argv
|
||||
|
||||
@classmethod
|
||||
def is_debug_mode(cls) -> bool:
|
||||
"""
|
||||
Возвращает признак режима отладки приложения
|
||||
|
||||
:return: Признак режима отладки
|
||||
"""
|
||||
|
||||
cls._check_initialization()
|
||||
return cls.__debug_mode
|
||||
|
||||
@classmethod
|
||||
def version_from_toml(cls) -> str:
|
||||
"""
|
||||
Чтение версии из файла pyproject.toml
|
||||
|
||||
:return: Номер версии
|
||||
"""
|
||||
|
||||
pyproject_path = os.path.join(cls.__base_dir, "pyproject.toml")
|
||||
with open(pyproject_path, 'rb') as f:
|
||||
data = tomllib.load(f)
|
||||
return data['project']['version']
|
||||
|
||||
@classmethod
|
||||
def get_config_files(cls) -> list[str]:
|
||||
"""
|
||||
Возвращает список файлов конфигурации
|
||||
|
||||
:return: Список файлов конфигурации
|
||||
"""
|
||||
|
||||
return [file for file in cls.__config_files.values() if file is not None]
|
||||
|
||||
@classmethod
|
||||
def set_config_file(cls, name: str, full_path: str | None) -> None:
|
||||
"""
|
||||
Устанавливает полный путь к файлу конфигурации
|
||||
|
||||
:param name: Название файла конфигурации
|
||||
:param full_path: Полный путь к файлу конфигурации
|
||||
"""
|
||||
|
||||
cls.__config_files[name] = full_path
|
||||
|
||||
@classmethod
|
||||
def get_installed_apps(cls) -> list[str]:
|
||||
"""
|
||||
Возвращает список установленных приложений
|
||||
|
||||
:return: Список установленных приложений
|
||||
"""
|
||||
|
||||
return [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.admindocs',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'corsheaders',
|
||||
'rest_framework',
|
||||
'net.xeaf.rack',
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def _check_initialization(cls) -> None:
|
||||
"""
|
||||
Проверяет завершение инициализации
|
||||
"""
|
||||
|
||||
if not cls.__is_initialized:
|
||||
raise ImproperlyConfigured(f"Class {__class__.__name__} is not initialized")
|
||||
|
||||
@classmethod
|
||||
def _init_configuration_files(cls) -> None:
|
||||
"""
|
||||
Инициализирует словарь файлов параметров конфигурации
|
||||
"""
|
||||
|
||||
root = f"{os.path.dirname(__file__)}/configs"
|
||||
for file in os.listdir(root):
|
||||
if file.endswith(".py") and file != "__init__.py":
|
||||
name = Path(file).stem
|
||||
cls.__config_files[name] = f"{root}/{file}"
|
||||
Reference in New Issue
Block a user