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.
@@ -0,0 +1,29 @@
1
+ """Permissão plugável das views REST (``RUNTIME_SETTINGS_PERMISSION``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from django.conf import settings
9
+ from django.http import HttpRequest
10
+ from django.utils.module_loading import import_string
11
+
12
+ PermissionFunc = Callable[[HttpRequest, str], bool]
13
+
14
+
15
+ def default_permission(request: HttpRequest, action: str) -> bool:
16
+ """Padrão: usuário staff; ``view`` exige ``view_setting``, ``change`` exige ``change_setting``."""
17
+ user: Any = getattr(request, "user", None)
18
+ if user is None or not user.is_authenticated or not user.is_staff:
19
+ return False
20
+ perm = "django_runtime_settings.view_setting" if action == "view" else "django_runtime_settings.change_setting"
21
+ return bool(user.has_perm(perm))
22
+
23
+
24
+ def get_permission() -> PermissionFunc:
25
+ value = getattr(settings, "RUNTIME_SETTINGS_PERMISSION", None)
26
+ if value is None:
27
+ return default_permission
28
+ func: PermissionFunc = import_string(value) if isinstance(value, str) else value
29
+ return func
File without changes
@@ -0,0 +1,124 @@
1
+ """Leitura da declaração ``RUNTIME_SETTINGS`` do ``settings.py``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import json
7
+ import os
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+ from django.conf import settings
13
+ from django.core.exceptions import ImproperlyConfigured, ValidationError
14
+ from django.utils.module_loading import import_string
15
+
16
+ from .schema import validate_schema
17
+
18
+ _PY_TYPES: dict[type, str] = {
19
+ bool: "boolean",
20
+ int: "integer",
21
+ float: "number",
22
+ str: "string",
23
+ list: "array",
24
+ dict: "object",
25
+ }
26
+
27
+ Validator = Callable[[Any], None]
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class SettingDef:
32
+ """Uma configuração declarada."""
33
+
34
+ key: str
35
+ default: Any
36
+ description: str = ""
37
+ group: str = ""
38
+ schema: dict[str, Any] | None = None
39
+ validators: tuple[Validator, ...] = field(default_factory=tuple)
40
+ env: str | None = None
41
+
42
+ def validate(self, value: Any) -> None:
43
+ """Valida pelo schema e depois pelos validadores Python."""
44
+ if self.schema is not None:
45
+ validate_schema(value, self.schema)
46
+ for validator in self.validators:
47
+ validator(value)
48
+
49
+ def env_value(self) -> tuple[bool, Any]:
50
+ """Retorna ``(True, valor)`` se a variável de ambiente existir e for válida."""
51
+ if not self.env or self.env not in os.environ:
52
+ return False, None
53
+ raw = os.environ[self.env]
54
+ try:
55
+ value = json.loads(raw)
56
+ except json.JSONDecodeError:
57
+ value = raw
58
+ try:
59
+ self.validate(value)
60
+ except ValidationError:
61
+ return False, None
62
+ return True, value
63
+
64
+ def get_default(self) -> Any:
65
+ return copy.deepcopy(self.default)
66
+
67
+
68
+ def _build(key: str, spec: Any) -> SettingDef:
69
+ if not isinstance(spec, dict) or "default" not in spec:
70
+ raise ImproperlyConfigured(f"RUNTIME_SETTINGS[{key!r}] precisa ser um dict com a chave 'default'.")
71
+ unknown = set(spec) - {"default", "description", "group", "schema", "type", "validators", "env"}
72
+ if unknown:
73
+ raise ImproperlyConfigured(f"RUNTIME_SETTINGS[{key!r}]: opções desconhecidas {sorted(unknown)}.")
74
+ schema = spec.get("schema")
75
+ py_type = spec.get("type")
76
+ if py_type is not None:
77
+ if py_type not in _PY_TYPES:
78
+ raise ImproperlyConfigured(f"RUNTIME_SETTINGS[{key!r}]: 'type' deve ser um de {list(_PY_TYPES)}.")
79
+ if schema is None:
80
+ schema = {"type": _PY_TYPES[py_type]}
81
+ elif "type" not in schema:
82
+ schema = {**schema, "type": _PY_TYPES[py_type]}
83
+ elif schema is None:
84
+ default = spec["default"]
85
+ for t, name in _PY_TYPES.items():
86
+ if type(default) is t:
87
+ schema = {"type": name}
88
+ break
89
+ validators: list[Validator] = []
90
+ for v in spec.get("validators", ()):
91
+ validators.append(import_string(v) if isinstance(v, str) else v)
92
+ env = spec.get("env")
93
+ if env is True:
94
+ env = key
95
+ return SettingDef(
96
+ key=key,
97
+ default=spec["default"],
98
+ description=spec.get("description", ""),
99
+ group=spec.get("group", ""),
100
+ schema=schema,
101
+ validators=tuple(validators),
102
+ env=env or None,
103
+ )
104
+
105
+
106
+ def get_definitions() -> dict[str, SettingDef]:
107
+ """Lê ``settings.RUNTIME_SETTINGS`` (relido a cada chamada, para respeitar ``override_settings``)."""
108
+ raw = getattr(settings, "RUNTIME_SETTINGS", {})
109
+ if not isinstance(raw, dict):
110
+ raise ImproperlyConfigured("RUNTIME_SETTINGS deve ser um dict.")
111
+ return {key: _build(key, spec) for key, spec in raw.items()}
112
+
113
+
114
+ def get_definition(key: str) -> SettingDef:
115
+ defs = get_definitions()
116
+ if key not in defs:
117
+ raise KeyError(f"Configuração não declarada em RUNTIME_SETTINGS: {key!r}")
118
+ return defs[key]
119
+
120
+
121
+ def cache_options() -> dict[str, Any]:
122
+ opts: dict[str, Any] = {"alias": "default", "timeout": 300, "prefix": "runtime_settings"}
123
+ opts.update(getattr(settings, "RUNTIME_SETTINGS_CACHE", {}))
124
+ return opts
@@ -0,0 +1,109 @@
1
+ """Validação por JSON Schema.
2
+
3
+ Usa a biblioteca ``jsonschema`` quando instalada (extra ``[jsonschema]``). Sem ela,
4
+ aplica um subconjunto próprio, suficiente para configurações: ``type``, ``enum``,
5
+ ``const``, ``properties``, ``required``, ``additionalProperties``, ``items``,
6
+ ``minItems``/``maxItems``, ``minimum``/``maximum``, ``exclusiveMinimum``/``exclusiveMaximum``,
7
+ ``minLength``/``maxLength`` e ``pattern``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from typing import Any
14
+
15
+ from django.core.exceptions import ValidationError
16
+
17
+ try: # pragma: no cover - depende do ambiente
18
+ import jsonschema as _jsonschema
19
+ except ImportError: # pragma: no cover - depende do ambiente
20
+ _jsonschema = None
21
+
22
+ _TYPES: dict[str, tuple[type, ...]] = {
23
+ "object": (dict,),
24
+ "array": (list, tuple),
25
+ "string": (str,),
26
+ "integer": (int,),
27
+ "number": (int, float),
28
+ "boolean": (bool,),
29
+ "null": (type(None),),
30
+ }
31
+
32
+
33
+ def _is_type(value: Any, name: str) -> bool:
34
+ if name not in _TYPES:
35
+ raise ValueError(f"Tipo JSON Schema não suportado: {name!r}")
36
+ if isinstance(value, bool) and name in ("integer", "number"):
37
+ return False
38
+ if name == "integer" and isinstance(value, float):
39
+ return value.is_integer()
40
+ return isinstance(value, _TYPES[name])
41
+
42
+
43
+ def _check(value: Any, schema: dict[str, Any], path: str, errors: list[str]) -> None:
44
+ where = path or "valor"
45
+ expected = schema.get("type")
46
+ if expected is not None:
47
+ names = expected if isinstance(expected, list) else [expected]
48
+ if not any(_is_type(value, n) for n in names):
49
+ errors.append(f"{where}: esperado tipo {' ou '.join(names)}, recebido {type(value).__name__}")
50
+ return
51
+ if "const" in schema and value != schema["const"]:
52
+ errors.append(f"{where}: deve ser {schema['const']!r}")
53
+ if "enum" in schema and value not in schema["enum"]:
54
+ errors.append(f"{where}: deve ser um de {schema['enum']!r}")
55
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
56
+ if "minimum" in schema and value < schema["minimum"]:
57
+ errors.append(f"{where}: mínimo {schema['minimum']}")
58
+ if "maximum" in schema and value > schema["maximum"]:
59
+ errors.append(f"{where}: máximo {schema['maximum']}")
60
+ if "exclusiveMinimum" in schema and value <= schema["exclusiveMinimum"]:
61
+ errors.append(f"{where}: deve ser maior que {schema['exclusiveMinimum']}")
62
+ if "exclusiveMaximum" in schema and value >= schema["exclusiveMaximum"]:
63
+ errors.append(f"{where}: deve ser menor que {schema['exclusiveMaximum']}")
64
+ if isinstance(value, str):
65
+ if "minLength" in schema and len(value) < schema["minLength"]:
66
+ errors.append(f"{where}: mínimo de {schema['minLength']} caracteres")
67
+ if "maxLength" in schema and len(value) > schema["maxLength"]:
68
+ errors.append(f"{where}: máximo de {schema['maxLength']} caracteres")
69
+ if "pattern" in schema and not re.search(schema["pattern"], value):
70
+ errors.append(f"{where}: não casa com o padrão {schema['pattern']!r}")
71
+ if isinstance(value, (list, tuple)):
72
+ if "minItems" in schema and len(value) < schema["minItems"]:
73
+ errors.append(f"{where}: mínimo de {schema['minItems']} itens")
74
+ if "maxItems" in schema and len(value) > schema["maxItems"]:
75
+ errors.append(f"{where}: máximo de {schema['maxItems']} itens")
76
+ items = schema.get("items")
77
+ if isinstance(items, dict):
78
+ for i, item in enumerate(value):
79
+ _check(item, items, f"{path}[{i}]", errors)
80
+ if isinstance(value, dict):
81
+ props: dict[str, Any] = schema.get("properties", {})
82
+ for req in schema.get("required", []):
83
+ if req not in value:
84
+ errors.append(f"{where}: falta a chave obrigatória {req!r}")
85
+ extra = schema.get("additionalProperties", True)
86
+ for k, v in value.items():
87
+ sub = f"{path}.{k}" if path else str(k)
88
+ if k in props:
89
+ _check(v, props[k], sub, errors)
90
+ elif extra is False:
91
+ errors.append(f"{where}: chave não permitida {k!r}")
92
+ elif isinstance(extra, dict):
93
+ _check(v, extra, sub, errors)
94
+
95
+
96
+ def validate_schema(value: Any, schema: dict[str, Any], *, use_jsonschema: bool | None = None) -> None:
97
+ """Valida ``value`` contra ``schema``; levanta ``ValidationError`` com todas as falhas."""
98
+ if use_jsonschema is None:
99
+ use_jsonschema = _jsonschema is not None
100
+ if use_jsonschema and _jsonschema is not None: # pragma: no cover - depende do ambiente
101
+ validator = _jsonschema.Draft202012Validator(schema)
102
+ msgs = [f"{'.'.join(map(str, e.absolute_path)) or 'valor'}: {e.message}" for e in validator.iter_errors(value)]
103
+ if msgs:
104
+ raise ValidationError(msgs)
105
+ return
106
+ errors: list[str] = []
107
+ _check(value, schema, "", errors)
108
+ if errors:
109
+ raise ValidationError(errors)
@@ -0,0 +1,5 @@
1
+ from django.dispatch import Signal
2
+
3
+ #: Enviado após o commit de ``config.set()``/``config.reset()``.
4
+ #: Argumentos: ``key``, ``old_value``, ``new_value``, ``user``.
5
+ setting_changed = Signal()
@@ -0,0 +1,54 @@
1
+ {% extends "admin/base_site.html" %}
2
+ {% load i18n %}
3
+
4
+ {% block breadcrumbs %}
5
+ <div class="breadcrumbs">
6
+ <a href="{% url 'admin:index' %}">{% translate 'Home' %}</a>
7
+ &rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a>
8
+ &rsaquo; {{ title }}
9
+ </div>
10
+ {% endblock %}
11
+
12
+ {% block content %}
13
+ <div id="content-main">
14
+ <p><a href="{{ history_url }}">Histórico de alterações</a></p>
15
+ {% if form.non_field_errors %}{{ form.non_field_errors }}{% endif %}
16
+ <form method="post" id="runtime-settings-form">{% csrf_token %}
17
+ {% for group, entries in groups.items %}
18
+ <fieldset class="module aligned">
19
+ {% if group %}<h2>{{ group }}</h2>{% endif %}
20
+ {% for entry in entries %}
21
+ <div class="form-row">
22
+ <h3 style="margin:0 0 4px">{{ entry.item.key }}
23
+ <small style="font-weight:normal">— origem: {{ entry.item.source }}</small></h3>
24
+ {% if entry.item.definition.description %}<div class="help">{{ entry.item.definition.description }}</div>{% endif %}
25
+ {% for field in entry.fields %}
26
+ <div class="fieldBox" style="margin:4px 0">
27
+ {{ field.errors }}
28
+ <label for="{{ field.id_for_label }}">{{ field.label }}</label>
29
+ {% if can_change %}{{ field }}{% else %}<span>{{ field.value }}</span>{% endif %}
30
+ </div>
31
+ {% endfor %}
32
+ <div class="help">Padrão: <code>{{ entry.item.default }}</code>
33
+ {% if entry.item.definition.env %} · env <code>{{ entry.item.definition.env }}</code>{% endif %}
34
+ {% if can_change and entry.item.source == "db" %}
35
+ · <button type="submit" form="reset-{{ entry.item.key }}" class="button">Restaurar padrão</button>
36
+ {% endif %}
37
+ </div>
38
+ </div>
39
+ {% endfor %}
40
+ </fieldset>
41
+ {% endfor %}
42
+ {% if can_change %}
43
+ <div class="submit-row">
44
+ <label for="id__reason">Motivo:</label>
45
+ <input type="text" name="_reason" id="id__reason" maxlength="500" size="60">
46
+ <input type="submit" value="{% translate 'Save' %}" class="default">
47
+ </div>
48
+ {% endif %}
49
+ </form>
50
+ {% if can_change %}{% for group, entries in groups.items %}{% for entry in entries %}{% if entry.item.source == "db" %}
51
+ <form method="post" id="reset-{{ entry.item.key }}" action="{% url 'admin:django_runtime_settings_setting_reset' entry.item.key %}">{% csrf_token %}</form>
52
+ {% endif %}{% endfor %}{% endfor %}{% endif %}
53
+ </div>
54
+ {% endblock %}
@@ -0,0 +1,12 @@
1
+ from django.urls import path
2
+
3
+ from . import views
4
+
5
+ app_name = "django_runtime_settings"
6
+
7
+ urlpatterns = [
8
+ path("", views.SettingListView.as_view(), name="list"),
9
+ path("history/", views.SettingHistoryView.as_view(), name="history"),
10
+ path("<str:key>/", views.SettingDetailView.as_view(), name="detail"),
11
+ path("<str:key>/history/", views.SettingHistoryView.as_view(), name="key-history"),
12
+ ]
@@ -0,0 +1,125 @@
1
+ """Rotas REST opcionais, sem dependências além do Django.
2
+
3
+ ``GET /`` lista; ``GET|PUT|PATCH|DELETE /<key>/`` lê, altera e restaura; ``GET /<key>/history/`` e
4
+ ``GET /history/`` mostram o histórico. Corpo do ``PUT``: ``{"value": ..., "reason": "..."}``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import Any
11
+
12
+ from django.core.exceptions import ValidationError
13
+ from django.http import HttpRequest, HttpResponseBase, JsonResponse
14
+ from django.utils.decorators import method_decorator
15
+ from django.views import View
16
+ from django.views.decorators.csrf import csrf_exempt
17
+
18
+ from .core import ResolvedSetting, config
19
+ from .permissions import get_permission
20
+ from .registry import get_definitions
21
+
22
+
23
+ def serialize(item: ResolvedSetting) -> dict[str, Any]:
24
+ d = item.definition
25
+ return {
26
+ "key": item.key,
27
+ "value": item.value,
28
+ "source": item.source,
29
+ "default": item.default,
30
+ "description": d.description,
31
+ "group": d.group,
32
+ "schema": d.schema,
33
+ "env": d.env,
34
+ }
35
+
36
+
37
+ def serialize_change(change: Any) -> dict[str, Any]:
38
+ user = change.changed_by
39
+ return {
40
+ "id": change.pk,
41
+ "key": change.key,
42
+ "action": change.action,
43
+ "old_value": change.old_value,
44
+ "new_value": change.new_value,
45
+ "changed_at": change.changed_at.isoformat(),
46
+ "changed_by": None if user is None else {"id": user.pk, "username": user.get_username()},
47
+ "reason": change.reason,
48
+ }
49
+
50
+
51
+ def _error(status: int, detail: Any) -> JsonResponse:
52
+ return JsonResponse({"detail": detail}, status=status)
53
+
54
+
55
+ def _page(request: HttpRequest) -> tuple[int, int]:
56
+ try:
57
+ limit = min(max(int(request.GET.get("limit", 50)), 1), 500)
58
+ offset = max(int(request.GET.get("offset", 0)), 0)
59
+ except ValueError:
60
+ return 50, 0
61
+ return limit, offset
62
+
63
+
64
+ class _Base(View):
65
+ action_for_method = {"get": "view", "head": "view", "put": "change", "patch": "change", "delete": "change"}
66
+
67
+ def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponseBase:
68
+ action = self.action_for_method.get(request.method.lower() if request.method else "", "change")
69
+ if not get_permission()(request, action):
70
+ user = getattr(request, "user", None)
71
+ status = 403 if user is not None and user.is_authenticated else 401
72
+ return _error(status, "Sem permissão.")
73
+ return super().dispatch(request, *args, **kwargs)
74
+
75
+
76
+ @method_decorator(csrf_exempt, name="dispatch")
77
+ class SettingListView(_Base):
78
+ def get(self, request: HttpRequest) -> JsonResponse:
79
+ return JsonResponse({"results": [serialize(i) for i in config.all()]})
80
+
81
+
82
+ @method_decorator(csrf_exempt, name="dispatch")
83
+ class SettingDetailView(_Base):
84
+ def get(self, request: HttpRequest, key: str) -> JsonResponse:
85
+ if key not in get_definitions():
86
+ return _error(404, f"Configuração não declarada: {key}")
87
+ return JsonResponse(serialize(config.resolve(key)))
88
+
89
+ def put(self, request: HttpRequest, key: str) -> JsonResponse:
90
+ if key not in get_definitions():
91
+ return _error(404, f"Configuração não declarada: {key}")
92
+ try:
93
+ body = json.loads(request.body or b"{}")
94
+ except json.JSONDecodeError as exc:
95
+ return _error(400, f"JSON inválido: {exc}")
96
+ if not isinstance(body, dict) or "value" not in body:
97
+ return _error(400, 'Corpo deve ser {"value": ..., "reason": "..."}.')
98
+ reason = body.get("reason", "")
99
+ if not isinstance(reason, str):
100
+ return _error(400, "'reason' deve ser texto.")
101
+ try:
102
+ item = config.set(key, body["value"], user=getattr(request, "user", None), reason=reason)
103
+ except ValidationError as exc:
104
+ return _error(400, exc.messages)
105
+ return JsonResponse(serialize(item))
106
+
107
+ patch = put
108
+
109
+ def delete(self, request: HttpRequest, key: str) -> JsonResponse:
110
+ if key not in get_definitions():
111
+ return _error(404, f"Configuração não declarada: {key}")
112
+ reason = request.GET.get("reason", "")
113
+ item = config.reset(key, user=getattr(request, "user", None), reason=reason)
114
+ return JsonResponse(serialize(item))
115
+
116
+
117
+ @method_decorator(csrf_exempt, name="dispatch")
118
+ class SettingHistoryView(_Base):
119
+ def get(self, request: HttpRequest, key: str | None = None) -> JsonResponse:
120
+ if key is not None and key not in get_definitions():
121
+ return _error(404, f"Configuração não declarada: {key}")
122
+ limit, offset = _page(request)
123
+ qs = config.history(key).select_related("changed_by")
124
+ total = qs.count()
125
+ return JsonResponse({"count": total, "results": [serialize_change(c) for c in qs[offset : offset + limit]]})
@@ -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,24 @@
1
+ django_runtime_settings/__init__.py,sha256=kLmXmN7bMXuodavUIMHYluUFs2NezlsVu8Z7M4-bzo8,535
2
+ django_runtime_settings/admin.py,sha256=uo4vFryOtyRJap4X7NsEPFuOvj4io0tpVEw97QKS3Ns,4138
3
+ django_runtime_settings/apps.py,sha256=76PnkSE2DZJFQ9EIiQvkiKp3vksT5GoaIZYukwpl-1o,1274
4
+ django_runtime_settings/core.py,sha256=SiUYY0W8hHoYQqSGllRknl2JGlbUu8XtHQ2-DlYgp28,5780
5
+ django_runtime_settings/forms.py,sha256=gnCe1ItZJ2quhjqZvWtw3rIr7sxrsWAj-LhPLlz8wfY,5225
6
+ django_runtime_settings/models.py,sha256=I6zuYxjnAs5esrTXE_bYt1pcRLkLDOPfYDSqK_BUaFw,2037
7
+ django_runtime_settings/permissions.py,sha256=-XaCeCm5mLYSmQGfLR-Ts_mFYdcHh9ibUu9gClFV_K0,1083
8
+ django_runtime_settings/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ django_runtime_settings/registry.py,sha256=PNycXse5GfQUbntYYzM2ed3kfMfZG6RfJ32efd7CEC0,4097
10
+ django_runtime_settings/schema.py,sha256=AbETk0OeqaXHlrUYauE7ltkUypoPBck0gyIXXLPHuCo,5055
11
+ django_runtime_settings/signals.py,sha256=BbGd35KDZMw8j-jG0w2uQT6xCyPNW-ZVCfjVNJdRKXs,193
12
+ django_runtime_settings/urls.py,sha256=uHKbs_Noo0zy6pPudGSPNO0rzl3Uuyg44rY9MBem-Ek,403
13
+ django_runtime_settings/views.py,sha256=Orqhe4cZjfGCWn6Afnep8ONs_b1ReFxlt_CyJMJnlSA,4821
14
+ django_runtime_settings/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ django_runtime_settings/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ django_runtime_settings/management/commands/runtime_settings.py,sha256=PkJxuyXUxXqRxLUwQqX1X4wZU_UK9WuLIhrhl0K0SvM,3606
17
+ django_runtime_settings/migrations/0001_initial.py,sha256=wSJrvDnFDiem1o2NFc2PveThfFb5vbj8wKJDNMK3IEc,3155
18
+ django_runtime_settings/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ django_runtime_settings/templates/admin/django_runtime_settings/settings.html,sha256=N6gEf8lQ5IZpho6lzwVdgIFP_gnZAOlew9CwsPbrYpg,2467
20
+ django_runtime_settings-0.1.0.dist-info/licenses/LICENSE,sha256=ASYeGjYLv6d4hS4VlX-wbp7RXIahOAvhBwO1lSq8pTw,1081
21
+ django_runtime_settings-0.1.0.dist-info/METADATA,sha256=bMQr26qw6sLql2mOhk-4hpVZ_IkI26muorf9Od58xFc,5163
22
+ django_runtime_settings-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
23
+ django_runtime_settings-0.1.0.dist-info/top_level.txt,sha256=S9Nxo-ICe1sa0SrpIyF8nMkWgCXxWCkYCOLN8-vI0mE,24
24
+ django_runtime_settings-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ django_runtime_settings