django-runtime-settings 0.1.0__py3-none-any.whl
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.
- django_runtime_settings/__init__.py +24 -0
- django_runtime_settings/admin.py +100 -0
- django_runtime_settings/apps.py +38 -0
- django_runtime_settings/core.py +172 -0
- django_runtime_settings/forms.py +128 -0
- django_runtime_settings/management/__init__.py +0 -0
- django_runtime_settings/management/commands/__init__.py +0 -0
- django_runtime_settings/management/commands/runtime_settings.py +74 -0
- django_runtime_settings/migrations/0001_initial.py +78 -0
- django_runtime_settings/migrations/__init__.py +0 -0
- django_runtime_settings/models.py +60 -0
- django_runtime_settings/permissions.py +29 -0
- django_runtime_settings/py.typed +0 -0
- django_runtime_settings/registry.py +124 -0
- django_runtime_settings/schema.py +109 -0
- django_runtime_settings/signals.py +5 -0
- django_runtime_settings/templates/admin/django_runtime_settings/settings.html +54 -0
- django_runtime_settings/urls.py +12 -0
- django_runtime_settings/views.py +125 -0
- django_runtime_settings-0.1.0.dist-info/METADATA +129 -0
- django_runtime_settings-0.1.0.dist-info/RECORD +24 -0
- django_runtime_settings-0.1.0.dist-info/WHEEL +5 -0
- django_runtime_settings-0.1.0.dist-info/licenses/LICENSE +21 -0
- django_runtime_settings-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -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()
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Formulário com um campo por configuração (e um subcampo por item de dicts escalares)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from django import forms
|
|
8
|
+
from django.core.exceptions import ValidationError
|
|
9
|
+
|
|
10
|
+
from .core import ResolvedSetting, config
|
|
11
|
+
|
|
12
|
+
SEP = "__"
|
|
13
|
+
_SCALARS = {"boolean", "integer", "number", "string"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _scalar_type(schema: dict[str, Any] | None) -> str | None:
|
|
17
|
+
if not schema:
|
|
18
|
+
return None
|
|
19
|
+
t = schema.get("type")
|
|
20
|
+
return t if isinstance(t, str) and t in _SCALARS else None
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _scalar_field(schema: dict[str, Any], label: str, help_text: str = "") -> forms.Field:
|
|
24
|
+
t = schema["type"]
|
|
25
|
+
kwargs: dict[str, Any] = {"label": label, "help_text": help_text}
|
|
26
|
+
if "enum" in schema:
|
|
27
|
+
return forms.TypedChoiceField(
|
|
28
|
+
choices=[(v, str(v)) for v in schema["enum"]],
|
|
29
|
+
coerce=lambda v, enum=schema["enum"]: next((e for e in enum if str(e) == v), v),
|
|
30
|
+
**kwargs,
|
|
31
|
+
)
|
|
32
|
+
if t == "boolean":
|
|
33
|
+
return forms.BooleanField(required=False, **kwargs)
|
|
34
|
+
if t in ("integer", "number"):
|
|
35
|
+
bounds = {"min_value": schema.get("minimum"), "max_value": schema.get("maximum")}
|
|
36
|
+
cls = forms.IntegerField if t == "integer" else forms.FloatField
|
|
37
|
+
return cls(**kwargs, **{k: v for k, v in bounds.items() if v is not None})
|
|
38
|
+
return forms.CharField(
|
|
39
|
+
required=schema.get("minLength", 0) > 0,
|
|
40
|
+
max_length=schema.get("maxLength"),
|
|
41
|
+
strip=False,
|
|
42
|
+
**kwargs,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def object_subkeys(item: ResolvedSetting) -> dict[str, dict[str, Any]] | None:
|
|
47
|
+
"""Se a configuração é um dict de escalares, devolve ``{subchave: schema}``; senão ``None``."""
|
|
48
|
+
schema = item.definition.schema or {}
|
|
49
|
+
if schema.get("type") != "object" or not isinstance(item.value, dict):
|
|
50
|
+
return None
|
|
51
|
+
props: dict[str, Any] = schema.get("properties", {})
|
|
52
|
+
extra = schema.get("additionalProperties", True)
|
|
53
|
+
keys = list(dict.fromkeys([*props, *item.default, *item.value])) if isinstance(item.default, dict) else list(props)
|
|
54
|
+
result: dict[str, dict[str, Any]] = {}
|
|
55
|
+
for sub in keys:
|
|
56
|
+
sub_schema = props.get(sub, extra if isinstance(extra, dict) else None)
|
|
57
|
+
if _scalar_type(sub_schema) is None:
|
|
58
|
+
return None
|
|
59
|
+
assert sub_schema is not None
|
|
60
|
+
result[str(sub)] = sub_schema
|
|
61
|
+
return result or None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class RuntimeSettingsForm(forms.Form):
|
|
65
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
66
|
+
super().__init__(*args, **kwargs)
|
|
67
|
+
self.items: list[ResolvedSetting] = config.all()
|
|
68
|
+
self.layout: list[tuple[ResolvedSetting, list[str]]] = []
|
|
69
|
+
for item in self.items:
|
|
70
|
+
names: list[str] = []
|
|
71
|
+
subkeys = object_subkeys(item)
|
|
72
|
+
scalar = _scalar_type(item.definition.schema)
|
|
73
|
+
if subkeys is not None:
|
|
74
|
+
for sub, sub_schema in subkeys.items():
|
|
75
|
+
name = f"{item.key}{SEP}{sub}"
|
|
76
|
+
field = _scalar_field(sub_schema, sub)
|
|
77
|
+
field.required = False # chave ausente é omitida; "required" do schema decide
|
|
78
|
+
self.fields[name] = field
|
|
79
|
+
self.initial[name] = item.value.get(sub)
|
|
80
|
+
names.append(name)
|
|
81
|
+
elif scalar is not None:
|
|
82
|
+
self.fields[item.key] = _scalar_field(
|
|
83
|
+
item.definition.schema or {}, item.key, item.definition.description
|
|
84
|
+
)
|
|
85
|
+
self.initial[item.key] = item.value
|
|
86
|
+
names.append(item.key)
|
|
87
|
+
else:
|
|
88
|
+
self.fields[item.key] = forms.JSONField(
|
|
89
|
+
label=item.key, help_text=item.definition.description, required=False
|
|
90
|
+
)
|
|
91
|
+
self.initial[item.key] = item.value
|
|
92
|
+
names.append(item.key)
|
|
93
|
+
self.layout.append((item, names))
|
|
94
|
+
|
|
95
|
+
def clean(self) -> dict[str, Any]:
|
|
96
|
+
cleaned = super().clean() or {}
|
|
97
|
+
self.values: dict[str, Any] = {}
|
|
98
|
+
for item, names in self.layout:
|
|
99
|
+
subkeys = object_subkeys(item)
|
|
100
|
+
if subkeys is not None:
|
|
101
|
+
value: Any = {}
|
|
102
|
+
for sub in subkeys:
|
|
103
|
+
v = cleaned.get(f"{item.key}{SEP}{sub}")
|
|
104
|
+
if v is not None and v != "":
|
|
105
|
+
value[sub] = v
|
|
106
|
+
else:
|
|
107
|
+
if item.key not in cleaned:
|
|
108
|
+
continue
|
|
109
|
+
value = cleaned[item.key]
|
|
110
|
+
try:
|
|
111
|
+
item.definition.validate(value)
|
|
112
|
+
except ValidationError as exc:
|
|
113
|
+
for msg in exc.messages:
|
|
114
|
+
self.add_error(names[0], msg)
|
|
115
|
+
continue
|
|
116
|
+
self.values[item.key] = value
|
|
117
|
+
return cleaned
|
|
118
|
+
|
|
119
|
+
def changed_values(self) -> dict[str, Any]:
|
|
120
|
+
"""Somente as chaves cujo valor final difere do atual."""
|
|
121
|
+
current = {i.key: i.value for i in self.items}
|
|
122
|
+
return {k: v for k, v in self.values.items() if v != current.get(k)}
|
|
123
|
+
|
|
124
|
+
def save(self, user: Any = None, reason: str = "") -> list[str]:
|
|
125
|
+
changed = self.changed_values()
|
|
126
|
+
for key, value in changed.items():
|
|
127
|
+
config.set(key, value, user=user, reason=reason)
|
|
128
|
+
return list(changed)
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from django.contrib.auth import get_user_model
|
|
7
|
+
from django.core.exceptions import ValidationError
|
|
8
|
+
from django.core.management.base import BaseCommand, CommandError, CommandParser
|
|
9
|
+
|
|
10
|
+
from django_runtime_settings.core import config
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Command(BaseCommand):
|
|
14
|
+
help = "Lista, lê, altera e restaura configurações online (RUNTIME_SETTINGS)."
|
|
15
|
+
|
|
16
|
+
def add_arguments(self, parser: CommandParser) -> None:
|
|
17
|
+
sub = parser.add_subparsers(dest="action", required=True)
|
|
18
|
+
sub.add_parser("list", help="Lista chaves, valor e origem.")
|
|
19
|
+
p_get = sub.add_parser("get", help="Mostra o valor (JSON).")
|
|
20
|
+
p_get.add_argument("key")
|
|
21
|
+
p_set = sub.add_parser("set", help="Altera o valor; VALUE é JSON (texto puro vira string).")
|
|
22
|
+
p_set.add_argument("key")
|
|
23
|
+
p_set.add_argument("value")
|
|
24
|
+
p_set.add_argument("--reason", default="")
|
|
25
|
+
p_set.add_argument("--user", help="username do responsável")
|
|
26
|
+
p_reset = sub.add_parser("reset", help="Remove o valor do banco.")
|
|
27
|
+
p_reset.add_argument("key")
|
|
28
|
+
p_reset.add_argument("--reason", default="")
|
|
29
|
+
p_reset.add_argument("--user", help="username do responsável")
|
|
30
|
+
p_hist = sub.add_parser("history", help="Histórico de alterações.")
|
|
31
|
+
p_hist.add_argument("key", nargs="?")
|
|
32
|
+
p_hist.add_argument("--limit", type=int, default=20)
|
|
33
|
+
|
|
34
|
+
def _user(self, username: str | None) -> Any:
|
|
35
|
+
if not username:
|
|
36
|
+
return None
|
|
37
|
+
model = get_user_model()
|
|
38
|
+
try:
|
|
39
|
+
return model._default_manager.get_by_natural_key(username)
|
|
40
|
+
except model.DoesNotExist as exc:
|
|
41
|
+
raise CommandError(f"Usuário não encontrado: {username}") from exc
|
|
42
|
+
|
|
43
|
+
def handle(self, *args: Any, **opts: Any) -> None:
|
|
44
|
+
action = opts["action"]
|
|
45
|
+
try:
|
|
46
|
+
if action == "list":
|
|
47
|
+
for item in config.all():
|
|
48
|
+
self.stdout.write(f"{item.key} [{item.source}] = {json.dumps(item.value, ensure_ascii=False)}")
|
|
49
|
+
elif action == "get":
|
|
50
|
+
self.stdout.write(json.dumps(config.get(opts["key"]), ensure_ascii=False, indent=2))
|
|
51
|
+
elif action == "set":
|
|
52
|
+
try:
|
|
53
|
+
value = json.loads(opts["value"])
|
|
54
|
+
except json.JSONDecodeError:
|
|
55
|
+
value = opts["value"]
|
|
56
|
+
item = config.set(opts["key"], value, user=self._user(opts["user"]), reason=opts["reason"])
|
|
57
|
+
self.stdout.write(self.style.SUCCESS(f"{item.key} = {json.dumps(item.value, ensure_ascii=False)}"))
|
|
58
|
+
elif action == "reset":
|
|
59
|
+
item = config.reset(opts["key"], user=self._user(opts["user"]), reason=opts["reason"])
|
|
60
|
+
self.stdout.write(
|
|
61
|
+
self.style.SUCCESS(f"{item.key} [{item.source}] = {json.dumps(item.value, ensure_ascii=False)}")
|
|
62
|
+
)
|
|
63
|
+
elif action == "history":
|
|
64
|
+
for c in config.history(opts["key"])[: opts["limit"]]:
|
|
65
|
+
who = c.changed_by.get_username() if c.changed_by else "-"
|
|
66
|
+
self.stdout.write(
|
|
67
|
+
f"{c.changed_at:%Y-%m-%d %H:%M:%S} {c.key} {c.action} {who}: "
|
|
68
|
+
f"{json.dumps(c.old_value, ensure_ascii=False)} -> "
|
|
69
|
+
f"{json.dumps(c.new_value, ensure_ascii=False)}"
|
|
70
|
+
)
|
|
71
|
+
except KeyError as exc:
|
|
72
|
+
raise CommandError(str(exc.args[0])) from exc
|
|
73
|
+
except ValidationError as exc:
|
|
74
|
+
raise CommandError("; ".join(exc.messages)) from exc
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# Generated by Django 6.1.4 on 2026-12-03 23:28
|
|
2
|
+
|
|
3
|
+
import django.db.models.deletion
|
|
4
|
+
from django.conf import settings
|
|
5
|
+
from django.db import migrations, models
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Migration(migrations.Migration):
|
|
9
|
+
|
|
10
|
+
initial = True
|
|
11
|
+
|
|
12
|
+
dependencies = [
|
|
13
|
+
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
operations = [
|
|
17
|
+
migrations.CreateModel(
|
|
18
|
+
name="Setting",
|
|
19
|
+
fields=[
|
|
20
|
+
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
|
21
|
+
("key", models.CharField(max_length=255, unique=True, verbose_name="chave")),
|
|
22
|
+
("value", models.JSONField(null=True, verbose_name="valor")),
|
|
23
|
+
("updated_at", models.DateTimeField(auto_now=True, verbose_name="alterado em")),
|
|
24
|
+
(
|
|
25
|
+
"updated_by",
|
|
26
|
+
models.ForeignKey(
|
|
27
|
+
blank=True,
|
|
28
|
+
null=True,
|
|
29
|
+
on_delete=django.db.models.deletion.SET_NULL,
|
|
30
|
+
related_name="+",
|
|
31
|
+
to=settings.AUTH_USER_MODEL,
|
|
32
|
+
verbose_name="alterado por",
|
|
33
|
+
),
|
|
34
|
+
),
|
|
35
|
+
],
|
|
36
|
+
options={
|
|
37
|
+
"verbose_name": "configuração",
|
|
38
|
+
"verbose_name_plural": "configurações",
|
|
39
|
+
"ordering": ["key"],
|
|
40
|
+
},
|
|
41
|
+
),
|
|
42
|
+
migrations.CreateModel(
|
|
43
|
+
name="SettingChange",
|
|
44
|
+
fields=[
|
|
45
|
+
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
|
46
|
+
("key", models.CharField(db_index=True, max_length=255, verbose_name="chave")),
|
|
47
|
+
(
|
|
48
|
+
"action",
|
|
49
|
+
models.CharField(
|
|
50
|
+
choices=[("set", "alterado"), ("reset", "restaurado")],
|
|
51
|
+
default="set",
|
|
52
|
+
max_length=10,
|
|
53
|
+
verbose_name="ação",
|
|
54
|
+
),
|
|
55
|
+
),
|
|
56
|
+
("old_value", models.JSONField(blank=True, null=True, verbose_name="valor anterior")),
|
|
57
|
+
("new_value", models.JSONField(blank=True, null=True, verbose_name="novo valor")),
|
|
58
|
+
("changed_at", models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="alterado em")),
|
|
59
|
+
("reason", models.TextField(blank=True, default="", verbose_name="motivo")),
|
|
60
|
+
(
|
|
61
|
+
"changed_by",
|
|
62
|
+
models.ForeignKey(
|
|
63
|
+
blank=True,
|
|
64
|
+
null=True,
|
|
65
|
+
on_delete=django.db.models.deletion.SET_NULL,
|
|
66
|
+
related_name="+",
|
|
67
|
+
to=settings.AUTH_USER_MODEL,
|
|
68
|
+
verbose_name="alterado por",
|
|
69
|
+
),
|
|
70
|
+
),
|
|
71
|
+
],
|
|
72
|
+
options={
|
|
73
|
+
"verbose_name": "alteração de configuração",
|
|
74
|
+
"verbose_name_plural": "histórico de configurações",
|
|
75
|
+
"ordering": ["-changed_at", "-id"],
|
|
76
|
+
},
|
|
77
|
+
),
|
|
78
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from django.conf import settings
|
|
4
|
+
from django.db import models
|
|
5
|
+
from django.utils.translation import gettext_lazy as _
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Setting(models.Model):
|
|
9
|
+
"""Valor sobrescrito no banco. Chaves sem linha usam env ou o padrão do código."""
|
|
10
|
+
|
|
11
|
+
key = models.CharField(_("chave"), max_length=255, unique=True)
|
|
12
|
+
value = models.JSONField(_("valor"), null=True)
|
|
13
|
+
updated_at = models.DateTimeField(_("alterado em"), auto_now=True)
|
|
14
|
+
updated_by = models.ForeignKey(
|
|
15
|
+
settings.AUTH_USER_MODEL,
|
|
16
|
+
verbose_name=_("alterado por"),
|
|
17
|
+
null=True,
|
|
18
|
+
blank=True,
|
|
19
|
+
on_delete=models.SET_NULL,
|
|
20
|
+
related_name="+",
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
class Meta:
|
|
24
|
+
verbose_name = _("configuração")
|
|
25
|
+
verbose_name_plural = _("configurações")
|
|
26
|
+
ordering = ["key"]
|
|
27
|
+
|
|
28
|
+
def __str__(self) -> str:
|
|
29
|
+
return self.key
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SettingChange(models.Model):
|
|
33
|
+
"""Histórico de alterações."""
|
|
34
|
+
|
|
35
|
+
class Action(models.TextChoices):
|
|
36
|
+
SET = "set", _("alterado")
|
|
37
|
+
RESET = "reset", _("restaurado")
|
|
38
|
+
|
|
39
|
+
key = models.CharField(_("chave"), max_length=255, db_index=True)
|
|
40
|
+
action = models.CharField(_("ação"), max_length=10, choices=Action.choices, default=Action.SET)
|
|
41
|
+
old_value = models.JSONField(_("valor anterior"), null=True, blank=True)
|
|
42
|
+
new_value = models.JSONField(_("novo valor"), null=True, blank=True)
|
|
43
|
+
changed_at = models.DateTimeField(_("alterado em"), auto_now_add=True, db_index=True)
|
|
44
|
+
changed_by = models.ForeignKey(
|
|
45
|
+
settings.AUTH_USER_MODEL,
|
|
46
|
+
verbose_name=_("alterado por"),
|
|
47
|
+
null=True,
|
|
48
|
+
blank=True,
|
|
49
|
+
on_delete=models.SET_NULL,
|
|
50
|
+
related_name="+",
|
|
51
|
+
)
|
|
52
|
+
reason = models.TextField(_("motivo"), blank=True, default="")
|
|
53
|
+
|
|
54
|
+
class Meta:
|
|
55
|
+
verbose_name = _("alteração de configuração")
|
|
56
|
+
verbose_name_plural = _("histórico de configurações")
|
|
57
|
+
ordering = ["-changed_at", "-id"]
|
|
58
|
+
|
|
59
|
+
def __str__(self) -> str:
|
|
60
|
+
return f"{self.key} @ {self.changed_at:%Y-%m-%d %H:%M}"
|