Добавлен класс ConfigurationManager
This commit is contained in:
66
net/xeaf/rack/managers/configuration_manager.py
Normal file
66
net/xeaf/rack/managers/configuration_manager.py
Normal file
@@ -0,0 +1,66 @@
|
||||
# DRF Rack
|
||||
# Библиотека классов расширений для Django REST Framework
|
||||
#
|
||||
# Автор: Николай В. Анохин <n.anokhin@xeaf.net>
|
||||
# Все права защищены. Лицензия: MIT
|
||||
|
||||
"""
|
||||
Описание класса ConfigurationManager
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
|
||||
|
||||
class ConfigurationManager:
|
||||
"""
|
||||
Прокси-менеджер для безопасного извлечения настроек из django.conf.settings
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def get_string(cls, key: str, default: str) -> str:
|
||||
"""
|
||||
Извлекает строковое значение, параметр default обязателен
|
||||
"""
|
||||
|
||||
value = getattr(settings, key, default)
|
||||
cls._assert_type(key, value, str)
|
||||
return value
|
||||
|
||||
@classmethod
|
||||
def get_int(cls, key: str, default: int) -> int:
|
||||
"""
|
||||
Извлекает целочисленное значение, параметр default обязателен
|
||||
"""
|
||||
|
||||
value = getattr(settings, key, default)
|
||||
cls._assert_type(key, value, int)
|
||||
return value
|
||||
|
||||
@classmethod
|
||||
def get_bool(cls, key: str, default: bool) -> bool:
|
||||
"""
|
||||
Извлекает логическое значение, параметр default обязателен.
|
||||
"""
|
||||
|
||||
value = getattr(settings, key, default)
|
||||
cls._assert_type(key, value, bool)
|
||||
return value
|
||||
|
||||
@classmethod
|
||||
def _assert_type(cls, key: str, value: Any, expected_type: type) -> None:
|
||||
"""
|
||||
Проверяет типы, защищая от bool/int полиморфизма
|
||||
"""
|
||||
|
||||
if expected_type is int and isinstance(value, bool):
|
||||
actual_type = bool
|
||||
else:
|
||||
actual_type = type(value)
|
||||
|
||||
if actual_type is not expected_type:
|
||||
raise ImproperlyConfigured(
|
||||
f"Configuration error: '{key}' must be of type {expected_type.__name__}, got {actual_type.__name__}."
|
||||
)
|
||||
Reference in New Issue
Block a user