django-runtime-settings 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. django_runtime_settings-0.1.0/LICENSE +21 -0
  2. django_runtime_settings-0.1.0/PKG-INFO +129 -0
  3. django_runtime_settings-0.1.0/README.md +90 -0
  4. django_runtime_settings-0.1.0/django_runtime_settings/__init__.py +24 -0
  5. django_runtime_settings-0.1.0/django_runtime_settings/admin.py +100 -0
  6. django_runtime_settings-0.1.0/django_runtime_settings/apps.py +38 -0
  7. django_runtime_settings-0.1.0/django_runtime_settings/core.py +172 -0
  8. django_runtime_settings-0.1.0/django_runtime_settings/forms.py +128 -0
  9. django_runtime_settings-0.1.0/django_runtime_settings/management/__init__.py +0 -0
  10. django_runtime_settings-0.1.0/django_runtime_settings/management/commands/__init__.py +0 -0
  11. django_runtime_settings-0.1.0/django_runtime_settings/management/commands/runtime_settings.py +74 -0
  12. django_runtime_settings-0.1.0/django_runtime_settings/migrations/0001_initial.py +78 -0
  13. django_runtime_settings-0.1.0/django_runtime_settings/migrations/__init__.py +0 -0
  14. django_runtime_settings-0.1.0/django_runtime_settings/models.py +60 -0
  15. django_runtime_settings-0.1.0/django_runtime_settings/permissions.py +29 -0
  16. django_runtime_settings-0.1.0/django_runtime_settings/py.typed +0 -0
  17. django_runtime_settings-0.1.0/django_runtime_settings/registry.py +124 -0
  18. django_runtime_settings-0.1.0/django_runtime_settings/schema.py +109 -0
  19. django_runtime_settings-0.1.0/django_runtime_settings/signals.py +5 -0
  20. django_runtime_settings-0.1.0/django_runtime_settings/templates/admin/django_runtime_settings/settings.html +54 -0
  21. django_runtime_settings-0.1.0/django_runtime_settings/urls.py +12 -0
  22. django_runtime_settings-0.1.0/django_runtime_settings/views.py +125 -0
  23. django_runtime_settings-0.1.0/django_runtime_settings.egg-info/PKG-INFO +129 -0
  24. django_runtime_settings-0.1.0/django_runtime_settings.egg-info/SOURCES.txt +30 -0
  25. django_runtime_settings-0.1.0/django_runtime_settings.egg-info/dependency_links.txt +1 -0
  26. django_runtime_settings-0.1.0/django_runtime_settings.egg-info/requires.txt +14 -0
  27. django_runtime_settings-0.1.0/django_runtime_settings.egg-info/top_level.txt +1 -0
  28. django_runtime_settings-0.1.0/pyproject.toml +85 -0
  29. django_runtime_settings-0.1.0/setup.cfg +4 -0
  30. django_runtime_settings-0.1.0/tests/test_core.py +162 -0
  31. django_runtime_settings-0.1.0/tests/test_interfaces.py +174 -0
  32. django_runtime_settings-0.1.0/tests/test_schema.py +62 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Django Tools By KelsonCM
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-runtime-settings
3
+ Version: 0.1.0
4
+ Summary: Django settings editable at runtime: JSON Schema validation, change history, cache, optional admin and REST API
5
+ Author: kelsoncm
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/django-by-kelsoncm/runtime_settings
8
+ Project-URL: Documentation, https://django-by-kelsoncm.github.io/runtime_settings/
9
+ Project-URL: Issues, https://github.com/django-by-kelsoncm/runtime_settings/issues
10
+ Keywords: django,settings,configuration,runtime,json-schema,constance
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: Django :: 5.2
14
+ Classifier: Framework :: Django :: 6.0
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: Django<7,>=5.2
27
+ Provides-Extra: jsonschema
28
+ Requires-Dist: jsonschema>=4.18; extra == "jsonschema"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8.0; extra == "dev"
31
+ Requires-Dist: pytest-django>=4.8; extra == "dev"
32
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
33
+ Requires-Dist: black>=24.0; extra == "dev"
34
+ Requires-Dist: ruff>=0.4; extra == "dev"
35
+ Requires-Dist: mypy>=1.10; extra == "dev"
36
+ Requires-Dist: django-stubs>=5.1; extra == "dev"
37
+ Requires-Dist: pre-commit>=3.7; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # django-runtime-settings
41
+
42
+ [![PyPI](https://img.shields.io/pypi/v/django-runtime-settings)](https://pypi.org/project/django-runtime-settings/)
43
+ [![Tests](https://github.com/django-by-kelsoncm/runtime_settings/actions/workflows/test.yml/badge.svg)](https://github.com/django-by-kelsoncm/runtime_settings/actions/workflows/test.yml)
44
+
45
+ Configurações Django alteráveis em tempo de execução, sem deploy.
46
+
47
+ 1. Declaração das chaves e padrões no `settings.py` (`RUNTIME_SETTINGS`).
48
+ 2. Valores JSON validados por tipo, JSON Schema e/ou validadores Python.
49
+ 3. Precedência: **banco > variável de ambiente > padrão do código**.
50
+ 4. Cache pelo framework de cache do Django, invalidado ao salvar.
51
+ 5. Histórico de alterações: quem, quando, antes e depois, motivo.
52
+ 6. Django admin opcional, com um campo por item (não JSON cru).
53
+ 7. API REST opcional, sem dependências, para projetos que não usam o Django admin.
54
+ 8. Comando `manage.py runtime_settings`.
55
+ 9. Única dependência: Django ≥ 5.2. Python ≥ 3.10.
56
+
57
+ Documentação: <https://django-by-kelsoncm.github.io/runtime_settings/>
58
+
59
+ ## Instalação
60
+
61
+ ```bash
62
+ pip install django-runtime-settings
63
+ # opcional: JSON Schema completo (sem ele, um subconjunto embutido é usado)
64
+ pip install "django-runtime-settings[jsonschema]"
65
+ ```
66
+
67
+ ```python
68
+ INSTALLED_APPS = [..., "django_runtime_settings"]
69
+
70
+ RUNTIME_SETTINGS = {
71
+ "SUGESTAO_PESOS": {
72
+ "default": {"cursos": 1.0, "cnes": 1.0, "cidade": 0.25},
73
+ "schema": {"type": "object", "additionalProperties": {"type": "number", "minimum": 0}},
74
+ "env": "SUGESTAO_PESOS", # JSON na variável de ambiente
75
+ "description": "Pesos da sugestão de contatos",
76
+ "group": "Sugestões",
77
+ },
78
+ "IA_LIMIAR": {"default": 0.7, "type": float, "schema": {"minimum": 0, "maximum": 1}},
79
+ "IA_MAX_SUGESTOES": {"default": 10, "validators": ["meuapp.validators.positivo"], "env": True},
80
+ }
81
+ ```
82
+
83
+ ```bash
84
+ python manage.py migrate
85
+ ```
86
+
87
+ ## Uso
88
+
89
+ ```python
90
+ from django_runtime_settings import config
91
+
92
+ config.IA_LIMIAR # 0.7
93
+ config.get("SUGESTAO_PESOS")["cidade"]
94
+ config.set("IA_LIMIAR", 0.8, user=request.user, reason="ajuste")
95
+ config.reset("IA_LIMIAR") # volta para env ou padrão
96
+ config.history("IA_LIMIAR") # QuerySet de SettingChange
97
+ ```
98
+
99
+ ## Interfaces
100
+
101
+ 1. **Django admin**: com `django.contrib.admin` instalado, aparece em *Configurações online*.
102
+ 2. **REST**: `path("api/settings/", include("django_runtime_settings.urls"))`.
103
+ 1. `GET /` lista; `GET|PUT|DELETE /<chave>/`; `GET /<chave>/history/`; `GET /history/`.
104
+ 2. `PUT` recebe `{"value": ..., "reason": "..."}`.
105
+ 3. Permissão: `RUNTIME_SETTINGS_PERMISSION = "meuapp.perms.pode"` (função `(request, action) -> bool`, `action` em `view`/`change`). Padrão: staff com `view_setting`/`change_setting`.
106
+ 3. **CLI**: `python manage.py runtime_settings list|get|set|reset|history`.
107
+
108
+ ## Comparação
109
+
110
+ | | django-runtime-settings | django-constance | django-dynamic-preferences |
111
+ |---|---|---|---|
112
+ | Valores JSON com schema | sim | não | parcial |
113
+ | Histórico de alterações | sim | não | não |
114
+ | Fallback para env | sim | não | não |
115
+ | UI sem Django admin | REST embutida | não | via DRF |
116
+ | Dependências | só Django | Django (+ redis opcional) | Django (+ DRF opcional) |
117
+
118
+ ## Desenvolvimento
119
+
120
+ ```bash
121
+ pip install -e ".[dev]"
122
+ pre-commit install
123
+ pytest --cov=django_runtime_settings
124
+ ruff check . && ruff format --check . && mypy django_runtime_settings
125
+ ```
126
+
127
+ ## Licença
128
+
129
+ MIT.
@@ -0,0 +1,90 @@
1
+ # django-runtime-settings
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/django-runtime-settings)](https://pypi.org/project/django-runtime-settings/)
4
+ [![Tests](https://github.com/django-by-kelsoncm/runtime_settings/actions/workflows/test.yml/badge.svg)](https://github.com/django-by-kelsoncm/runtime_settings/actions/workflows/test.yml)
5
+
6
+ Configurações Django alteráveis em tempo de execução, sem deploy.
7
+
8
+ 1. Declaração das chaves e padrões no `settings.py` (`RUNTIME_SETTINGS`).
9
+ 2. Valores JSON validados por tipo, JSON Schema e/ou validadores Python.
10
+ 3. Precedência: **banco > variável de ambiente > padrão do código**.
11
+ 4. Cache pelo framework de cache do Django, invalidado ao salvar.
12
+ 5. Histórico de alterações: quem, quando, antes e depois, motivo.
13
+ 6. Django admin opcional, com um campo por item (não JSON cru).
14
+ 7. API REST opcional, sem dependências, para projetos que não usam o Django admin.
15
+ 8. Comando `manage.py runtime_settings`.
16
+ 9. Única dependência: Django ≥ 5.2. Python ≥ 3.10.
17
+
18
+ Documentação: <https://django-by-kelsoncm.github.io/runtime_settings/>
19
+
20
+ ## Instalação
21
+
22
+ ```bash
23
+ pip install django-runtime-settings
24
+ # opcional: JSON Schema completo (sem ele, um subconjunto embutido é usado)
25
+ pip install "django-runtime-settings[jsonschema]"
26
+ ```
27
+
28
+ ```python
29
+ INSTALLED_APPS = [..., "django_runtime_settings"]
30
+
31
+ RUNTIME_SETTINGS = {
32
+ "SUGESTAO_PESOS": {
33
+ "default": {"cursos": 1.0, "cnes": 1.0, "cidade": 0.25},
34
+ "schema": {"type": "object", "additionalProperties": {"type": "number", "minimum": 0}},
35
+ "env": "SUGESTAO_PESOS", # JSON na variável de ambiente
36
+ "description": "Pesos da sugestão de contatos",
37
+ "group": "Sugestões",
38
+ },
39
+ "IA_LIMIAR": {"default": 0.7, "type": float, "schema": {"minimum": 0, "maximum": 1}},
40
+ "IA_MAX_SUGESTOES": {"default": 10, "validators": ["meuapp.validators.positivo"], "env": True},
41
+ }
42
+ ```
43
+
44
+ ```bash
45
+ python manage.py migrate
46
+ ```
47
+
48
+ ## Uso
49
+
50
+ ```python
51
+ from django_runtime_settings import config
52
+
53
+ config.IA_LIMIAR # 0.7
54
+ config.get("SUGESTAO_PESOS")["cidade"]
55
+ config.set("IA_LIMIAR", 0.8, user=request.user, reason="ajuste")
56
+ config.reset("IA_LIMIAR") # volta para env ou padrão
57
+ config.history("IA_LIMIAR") # QuerySet de SettingChange
58
+ ```
59
+
60
+ ## Interfaces
61
+
62
+ 1. **Django admin**: com `django.contrib.admin` instalado, aparece em *Configurações online*.
63
+ 2. **REST**: `path("api/settings/", include("django_runtime_settings.urls"))`.
64
+ 1. `GET /` lista; `GET|PUT|DELETE /<chave>/`; `GET /<chave>/history/`; `GET /history/`.
65
+ 2. `PUT` recebe `{"value": ..., "reason": "..."}`.
66
+ 3. Permissão: `RUNTIME_SETTINGS_PERMISSION = "meuapp.perms.pode"` (função `(request, action) -> bool`, `action` em `view`/`change`). Padrão: staff com `view_setting`/`change_setting`.
67
+ 3. **CLI**: `python manage.py runtime_settings list|get|set|reset|history`.
68
+
69
+ ## Comparação
70
+
71
+ | | django-runtime-settings | django-constance | django-dynamic-preferences |
72
+ |---|---|---|---|
73
+ | Valores JSON com schema | sim | não | parcial |
74
+ | Histórico de alterações | sim | não | não |
75
+ | Fallback para env | sim | não | não |
76
+ | UI sem Django admin | REST embutida | não | via DRF |
77
+ | Dependências | só Django | Django (+ redis opcional) | Django (+ DRF opcional) |
78
+
79
+ ## Desenvolvimento
80
+
81
+ ```bash
82
+ pip install -e ".[dev]"
83
+ pre-commit install
84
+ pytest --cov=django_runtime_settings
85
+ ruff check . && ruff format --check . && mypy django_runtime_settings
86
+ ```
87
+
88
+ ## Licença
89
+
90
+ MIT.
@@ -0,0 +1,24 @@
1
+ """Configurações Django alteráveis online."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ if TYPE_CHECKING:
10
+ from .core import RuntimeConfig
11
+
12
+ config: RuntimeConfig
13
+
14
+
15
+ def __getattr__(name: str) -> Any:
16
+ # Import tardio: permite ``from django_runtime_settings import config`` em settings/urls sem carregar models cedo.
17
+ if name == "config":
18
+ from .core import config
19
+
20
+ return config
21
+ raise AttributeError(name)
22
+
23
+
24
+ __all__ = ["config", "__version__"]
@@ -0,0 +1,100 @@
1
+ """Integração opcional com o Django admin (carregada só se ``django.contrib.admin`` estiver instalado)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from django.contrib import admin, messages
8
+ from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
9
+ from django.template.response import TemplateResponse
10
+ from django.urls import path, reverse
11
+
12
+ from .core import config
13
+ from .forms import RuntimeSettingsForm
14
+ from .models import Setting, SettingChange
15
+
16
+
17
+ @admin.register(Setting)
18
+ class SettingAdmin(admin.ModelAdmin): # type: ignore[type-arg]
19
+ """A lista de ``Setting`` vira uma página única com o formulário de todas as configurações."""
20
+
21
+ def has_add_permission(self, request: HttpRequest) -> bool:
22
+ return False
23
+
24
+ def has_delete_permission(self, request: HttpRequest, obj: Any = None) -> bool:
25
+ return False
26
+
27
+ def get_urls(self) -> list[Any]:
28
+ info = self.opts.app_label, self.opts.model_name
29
+ return [
30
+ path("", self.admin_site.admin_view(self.settings_view), name="%s_%s_changelist" % info),
31
+ path(
32
+ "<str:key>/reset/",
33
+ self.admin_site.admin_view(self.reset_view),
34
+ name="%s_%s_reset" % info,
35
+ ),
36
+ ]
37
+
38
+ def settings_view(self, request: HttpRequest) -> HttpResponse:
39
+ if not self.has_view_permission(request):
40
+ from django.core.exceptions import PermissionDenied
41
+
42
+ raise PermissionDenied
43
+ can_change = self.has_change_permission(request)
44
+ if request.method == "POST" and can_change:
45
+ form = RuntimeSettingsForm(request.POST)
46
+ if form.is_valid():
47
+ changed = form.save(user=request.user, reason=request.POST.get("_reason", ""))
48
+ if changed:
49
+ messages.success(request, f"Configurações alteradas: {', '.join(changed)}.")
50
+ else:
51
+ messages.info(request, "Nenhuma alteração.")
52
+ return HttpResponseRedirect(request.path)
53
+ else:
54
+ form = RuntimeSettingsForm()
55
+ groups: dict[str, list[dict[str, Any]]] = {}
56
+ for item, names in form.layout:
57
+ groups.setdefault(item.definition.group or "", []).append(
58
+ {"item": item, "fields": [form[n] for n in names]}
59
+ )
60
+ context = {
61
+ **self.admin_site.each_context(request),
62
+ "title": str(self.opts.verbose_name_plural).capitalize(),
63
+ "opts": self.opts,
64
+ "form": form,
65
+ "groups": groups,
66
+ "can_change": can_change,
67
+ "history_url": reverse("admin:django_runtime_settings_settingchange_changelist"),
68
+ }
69
+ return TemplateResponse(request, "admin/django_runtime_settings/settings.html", context)
70
+
71
+ def reset_view(self, request: HttpRequest, key: str) -> HttpResponse:
72
+ if request.method != "POST" or not self.has_change_permission(request):
73
+ from django.core.exceptions import PermissionDenied
74
+
75
+ raise PermissionDenied
76
+ try:
77
+ config.reset(key, user=request.user, reason=request.POST.get("_reason", ""))
78
+ except KeyError:
79
+ messages.error(request, f"Configuração não declarada: {key}")
80
+ else:
81
+ messages.success(request, f"{key} restaurada.")
82
+ return HttpResponseRedirect(reverse("admin:django_runtime_settings_setting_changelist"))
83
+
84
+
85
+ @admin.register(SettingChange)
86
+ class SettingChangeAdmin(admin.ModelAdmin): # type: ignore[type-arg]
87
+ list_display = ("changed_at", "key", "action", "changed_by", "reason")
88
+ list_filter = ("key", "action")
89
+ search_fields = ("key", "reason")
90
+ date_hierarchy = "changed_at"
91
+ readonly_fields = ("key", "action", "old_value", "new_value", "changed_at", "changed_by", "reason")
92
+
93
+ def has_add_permission(self, request: HttpRequest) -> bool:
94
+ return False
95
+
96
+ def has_change_permission(self, request: HttpRequest, obj: Any = None) -> bool:
97
+ return False
98
+
99
+ def has_delete_permission(self, request: HttpRequest, obj: Any = None) -> bool:
100
+ return False
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from django.apps import AppConfig
6
+ from django.core import checks
7
+ from django.core.exceptions import ImproperlyConfigured, ValidationError
8
+
9
+
10
+ def check_definitions(app_configs: Any = None, **kwargs: Any) -> list[checks.CheckMessage]:
11
+ """Confere a declaração ``RUNTIME_SETTINGS`` e se cada padrão passa na própria validação."""
12
+ from . import registry
13
+
14
+ try:
15
+ defs = registry.get_definitions()
16
+ except (ImproperlyConfigured, ImportError) as exc:
17
+ return [checks.Error(str(exc), id="django_runtime_settings.E001")]
18
+ errors: list[checks.CheckMessage] = []
19
+ for d in defs.values():
20
+ try:
21
+ d.validate(d.default)
22
+ except ValidationError as exc:
23
+ errors.append(
24
+ checks.Error(
25
+ f"Padrão de {d.key!r} não passa na validação: {'; '.join(exc.messages)}",
26
+ id="django_runtime_settings.E002",
27
+ )
28
+ )
29
+ return errors
30
+
31
+
32
+ class RuntimeSettingsConfig(AppConfig):
33
+ name = "django_runtime_settings"
34
+ verbose_name = "Configurações online"
35
+ default_auto_field = "django.db.models.BigAutoField"
36
+
37
+ def ready(self) -> None:
38
+ checks.register(check_definitions)
@@ -0,0 +1,172 @@
1
+ """API Python: ``config.CHAVE``, ``config.get()``, ``config.set()``, ``config.reset()``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING, Any, Literal
7
+
8
+ from django.core.cache import caches
9
+ from django.db import transaction
10
+
11
+ from . import registry
12
+ from .signals import setting_changed
13
+
14
+ if TYPE_CHECKING:
15
+ from django.contrib.auth.base_user import AbstractBaseUser
16
+ from django.contrib.auth.models import AnonymousUser
17
+
18
+ Source = Literal["db", "env", "default"]
19
+
20
+ _CACHE_KEY = "values"
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ResolvedSetting:
25
+ key: str
26
+ value: Any
27
+ source: Source
28
+ default: Any
29
+ definition: registry.SettingDef
30
+
31
+
32
+ def _cache_key() -> str:
33
+ return f"{registry.cache_options()['prefix']}:{_CACHE_KEY}"
34
+
35
+
36
+ def _cache_timeout() -> int:
37
+ return int(registry.cache_options()["timeout"])
38
+
39
+
40
+ def _cache() -> Any:
41
+ return caches[registry.cache_options()["alias"]]
42
+
43
+
44
+ def _db_values() -> dict[str, Any]:
45
+ """Valores do banco, via cache (uma entrada para todas as chaves)."""
46
+ from .models import Setting
47
+
48
+ timeout = _cache_timeout()
49
+ if timeout > 0:
50
+ cached = _cache().get(_cache_key())
51
+ if cached is not None:
52
+ return dict(cached)
53
+ values = dict(Setting.objects.values_list("key", "value"))
54
+ if timeout > 0:
55
+ _cache().set(_cache_key(), values, timeout)
56
+ return values
57
+
58
+
59
+ def invalidate_cache() -> None:
60
+ """Apaga a entrada de cache; a próxima leitura vai ao banco."""
61
+ _cache().delete(_cache_key())
62
+
63
+
64
+ class RuntimeConfig:
65
+ """Acesso às configurações declaradas em ``RUNTIME_SETTINGS``. Precedência: banco > env > padrão."""
66
+
67
+ def resolve(self, key: str) -> ResolvedSetting:
68
+ definition = registry.get_definition(key)
69
+ return self._resolve(definition, _db_values())
70
+
71
+ def _resolve(self, definition: registry.SettingDef, db: dict[str, Any]) -> ResolvedSetting:
72
+ default = definition.get_default()
73
+ if definition.key in db:
74
+ return ResolvedSetting(definition.key, db[definition.key], "db", default, definition)
75
+ found, env_value = definition.env_value()
76
+ if found:
77
+ return ResolvedSetting(definition.key, env_value, "env", default, definition)
78
+ return ResolvedSetting(definition.key, default, "default", default, definition)
79
+
80
+ def all(self) -> list[ResolvedSetting]:
81
+ db = _db_values()
82
+ return [self._resolve(d, db) for d in registry.get_definitions().values()]
83
+
84
+ def get(self, key: str) -> Any:
85
+ return self.resolve(key).value
86
+
87
+ def __getattr__(self, key: str) -> Any:
88
+ if key.startswith("_"):
89
+ raise AttributeError(key)
90
+ try:
91
+ return self.get(key)
92
+ except KeyError as exc:
93
+ raise AttributeError(str(exc)) from exc
94
+
95
+ def __dir__(self) -> list[str]:
96
+ return sorted(set(super().__dir__()) | set(registry.get_definitions()))
97
+
98
+ def validate(self, key: str, value: Any) -> None:
99
+ registry.get_definition(key).validate(value)
100
+
101
+ def set(
102
+ self,
103
+ key: str,
104
+ value: Any,
105
+ *,
106
+ user: AbstractBaseUser | AnonymousUser | None = None,
107
+ reason: str = "",
108
+ ) -> ResolvedSetting:
109
+ """Valida e grava ``value`` no banco, registrando o histórico."""
110
+ from .models import Setting, SettingChange
111
+
112
+ definition = registry.get_definition(key)
113
+ definition.validate(value)
114
+ user_obj = user if user is not None and getattr(user, "pk", None) is not None else None
115
+ with transaction.atomic():
116
+ old = self.resolve(key).value
117
+ Setting.objects.update_or_create(key=key, defaults={"value": value, "updated_by": user_obj})
118
+ SettingChange.objects.create(
119
+ key=key,
120
+ action=SettingChange.Action.SET,
121
+ old_value=old,
122
+ new_value=value,
123
+ changed_by=user_obj,
124
+ reason=reason,
125
+ )
126
+ self._after_change(key, old, value, user_obj)
127
+ return self.resolve(key)
128
+
129
+ def reset(
130
+ self, key: str, *, user: AbstractBaseUser | AnonymousUser | None = None, reason: str = ""
131
+ ) -> ResolvedSetting:
132
+ """Remove o valor do banco; volta a valer env ou o padrão do código."""
133
+ from .models import Setting, SettingChange
134
+
135
+ registry.get_definition(key)
136
+ user_obj = user if user is not None and getattr(user, "pk", None) is not None else None
137
+ with transaction.atomic():
138
+ old = Setting.objects.filter(key=key).values_list("value", flat=True).first()
139
+ deleted, _ = Setting.objects.filter(key=key).delete()
140
+ if deleted:
141
+ invalidate_cache()
142
+ new = self.resolve(key).value
143
+ SettingChange.objects.create(
144
+ key=key,
145
+ action=SettingChange.Action.RESET,
146
+ old_value=old,
147
+ new_value=new,
148
+ changed_by=user_obj,
149
+ reason=reason,
150
+ )
151
+ self._after_change(key, old, new, user_obj)
152
+ return self.resolve(key)
153
+
154
+ def history(self, key: str | None = None) -> Any:
155
+ from .models import SettingChange
156
+
157
+ qs = SettingChange.objects.all()
158
+ if key is not None:
159
+ registry.get_definition(key)
160
+ qs = qs.filter(key=key)
161
+ return qs
162
+
163
+ @staticmethod
164
+ def _after_change(key: str, old: Any, new: Any, user: Any) -> None:
165
+ invalidate_cache()
166
+ transaction.on_commit(invalidate_cache)
167
+ transaction.on_commit(
168
+ lambda: setting_changed.send(sender=RuntimeConfig, key=key, old_value=old, new_value=new, user=user)
169
+ )
170
+
171
+
172
+ config = RuntimeConfig()