django-admin-api-mcp 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.
- admin_api_mcp/__init__.py +9 -0
- admin_api_mcp/actions.py +197 -0
- admin_api_mcp/admin.py +131 -0
- admin_api_mcp/apps.py +10 -0
- admin_api_mcp/auth.py +62 -0
- admin_api_mcp/changelist.py +261 -0
- admin_api_mcp/checks.py +35 -0
- admin_api_mcp/confirm.py +97 -0
- admin_api_mcp/contrib/__init__.py +1 -0
- admin_api_mcp/contrib/search/__init__.py +0 -0
- admin_api_mcp/contrib/search/apps.py +21 -0
- admin_api_mcp/contrib/search/backend.py +121 -0
- admin_api_mcp/contrib/search/checks.py +12 -0
- admin_api_mcp/contrib/search/conf.py +42 -0
- admin_api_mcp/contrib/search/engines/__init__.py +0 -0
- admin_api_mcp/contrib/search/engines/base.py +99 -0
- admin_api_mcp/contrib/search/engines/db.py +265 -0
- admin_api_mcp/contrib/search/fold.py +41 -0
- admin_api_mcp/contrib/search/indexer.py +364 -0
- admin_api_mcp/contrib/search/management/__init__.py +0 -0
- admin_api_mcp/contrib/search/management/commands/__init__.py +0 -0
- admin_api_mcp/contrib/search/management/commands/rebuild_search_index.py +29 -0
- admin_api_mcp/contrib/search/management/commands/search_index.py +25 -0
- admin_api_mcp/contrib/search/migrations/0001_initial.py +83 -0
- admin_api_mcp/contrib/search/migrations/__init__.py +0 -0
- admin_api_mcp/contrib/search/models.py +43 -0
- admin_api_mcp/contrib/subadmin.py +37 -0
- admin_api_mcp/custom_views.py +471 -0
- admin_api_mcp/decorators.py +26 -0
- admin_api_mcp/deletion.py +58 -0
- admin_api_mcp/detail.py +115 -0
- admin_api_mcp/encoders.py +72 -0
- admin_api_mcp/errors.py +82 -0
- admin_api_mcp/jsonschema.py +225 -0
- admin_api_mcp/management/__init__.py +0 -0
- admin_api_mcp/management/commands/__init__.py +0 -0
- admin_api_mcp/management/commands/create_api_token.py +40 -0
- admin_api_mcp/management/commands/mcp_serve.py +86 -0
- admin_api_mcp/management/commands/migrate_from_admin_api.py +153 -0
- admin_api_mcp/mcp/__init__.py +7 -0
- admin_api_mcp/mcp/bridge.py +71 -0
- admin_api_mcp/mcp/handlers.py +771 -0
- admin_api_mcp/mcp/resolve.py +410 -0
- admin_api_mcp/mcp/server.py +76 -0
- admin_api_mcp/mcp/sites.py +284 -0
- admin_api_mcp/mcp/stdio.py +53 -0
- admin_api_mcp/mcp/tools.py +84 -0
- admin_api_mcp/mcp/views.py +74 -0
- admin_api_mcp/middleware.py +18 -0
- admin_api_mcp/migrations/0001_initial.py +40 -0
- admin_api_mcp/migrations/0002_mcp_confirmation.py +27 -0
- admin_api_mcp/migrations/0003_mcp_user_instructions.py +28 -0
- admin_api_mcp/migrations/__init__.py +0 -0
- admin_api_mcp/mixins.py +173 -0
- admin_api_mcp/models.py +145 -0
- admin_api_mcp/nested.py +122 -0
- admin_api_mcp/resolver.py +95 -0
- admin_api_mcp/scopes.py +142 -0
- admin_api_mcp/sensitive.py +67 -0
- admin_api_mcp/services.py +652 -0
- admin_api_mcp/sites.py +242 -0
- admin_api_mcp/templates/admin_api_mcp/token_created.html +17 -0
- admin_api_mcp/views/__init__.py +0 -0
- admin_api_mcp/views/changelist.py +70 -0
- admin_api_mcp/views/custom.py +33 -0
- admin_api_mcp/views/detail.py +50 -0
- admin_api_mcp/views/nested.py +73 -0
- admin_api_mcp/views/registry.py +15 -0
- admin_api_mcp/writes.py +530 -0
- django_admin_api_mcp-0.1.0.dist-info/METADATA +280 -0
- django_admin_api_mcp-0.1.0.dist-info/RECORD +73 -0
- django_admin_api_mcp-0.1.0.dist-info/WHEEL +4 -0
- django_admin_api_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
"""Custom admin views in the API and MCP: ``@admin_api_mcp.view``.
|
|
2
|
+
|
|
3
|
+
A custom admin page (a statement, a stock balance, "post this invoice"…) usually has two
|
|
4
|
+
parts: computing data and rendering HTML. Put the first part in a ModelAdmin method decorated
|
|
5
|
+
with :func:`admin_api_mcp.view`; the HTML view and the API then share it::
|
|
6
|
+
|
|
7
|
+
class ClientAdmin(admin.ModelAdmin):
|
|
8
|
+
@admin_api_mcp.view(detail=True, params=StatementForm, description="Account statement.")
|
|
9
|
+
def statement(self, request, obj, date_from=None, date_to=None):
|
|
10
|
+
return {...} # JSON-able (models, dates, Decimals are encoded)
|
|
11
|
+
|
|
12
|
+
* ``detail=True``: runs on one object, ``method(request, obj, **params)``;
|
|
13
|
+
REST ``/v1/<app>/<model>/<pk>/views/<name>/``.
|
|
14
|
+
``detail=False``: ``method(request, **params)``; REST ``/v1/<app>/<model>/views/<name>/``.
|
|
15
|
+
* ``params``: a Django ``Form`` class (validated, ``cleaned_data`` passed as keyword arguments,
|
|
16
|
+
JSON Schema generated from it) or a dict of JSON Schema properties (with ``required=[...]``).
|
|
17
|
+
* ``permissions``: like ``@admin.action(permissions=...)``: every ``has_<perm>_permission`` must
|
|
18
|
+
pass (``view`` means view-or-change; with ``detail=True`` the object is passed for the
|
|
19
|
+
built-in ones). Token scopes apply to the built-in ones.
|
|
20
|
+
* ``writes``: defaults to ``True`` when ``permissions`` asks for more than ``view``
|
|
21
|
+
(``writes=True`` with the default permissions means ``permissions=["change"]``). Write views
|
|
22
|
+
are POST only, run in a transaction, need a write scope on tokens, are hidden from read-only
|
|
23
|
+
MCP sites and support a dry run (MCP ``dry_run``, REST ``?dry_run=1``). Read views accept GET
|
|
24
|
+
(query string) and POST (JSON).
|
|
25
|
+
* MCP: listed in ``list_models`` and ``describe_model``, run with the ``run_view`` tool;
|
|
26
|
+
``mcp_tool="name"`` also publishes the view as its own MCP tool (top-level admins only).
|
|
27
|
+
* ``api_enabled=False`` hides the view from both surfaces, ``mcp_enabled=False`` from MCP only.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import copy
|
|
33
|
+
from dataclasses import dataclass, field
|
|
34
|
+
|
|
35
|
+
from django import forms
|
|
36
|
+
from django.core.exceptions import ImproperlyConfigured, ValidationError
|
|
37
|
+
from django.core.exceptions import PermissionDenied as DjangoPermissionDenied
|
|
38
|
+
from django.db import router, transaction
|
|
39
|
+
from django.http import HttpResponseBase, QueryDict
|
|
40
|
+
from django.utils.dateparse import parse_date, parse_datetime, parse_time
|
|
41
|
+
from django.utils.translation import gettext
|
|
42
|
+
|
|
43
|
+
from . import scopes
|
|
44
|
+
from .encoders import encode_value
|
|
45
|
+
from .errors import ApiError, NotFound, PermissionDeniedError
|
|
46
|
+
|
|
47
|
+
VIEW_ATTR = "admin_api_view"
|
|
48
|
+
READ_METHODS = ("GET", "POST")
|
|
49
|
+
WRITE_METHODS = ("POST",)
|
|
50
|
+
# Reserved keys of a promoted MCP tool's arguments (params are flattened next to them).
|
|
51
|
+
TOOL_RESERVED = frozenset({"pk", "dry_run", "confirm_token"})
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class InvalidParams(ApiError):
|
|
55
|
+
status = 400
|
|
56
|
+
code = "invalid_params"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class ViewNotSupported(ApiError):
|
|
60
|
+
status = 400
|
|
61
|
+
code = "view_not_supported"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class ViewSpec:
|
|
66
|
+
"""What ``@admin_api_mcp.view`` attaches to a ModelAdmin method."""
|
|
67
|
+
|
|
68
|
+
name: str
|
|
69
|
+
attname: str # the method name on the admin
|
|
70
|
+
detail: bool = False
|
|
71
|
+
permissions: tuple = ("view",)
|
|
72
|
+
writes: bool = False
|
|
73
|
+
form_class: type | None = None
|
|
74
|
+
properties: dict = field(default_factory=dict) # JSON Schema properties, when not a form
|
|
75
|
+
required: tuple = ()
|
|
76
|
+
title: str = ""
|
|
77
|
+
description: str = ""
|
|
78
|
+
output_schema: dict | None = None
|
|
79
|
+
api_enabled: bool = True
|
|
80
|
+
mcp_enabled: bool = True
|
|
81
|
+
mcp_tool: str | None = None
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def methods(self) -> tuple:
|
|
85
|
+
return WRITE_METHODS if self.writes else READ_METHODS
|
|
86
|
+
|
|
87
|
+
def params_schema(self) -> dict:
|
|
88
|
+
"""JSON Schema (object) of the parameters."""
|
|
89
|
+
if self.form_class is not None:
|
|
90
|
+
from .jsonschema import form_object_schema
|
|
91
|
+
|
|
92
|
+
return form_object_schema(self.form_class, required=True)
|
|
93
|
+
out = {"type": "object", "properties": dict(self.properties), "additionalProperties": False}
|
|
94
|
+
if self.required:
|
|
95
|
+
out["required"] = list(self.required)
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
def describe(self) -> dict:
|
|
99
|
+
out = {
|
|
100
|
+
"name": self.name,
|
|
101
|
+
"title": self.title,
|
|
102
|
+
"description": self.description,
|
|
103
|
+
"detail": self.detail,
|
|
104
|
+
"writes": self.writes,
|
|
105
|
+
"permissions": list(self.permissions),
|
|
106
|
+
"params_schema": self.params_schema(),
|
|
107
|
+
}
|
|
108
|
+
if self.output_schema is not None:
|
|
109
|
+
out["output_schema"] = self.output_schema
|
|
110
|
+
if self.mcp_tool:
|
|
111
|
+
out["mcp_tool"] = self.mcp_tool
|
|
112
|
+
return out
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def view(
|
|
116
|
+
function=None,
|
|
117
|
+
*,
|
|
118
|
+
name: str | None = None,
|
|
119
|
+
detail: bool = False,
|
|
120
|
+
permissions=("view",),
|
|
121
|
+
writes: bool | None = None,
|
|
122
|
+
params=None,
|
|
123
|
+
required=(),
|
|
124
|
+
title: str | None = None,
|
|
125
|
+
description: str | None = None,
|
|
126
|
+
output_schema: dict | None = None,
|
|
127
|
+
api_enabled: bool = True,
|
|
128
|
+
mcp_enabled: bool = True,
|
|
129
|
+
mcp_tool: str | None = None,
|
|
130
|
+
):
|
|
131
|
+
"""Expose a ModelAdmin method as a custom view in the REST API and MCP. See the module docs."""
|
|
132
|
+
|
|
133
|
+
def decorator(func):
|
|
134
|
+
where = f"@admin_api_mcp.view {func.__name__}:"
|
|
135
|
+
permissions_ = (permissions,) if isinstance(permissions, str) else tuple(permissions)
|
|
136
|
+
if writes and permissions_ == ("view",):
|
|
137
|
+
permissions_ = ("change",) # a write view does not run on view permission alone
|
|
138
|
+
if not permissions_:
|
|
139
|
+
raise ImproperlyConfigured(f"{where} permissions cannot be empty.")
|
|
140
|
+
form_class, properties = None, {}
|
|
141
|
+
if isinstance(params, type) and issubclass(params, forms.BaseForm):
|
|
142
|
+
form_class = params
|
|
143
|
+
if required:
|
|
144
|
+
raise ImproperlyConfigured(f"{where} 'required' comes from the form.")
|
|
145
|
+
elif isinstance(params, dict):
|
|
146
|
+
properties = dict(params)
|
|
147
|
+
unknown = set(required) - set(properties)
|
|
148
|
+
if unknown:
|
|
149
|
+
raise ImproperlyConfigured(f"{where} required {sorted(unknown)} not in params.")
|
|
150
|
+
elif params is not None:
|
|
151
|
+
raise ImproperlyConfigured(f"{where} params must be a Form class or a dict of JSON Schema properties.")
|
|
152
|
+
names = set(form_class.base_fields) if form_class is not None else set(properties)
|
|
153
|
+
if mcp_tool and names & TOOL_RESERVED:
|
|
154
|
+
raise ImproperlyConfigured(
|
|
155
|
+
f"{where} params {sorted(names & TOOL_RESERVED)} clash with the arguments "
|
|
156
|
+
f"of the MCP tool {mcp_tool!r}; rename them."
|
|
157
|
+
)
|
|
158
|
+
doc = (func.__doc__ or "").strip()
|
|
159
|
+
spec = ViewSpec(
|
|
160
|
+
name=name or func.__name__,
|
|
161
|
+
attname=func.__name__,
|
|
162
|
+
detail=detail,
|
|
163
|
+
permissions=permissions_,
|
|
164
|
+
writes=(set(permissions_) != {"view"}) if writes is None else bool(writes),
|
|
165
|
+
form_class=form_class,
|
|
166
|
+
properties=properties,
|
|
167
|
+
required=tuple(required),
|
|
168
|
+
title=str(title or (name or func.__name__).replace("_", " ").capitalize()),
|
|
169
|
+
description=str(description or doc),
|
|
170
|
+
output_schema=output_schema,
|
|
171
|
+
api_enabled=api_enabled,
|
|
172
|
+
mcp_enabled=mcp_enabled,
|
|
173
|
+
mcp_tool=mcp_tool,
|
|
174
|
+
)
|
|
175
|
+
setattr(func, VIEW_ATTR, spec)
|
|
176
|
+
return func
|
|
177
|
+
|
|
178
|
+
if function is None:
|
|
179
|
+
return decorator
|
|
180
|
+
return decorator(function)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
# --------------------------------------------------------------------------------------------
|
|
184
|
+
# discovery
|
|
185
|
+
# --------------------------------------------------------------------------------------------
|
|
186
|
+
_class_cache: dict = {}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def declared_views(model_admin) -> dict[str, ViewSpec]:
|
|
190
|
+
"""``{name: spec}`` of the views declared on the admin's class (subclasses override)."""
|
|
191
|
+
cls = type(model_admin)
|
|
192
|
+
cached = _class_cache.get(cls)
|
|
193
|
+
if cached is None:
|
|
194
|
+
cached = {}
|
|
195
|
+
for klass in reversed(cls.__mro__):
|
|
196
|
+
for attr, value in vars(klass).items():
|
|
197
|
+
# an override replaces the inherited view; without the decorator it removes it
|
|
198
|
+
cached = {n: s for n, s in cached.items() if s.attname != attr}
|
|
199
|
+
spec = getattr(value, VIEW_ATTR, None)
|
|
200
|
+
if isinstance(spec, ViewSpec):
|
|
201
|
+
cached[spec.name] = spec
|
|
202
|
+
_class_cache[cls] = cached
|
|
203
|
+
return cached
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def has_view_permission(model_admin, request, spec: ViewSpec, obj=None) -> bool:
|
|
207
|
+
"""Every permission of ``spec`` (and the token scopes of the built-in ones)."""
|
|
208
|
+
for perm in spec.permissions:
|
|
209
|
+
if perm == "view":
|
|
210
|
+
ok = model_admin.has_view_or_change_permission(request, obj)
|
|
211
|
+
elif perm == "add":
|
|
212
|
+
ok = model_admin.has_add_permission(request)
|
|
213
|
+
elif perm in ("change", "delete"):
|
|
214
|
+
ok = getattr(model_admin, f"has_{perm}_permission")(request, obj)
|
|
215
|
+
else: # custom, like admin actions: has_<perm>_permission(request)
|
|
216
|
+
checker = getattr(model_admin, f"has_{perm}_permission", None)
|
|
217
|
+
if checker is None:
|
|
218
|
+
raise ImproperlyConfigured(
|
|
219
|
+
f"{type(model_admin).__name__} has no has_{perm}_permission() for view {spec.name!r}."
|
|
220
|
+
)
|
|
221
|
+
ok = checker(request)
|
|
222
|
+
if not ok:
|
|
223
|
+
return False
|
|
224
|
+
return all(scopes.request_allows(request, model_admin.opts, op) for op in scope_ops(spec))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def scope_ops(spec: ViewSpec) -> set:
|
|
228
|
+
"""Token scope operations a view needs (:func:`admin_api_mcp.scopes.required_ops`)."""
|
|
229
|
+
return scopes.required_ops(spec.permissions, writes=spec.writes)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _enabled(spec: ViewSpec, mcp: bool, read_only: bool) -> bool:
|
|
233
|
+
"""Is ``spec`` switched on for this surface (REST or MCP, read-only or not)?"""
|
|
234
|
+
return spec.api_enabled and (spec.mcp_enabled or not mcp) and not (read_only and spec.writes)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def available_views(model_admin, request, *, mcp: bool = False, read_only: bool = False) -> list[ViewSpec]:
|
|
238
|
+
"""The views ``request.user`` may run on this admin (detail views checked without an object)."""
|
|
239
|
+
return [
|
|
240
|
+
spec
|
|
241
|
+
for spec in declared_views(model_admin).values()
|
|
242
|
+
if _enabled(spec, mcp, read_only) and has_view_permission(model_admin, request, spec)
|
|
243
|
+
]
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def get_view(model_admin, request, name: str, *, mcp: bool = False, read_only: bool = False) -> ViewSpec:
|
|
247
|
+
spec = declared_views(model_admin).get(name)
|
|
248
|
+
if spec is None or not _enabled(spec, mcp, read_only):
|
|
249
|
+
raise NotFound(
|
|
250
|
+
gettext("No view '%(view)s' on %(models)s.")
|
|
251
|
+
% {"view": name, "models": model_admin.opts.verbose_name_plural}
|
|
252
|
+
)
|
|
253
|
+
return spec
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
# --------------------------------------------------------------------------------------------
|
|
257
|
+
# parameters
|
|
258
|
+
# --------------------------------------------------------------------------------------------
|
|
259
|
+
_TYPES = {
|
|
260
|
+
"string": lambda v: isinstance(v, str),
|
|
261
|
+
"integer": lambda v: isinstance(v, int) and not isinstance(v, bool),
|
|
262
|
+
"number": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool),
|
|
263
|
+
"boolean": lambda v: isinstance(v, bool),
|
|
264
|
+
"array": lambda v: isinstance(v, list),
|
|
265
|
+
"object": lambda v: isinstance(v, dict),
|
|
266
|
+
"null": lambda v: v is None,
|
|
267
|
+
}
|
|
268
|
+
_FORMATS = {"date": parse_date, "date-time": parse_datetime, "time": parse_time}
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _types(schema) -> list:
|
|
272
|
+
t = schema.get("type")
|
|
273
|
+
return t if isinstance(t, list) else ([t] if t else [])
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _from_query(raw: list[str], schema: dict):
|
|
277
|
+
"""Query-string values (strings) → the JSON type the schema asks for."""
|
|
278
|
+
types = _types(schema)
|
|
279
|
+
if "array" in types:
|
|
280
|
+
items = schema.get("items") or {}
|
|
281
|
+
return [_from_query([v], items) for v in raw]
|
|
282
|
+
value = raw[-1]
|
|
283
|
+
if value == "" and "null" in types:
|
|
284
|
+
return None
|
|
285
|
+
for t in types:
|
|
286
|
+
try:
|
|
287
|
+
if t == "integer":
|
|
288
|
+
return int(value)
|
|
289
|
+
if t == "number":
|
|
290
|
+
return float(value) if any(c in value for c in ".eE") else int(value)
|
|
291
|
+
if t == "boolean" and value.lower() in ("1", "true", "yes", "on", "0", "false", "no", "off"):
|
|
292
|
+
return value.lower() in ("1", "true", "yes", "on")
|
|
293
|
+
except ValueError:
|
|
294
|
+
continue
|
|
295
|
+
return value
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _check_value(name: str, value, schema: dict, errors: dict):
|
|
299
|
+
types = _types(schema)
|
|
300
|
+
if types and not any(_TYPES.get(t, lambda v: True)(value) for t in types):
|
|
301
|
+
errors.setdefault(name, []).append(f"Expected {' or '.join(types)}.")
|
|
302
|
+
return value
|
|
303
|
+
if "enum" in schema and value not in schema["enum"]:
|
|
304
|
+
errors.setdefault(name, []).append(f"Must be one of: {', '.join(map(str, schema['enum']))}.")
|
|
305
|
+
return value
|
|
306
|
+
if isinstance(value, list) and "items" in schema:
|
|
307
|
+
return [_check_value(f"{name}[{i}]", v, schema["items"], errors) for i, v in enumerate(value)]
|
|
308
|
+
parser = _FORMATS.get(schema.get("format"))
|
|
309
|
+
if parser is not None and isinstance(value, str):
|
|
310
|
+
try:
|
|
311
|
+
parsed = parser(value)
|
|
312
|
+
except ValueError:
|
|
313
|
+
parsed = None
|
|
314
|
+
if parsed is None:
|
|
315
|
+
errors.setdefault(name, []).append(f"Not a valid {schema['format']}.")
|
|
316
|
+
return parsed
|
|
317
|
+
for key, test, msg in (
|
|
318
|
+
("minimum", lambda v, m: v >= m, "at least"),
|
|
319
|
+
("maximum", lambda v, m: v <= m, "at most"),
|
|
320
|
+
):
|
|
321
|
+
if key in schema and isinstance(value, (int, float)) and not test(value, schema[key]):
|
|
322
|
+
errors.setdefault(name, []).append(f"Must be {msg} {schema[key]}.")
|
|
323
|
+
return value
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _clean_schema_params(spec: ViewSpec, data: dict) -> dict:
|
|
327
|
+
errors: dict = {}
|
|
328
|
+
for key in data:
|
|
329
|
+
if key not in spec.properties:
|
|
330
|
+
errors.setdefault(key, []).append("Unknown parameter.")
|
|
331
|
+
out = {}
|
|
332
|
+
for key, schema in spec.properties.items():
|
|
333
|
+
if key in data:
|
|
334
|
+
out[key] = _check_value(key, data[key], schema, errors)
|
|
335
|
+
elif key in spec.required:
|
|
336
|
+
errors.setdefault(key, []).append("This parameter is required.")
|
|
337
|
+
elif "default" in schema:
|
|
338
|
+
out[key] = _check_value(key, schema["default"], schema, errors)
|
|
339
|
+
if errors:
|
|
340
|
+
raise InvalidParams("Invalid parameters.", fields=errors)
|
|
341
|
+
return out
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _clean_form_params(spec: ViewSpec, request, data) -> dict:
|
|
345
|
+
from .writes import field_post_values
|
|
346
|
+
|
|
347
|
+
base_fields = spec.form_class.base_fields
|
|
348
|
+
if isinstance(data, QueryDict):
|
|
349
|
+
query = data
|
|
350
|
+
unknown = [k for k in query if k not in base_fields and not any(k.startswith(f"{f}_") for f in base_fields)]
|
|
351
|
+
else:
|
|
352
|
+
query = QueryDict(mutable=True)
|
|
353
|
+
unknown = [k for k in data if k not in base_fields]
|
|
354
|
+
for key, value in data.items():
|
|
355
|
+
if key in base_fields:
|
|
356
|
+
for post_key, values in field_post_values(key, base_fields[key], value).items():
|
|
357
|
+
query.setlist(post_key, values)
|
|
358
|
+
if unknown:
|
|
359
|
+
raise InvalidParams("Invalid parameters.", fields={k: ["Unknown parameter."] for k in unknown})
|
|
360
|
+
form = spec.form_class(data=query)
|
|
361
|
+
if not form.is_valid():
|
|
362
|
+
errors = {k: [str(m) for m in v] for k, v in form.errors.items()}
|
|
363
|
+
raise InvalidParams("Invalid parameters.", fields=errors)
|
|
364
|
+
return dict(form.cleaned_data)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def clean_params(spec: ViewSpec, request, data) -> dict:
|
|
368
|
+
"""Validate ``data`` (a JSON object, or the query string of a GET as a ``QueryDict``) into the
|
|
369
|
+
keyword arguments of the view method."""
|
|
370
|
+
if spec.form_class is not None:
|
|
371
|
+
return _clean_form_params(spec, request, data)
|
|
372
|
+
if isinstance(data, QueryDict):
|
|
373
|
+
data = {k: _from_query(data.getlist(k), spec.properties.get(k, {})) for k in data}
|
|
374
|
+
return _clean_schema_params(spec, data)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
# --------------------------------------------------------------------------------------------
|
|
378
|
+
# running
|
|
379
|
+
# --------------------------------------------------------------------------------------------
|
|
380
|
+
def view_object(model_admin, request, spec: ViewSpec, object_id):
|
|
381
|
+
"""The object a detail view runs on (``None`` for a list view); checks the pk is given or absent."""
|
|
382
|
+
from .services import get_object
|
|
383
|
+
|
|
384
|
+
if spec.detail:
|
|
385
|
+
if object_id is None:
|
|
386
|
+
raise InvalidParams(gettext("View '%(view)s' runs on one record: give its ID.") % {"view": spec.name})
|
|
387
|
+
return get_object(model_admin, request, object_id)
|
|
388
|
+
if object_id is not None:
|
|
389
|
+
raise InvalidParams(
|
|
390
|
+
gettext("View '%(view)s' does not run on one record: no ID expected.") % {"view": spec.name}
|
|
391
|
+
)
|
|
392
|
+
return None
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def check_view_permission(model_admin, request, spec: ViewSpec, obj=None) -> None:
|
|
396
|
+
if not has_view_permission(model_admin, request, spec, obj):
|
|
397
|
+
raise PermissionDeniedError(gettext("You may not run the view '%(view)s'.") % {"view": spec.name})
|
|
398
|
+
for op in scope_ops(spec): # second line of defense, like the other services
|
|
399
|
+
scopes.check(request, model_admin.opts, op)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def run_view(model_admin, request, spec: ViewSpec, obj=None, data=None) -> dict:
|
|
403
|
+
"""Validate ``data`` and run the view ``spec`` on ``obj``, its permissions checked by the caller
|
|
404
|
+
(:func:`admin_api_mcp.services.run_view`). Returns ``{"view", "result", "messages"}``, plus ``"pk"``
|
|
405
|
+
for a detail view."""
|
|
406
|
+
from .writes import capture_messages
|
|
407
|
+
|
|
408
|
+
kwargs = clean_params(spec, request, data if data is not None else {})
|
|
409
|
+
|
|
410
|
+
# a copy, so messages raised by the view are captured and returned instead of stored
|
|
411
|
+
request = copy.copy(request)
|
|
412
|
+
storage = capture_messages(request)
|
|
413
|
+
method = getattr(model_admin, spec.attname)
|
|
414
|
+
args = (request, obj) if spec.detail else (request,)
|
|
415
|
+
try:
|
|
416
|
+
if spec.writes:
|
|
417
|
+
with transaction.atomic(using=router.db_for_write(model_admin.model)):
|
|
418
|
+
result = method(*args, **kwargs)
|
|
419
|
+
if isinstance(result, HttpResponseBase):
|
|
420
|
+
transaction.set_rollback(True)
|
|
421
|
+
elif obj is not None: # the view's title only: parameter values stay out of the audit table
|
|
422
|
+
model_admin.log_change(request, obj, gettext("Ran %(view)s.") % {"view": spec.title})
|
|
423
|
+
else:
|
|
424
|
+
result = method(*args, **kwargs)
|
|
425
|
+
except DjangoPermissionDenied as exc:
|
|
426
|
+
raise PermissionDeniedError(str(exc) or None) from exc
|
|
427
|
+
except ValidationError as exc:
|
|
428
|
+
raise ApiError(
|
|
429
|
+
"; ".join(exc.messages), status=400, code="validation_failed", non_field_errors=exc.messages
|
|
430
|
+
) from exc
|
|
431
|
+
if isinstance(result, HttpResponseBase):
|
|
432
|
+
raise ViewNotSupported(
|
|
433
|
+
f"View {spec.name!r} returned a page/file; nothing was changed. Return JSON-able data from the "
|
|
434
|
+
"@admin_api_mcp.view method and render it in your HTML view instead."
|
|
435
|
+
)
|
|
436
|
+
out = {"view": spec.name}
|
|
437
|
+
if spec.detail:
|
|
438
|
+
out["pk"] = encode_value(obj.pk)
|
|
439
|
+
out["result"] = encode_value(result)
|
|
440
|
+
messages = storage.captured()
|
|
441
|
+
if messages:
|
|
442
|
+
out["messages"] = messages
|
|
443
|
+
return out
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def view_url(spec: ViewSpec, base_url: str | None, pk=None) -> str | None:
|
|
447
|
+
"""REST url of a view under the changelist url ``base_url``."""
|
|
448
|
+
if base_url is None:
|
|
449
|
+
return None
|
|
450
|
+
if spec.detail:
|
|
451
|
+
if pk is None:
|
|
452
|
+
return None
|
|
453
|
+
from django.contrib.admin.utils import quote
|
|
454
|
+
|
|
455
|
+
return f"{base_url}{quote(str(pk))}/views/{spec.name}/"
|
|
456
|
+
return f"{base_url}views/{spec.name}/"
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
__all__ = [
|
|
460
|
+
"InvalidParams",
|
|
461
|
+
"ViewNotSupported",
|
|
462
|
+
"ViewSpec",
|
|
463
|
+
"available_views",
|
|
464
|
+
"check_view_permission",
|
|
465
|
+
"clean_params",
|
|
466
|
+
"declared_views",
|
|
467
|
+
"get_view",
|
|
468
|
+
"run_view",
|
|
469
|
+
"view",
|
|
470
|
+
"view_object",
|
|
471
|
+
]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from django.contrib import admin
|
|
4
|
+
|
|
5
|
+
API_DISPLAY_ATTR = "admin_api_display"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def display(function=None, *, boolean=None, ordering=None, description=None, empty_value=None):
|
|
9
|
+
"""Like ``@admin.display`` and also marks the callable as safe to expose in the API.
|
|
10
|
+
|
|
11
|
+
Callables in ``list_display`` are left out of the API unless they are listed in
|
|
12
|
+
``api_list_display`` or decorated with this.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def decorator(func):
|
|
16
|
+
func = admin.display(boolean=boolean, ordering=ordering, description=description, empty_value=empty_value)(func)
|
|
17
|
+
setattr(func, API_DISPLAY_ATTR, True)
|
|
18
|
+
return func
|
|
19
|
+
|
|
20
|
+
if function is None:
|
|
21
|
+
return decorator
|
|
22
|
+
return decorator(function)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def is_api_display(func) -> bool:
|
|
26
|
+
return bool(getattr(func, API_DISPLAY_ATTR, False))
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import html
|
|
4
|
+
|
|
5
|
+
from django.db import router, transaction
|
|
6
|
+
from django.utils.html import strip_tags
|
|
7
|
+
|
|
8
|
+
from .encoders import encode_value
|
|
9
|
+
from .errors import ApiError, PermissionDeniedError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Protected(ApiError):
|
|
13
|
+
status = 409
|
|
14
|
+
code = "protected"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _text(value):
|
|
18
|
+
if isinstance(value, (list, tuple)):
|
|
19
|
+
return [_text(v) for v in value]
|
|
20
|
+
return html.unescape(strip_tags(str(value)))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def deletion_summary(model_admin, request, objs) -> dict:
|
|
24
|
+
"""What deleting ``objs`` would remove, as the admin's delete confirmation page lists it."""
|
|
25
|
+
to_delete, model_count, perms_needed, protected = model_admin.get_deleted_objects(objs, request)
|
|
26
|
+
return {
|
|
27
|
+
"to_delete": _text(to_delete),
|
|
28
|
+
"model_count": {str(k): v for k, v in model_count.items()},
|
|
29
|
+
"perms_needed": sorted(str(p) for p in perms_needed),
|
|
30
|
+
"protected": _text(list(protected)),
|
|
31
|
+
"can_delete": not perms_needed and not protected,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def delete_preview(model_admin, request, obj) -> dict:
|
|
36
|
+
return {"object": encode_value(obj), **deletion_summary(model_admin, request, [obj])}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _log_deletion(model_admin, request, obj):
|
|
40
|
+
if hasattr(model_admin, "log_deletions"): # Django >= 5.1
|
|
41
|
+
model_admin.log_deletions(request, [obj])
|
|
42
|
+
else: # pragma: no cover - Django < 5.1
|
|
43
|
+
model_admin.log_deletion(request, obj, str(obj))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def delete_object(model_admin, request, obj) -> dict:
|
|
47
|
+
preview = delete_preview(model_admin, request, obj)
|
|
48
|
+
if preview["protected"]:
|
|
49
|
+
raise Protected("Related objects are protected.", protected=preview["protected"])
|
|
50
|
+
if preview["perms_needed"]:
|
|
51
|
+
raise PermissionDeniedError(
|
|
52
|
+
"Missing delete permission on related objects.", perms_needed=preview["perms_needed"]
|
|
53
|
+
)
|
|
54
|
+
deleted = encode_value(obj)
|
|
55
|
+
with transaction.atomic(using=router.db_for_write(model_admin.model)):
|
|
56
|
+
_log_deletion(model_admin, request, obj)
|
|
57
|
+
model_admin.delete_model(request, obj)
|
|
58
|
+
return deleted
|
admin_api_mcp/detail.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Serialize one object, and its inlines, the way the admin change form shows it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from django.contrib.admin.utils import flatten_fieldsets, lookup_field
|
|
6
|
+
|
|
7
|
+
from .changelist import _model_field, _name_key
|
|
8
|
+
from .decorators import is_api_display
|
|
9
|
+
from .encoders import encode_field_value, encode_value
|
|
10
|
+
from .resolver import resolve
|
|
11
|
+
from .sensitive import Redactor
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def field_value(obj, field):
|
|
15
|
+
if field.many_to_many:
|
|
16
|
+
return [encode_value(o) for o in getattr(obj, field.name).all()]
|
|
17
|
+
if field.is_relation and (field.many_to_one or field.one_to_one) and field.concrete:
|
|
18
|
+
return encode_value(getattr(obj, field.name))
|
|
19
|
+
return encode_field_value(field, field.value_from_object(obj))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def detail_fields(model_admin, request, obj) -> tuple[list, bool]:
|
|
23
|
+
"""Return (field names, explicit). Explicit = from ``api_detail_fields`` / ``get_api_detail_fields``."""
|
|
24
|
+
explicit = resolve(model_admin, "detail_fields", request, obj)
|
|
25
|
+
if explicit is not None:
|
|
26
|
+
return list(explicit), True
|
|
27
|
+
return flatten_fieldsets(model_admin.get_fieldsets(request, obj)), False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def serialize_values(model_admin, obj, names, explicit) -> dict:
|
|
31
|
+
model = type(obj)
|
|
32
|
+
out = {}
|
|
33
|
+
for name in names:
|
|
34
|
+
field = _model_field(model, name)
|
|
35
|
+
if field is not None:
|
|
36
|
+
out[name] = field_value(obj, field)
|
|
37
|
+
continue
|
|
38
|
+
func = name if callable(name) else getattr(model_admin, name, None) or getattr(model, name, None)
|
|
39
|
+
if explicit or is_api_display(func):
|
|
40
|
+
_f, _attr, value = lookup_field(name, obj, model_admin)
|
|
41
|
+
out[_name_key(name)] = encode_value(value)
|
|
42
|
+
return out
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def inline_prefixes(model_admin, request, obj, change):
|
|
46
|
+
"""``[(prefix, FormSet, inline)]`` with the same prefix rules as ``ModelAdmin._create_formsets``."""
|
|
47
|
+
out = []
|
|
48
|
+
prefixes = {}
|
|
49
|
+
args = [request, obj] if change else [request]
|
|
50
|
+
for FormSet, inline in model_admin.get_formsets_with_inlines(*args):
|
|
51
|
+
prefix = FormSet.get_default_prefix()
|
|
52
|
+
prefixes[prefix] = prefixes.get(prefix, 0) + 1
|
|
53
|
+
if prefixes[prefix] != 1 or not prefix:
|
|
54
|
+
prefix = f"{prefix}-{prefixes[prefix]}"
|
|
55
|
+
out.append((prefix, FormSet, inline))
|
|
56
|
+
return out
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def inline_queryset(FormSet, inline, request, obj):
|
|
60
|
+
qs = inline.get_queryset(request)
|
|
61
|
+
fk = getattr(FormSet, "fk", None)
|
|
62
|
+
if fk is not None:
|
|
63
|
+
return qs.filter(**{fk.name: obj})
|
|
64
|
+
ct_field = getattr(FormSet, "ct_field", None) # generic inlines
|
|
65
|
+
if ct_field is not None:
|
|
66
|
+
from django.contrib.contenttypes.models import ContentType
|
|
67
|
+
|
|
68
|
+
ct = ContentType.objects.get_for_model(obj, for_concrete_model=FormSet.for_concrete_model)
|
|
69
|
+
return qs.filter(**{ct_field.name: ct, FormSet.ct_fk_field.name: obj.pk})
|
|
70
|
+
return qs.none()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def inline_field_names(FormSet, inline, request, obj) -> list:
|
|
74
|
+
fk = getattr(FormSet, "fk", None)
|
|
75
|
+
return [n for n in flatten_fieldsets(inline.get_fieldsets(request, obj)) if fk is None or n != fk.name]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def serialize_inlines(model_admin, request, obj) -> dict:
|
|
79
|
+
out = {}
|
|
80
|
+
for prefix, FormSet, inline in inline_prefixes(model_admin, request, obj, change=True):
|
|
81
|
+
names = inline_field_names(FormSet, inline, request, obj)
|
|
82
|
+
qs = inline_queryset(FormSet, inline, request, obj)
|
|
83
|
+
related = [n for n in names if (f := _model_field(qs.model, n)) is not None and f.many_to_one]
|
|
84
|
+
many = [n for n in names if (f := _model_field(qs.model, n)) is not None and f.many_to_many]
|
|
85
|
+
if related:
|
|
86
|
+
qs = qs.select_related(*related)
|
|
87
|
+
if many:
|
|
88
|
+
qs = qs.prefetch_related(*many)
|
|
89
|
+
if not qs.query.order_by and not qs.ordered:
|
|
90
|
+
qs = qs.order_by("pk")
|
|
91
|
+
redactor = Redactor(inline, request)
|
|
92
|
+
out[prefix] = [
|
|
93
|
+
{"pk": encode_value(row.pk), **redactor.redact(serialize_values(inline, row, names, explicit=False))}
|
|
94
|
+
for row in qs
|
|
95
|
+
]
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def serialize_totals(model_admin, request, obj) -> dict:
|
|
100
|
+
"""The header totals named by ``api_totals`` (field names, admin methods or model attributes)."""
|
|
101
|
+
getter = getattr(model_admin, "get_api_totals", None)
|
|
102
|
+
names = getter(request, obj) if getter else getattr(model_admin, "api_totals", None)
|
|
103
|
+
if not names:
|
|
104
|
+
return {}
|
|
105
|
+
return Redactor(model_admin, request).redact(serialize_values(model_admin, obj, names, explicit=True))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def serialize_object(model_admin, request, obj) -> dict:
|
|
109
|
+
names, explicit = detail_fields(model_admin, request, obj)
|
|
110
|
+
payload = {"pk": encode_value(obj.pk), "str": str(obj)}
|
|
111
|
+
payload.update(Redactor(model_admin, request).redact(serialize_values(model_admin, obj, names, explicit)))
|
|
112
|
+
inlines = serialize_inlines(model_admin, request, obj)
|
|
113
|
+
if inlines:
|
|
114
|
+
payload["inlines"] = inlines
|
|
115
|
+
return payload
|