django-admin-api-mcp 0.1.0a2__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.
Files changed (49) hide show
  1. admin_api/__init__.py +9 -0
  2. admin_api/actions.py +115 -0
  3. admin_api/admin.py +108 -0
  4. admin_api/apps.py +9 -0
  5. admin_api/auth.py +62 -0
  6. admin_api/changelist.py +194 -0
  7. admin_api/checks.py +35 -0
  8. admin_api/contrib/__init__.py +1 -0
  9. admin_api/contrib/subadmin.py +37 -0
  10. admin_api/custom_views.py +458 -0
  11. admin_api/decorators.py +26 -0
  12. admin_api/deletion.py +54 -0
  13. admin_api/detail.py +127 -0
  14. admin_api/encoders.py +59 -0
  15. admin_api/errors.py +44 -0
  16. admin_api/jsonschema.py +216 -0
  17. admin_api/management/__init__.py +0 -0
  18. admin_api/management/commands/__init__.py +0 -0
  19. admin_api/management/commands/create_api_token.py +40 -0
  20. admin_api/management/commands/mcp_serve.py +86 -0
  21. admin_api/mcp/__init__.py +7 -0
  22. admin_api/mcp/bridge.py +71 -0
  23. admin_api/mcp/confirm.py +54 -0
  24. admin_api/mcp/handlers.py +665 -0
  25. admin_api/mcp/server.py +75 -0
  26. admin_api/mcp/sites.py +198 -0
  27. admin_api/mcp/stdio.py +53 -0
  28. admin_api/mcp/tools.py +84 -0
  29. admin_api/mcp/views.py +69 -0
  30. admin_api/middleware.py +18 -0
  31. admin_api/migrations/0001_initial.py +40 -0
  32. admin_api/migrations/__init__.py +0 -0
  33. admin_api/mixins.py +144 -0
  34. admin_api/models.py +113 -0
  35. admin_api/nested.py +122 -0
  36. admin_api/resolver.py +95 -0
  37. admin_api/scopes.py +121 -0
  38. admin_api/services.py +423 -0
  39. admin_api/sites.py +225 -0
  40. admin_api/views/__init__.py +0 -0
  41. admin_api/views/changelist.py +50 -0
  42. admin_api/views/custom.py +31 -0
  43. admin_api/views/detail.py +39 -0
  44. admin_api/views/nested.py +70 -0
  45. admin_api/views/registry.py +15 -0
  46. admin_api/writes.py +479 -0
  47. django_admin_api_mcp-0.1.0a2.dist-info/METADATA +274 -0
  48. django_admin_api_mcp-0.1.0a2.dist-info/RECORD +49 -0
  49. django_admin_api_mcp-0.1.0a2.dist-info/WHEEL +4 -0
admin_api/services.py ADDED
@@ -0,0 +1,423 @@
1
+ """Transport-neutral operations behind the API.
2
+
3
+ Every function takes a Django ``request`` (with ``user``, ``is_api`` and, for list-style
4
+ operations, the changelist query in ``request.GET``) and returns a JSON-serializable ``dict``,
5
+ or raises :class:`admin_api.errors.ApiError`. The REST views and the MCP tools are thin
6
+ adapters over these functions, so both surfaces share permissions, validation and output.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from django.apps import apps
12
+ from django.contrib.admin.utils import unquote
13
+ from django.urls import NoReverseMatch, reverse
14
+
15
+ from . import scopes
16
+ from .changelist import (
17
+ PER_PAGE_PARAM,
18
+ SHAPE_PARAM,
19
+ SHAPES,
20
+ BadLookup,
21
+ build_changelist,
22
+ describe_columns,
23
+ describe_filters,
24
+ get_columns,
25
+ split_api_params,
26
+ )
27
+ from .encoders import encode_value
28
+ from .errors import NotFound, PermissionDeniedError
29
+ from .nested import BadParents, ModelPath, Target
30
+ from .resolver import resolve
31
+
32
+
33
+ # --------------------------------------------------------------------------------------------
34
+ # lookup
35
+ # --------------------------------------------------------------------------------------------
36
+ def get_model_admin(api_site, request, app_label: str, model_name: str, *, segments=(), parents=()):
37
+ """The API admin for ``app_label.model_name`` (or the admin nested under it at ``segments``,
38
+ inside the objects ``parents``), if exposed and viewable by ``request.user``.
39
+
40
+ Sets ``request.admin_api_target`` (:class:`admin_api.nested.Target`). For a nested admin,
41
+ also prepares ``request`` for it (e.g. ``request.subadmin``): every ancestor is loaded through
42
+ its admin and must be viewable.
43
+ """
44
+ path = ModelPath(app_label, model_name, tuple(segments))
45
+ chain = api_site.get_admin_chain(path)
46
+ if chain is None:
47
+ raise NotFound(f"No API for {path.label}.")
48
+ model_admin = chain[-1]
49
+ parents = list(parents or ())
50
+ if len(parents) != path.depth:
51
+ raise BadParents(
52
+ f"{path.label} needs {path.depth} parent pk(s), one per level, got {len(parents)}."
53
+ if path.depth
54
+ else f"{path.label} is not nested: no parents expected."
55
+ )
56
+ if path.depth:
57
+ api_site.prepare_nested_request(model_admin, request, parents)
58
+ if not model_admin.has_view_or_change_permission(request):
59
+ raise PermissionDeniedError()
60
+ # Second line of defense: also enforced in ApiAdminMixin.has_*_permission, but an admin may
61
+ # override those without calling super().
62
+ scopes.check(request, model_admin.opts, "view")
63
+ request.admin_api_target = Target(api_site, path, parents, chain)
64
+ return model_admin
65
+
66
+
67
+ def get_model_admin_by_label(api_site, request, label: str, parents=()):
68
+ """Same as :func:`get_model_admin` for ``"app_label.model_name"`` or a nested path
69
+ ``"app_label.model_name/child/grandchild"``."""
70
+ path = ModelPath.parse(label)
71
+ return get_model_admin(api_site, request, path.app_label, path.model_name, segments=path.segments, parents=parents)
72
+
73
+
74
+ def get_object(model_admin, request, object_id):
75
+ obj = model_admin.get_object(request, unquote(str(object_id)))
76
+ if obj is None:
77
+ raise NotFound(f"{model_admin.model._meta.verbose_name} with pk {object_id!r} does not exist.")
78
+ return obj
79
+
80
+
81
+ # --------------------------------------------------------------------------------------------
82
+ # read
83
+ # --------------------------------------------------------------------------------------------
84
+ def _api_base(api_site):
85
+ try:
86
+ return reverse(f"{api_site.name}:index")
87
+ except NoReverseMatch: # API urls not mounted (e.g. MCP only)
88
+ return None
89
+
90
+
91
+ def registry(api_site, request) -> dict:
92
+ """The apps/models the current user may use, with their permissions.
93
+
94
+ Nested admins are listed too, after a viewable parent, with ``path``, ``nested_under`` (the
95
+ model of each parent pk) and ``url_template`` (``{0}``, ``{1}``… stand for the parent pks).
96
+ """
97
+ base = _api_base(api_site)
98
+ app_dict: dict[str, dict] = {}
99
+
100
+ def add(model_admin, path, ancestors):
101
+ if not model_admin.has_module_permission(request):
102
+ return
103
+ perms = model_admin.get_model_perms(request)
104
+ if not any(perms.values()):
105
+ return
106
+ opts = model_admin.model._meta
107
+ app = app_dict.setdefault(
108
+ opts.app_label,
109
+ {
110
+ "app_label": opts.app_label,
111
+ "name": str(apps.get_app_config(opts.app_label).verbose_name),
112
+ "models": [],
113
+ },
114
+ )
115
+ entry = {
116
+ "model": opts.model_name,
117
+ "object_name": opts.object_name,
118
+ "name": str(opts.verbose_name),
119
+ "name_plural": str(opts.verbose_name_plural),
120
+ "perms": perms,
121
+ "url": path.url(base) if base and not path.depth else None,
122
+ }
123
+ if path.depth:
124
+ entry["path"] = path.label
125
+ entry["nested_under"] = list(ancestors)
126
+ entry["url_template"] = path.url_template(base) if base else None
127
+ app["models"].append(entry)
128
+ # children need a viewable parent object
129
+ if not model_admin.has_view_or_change_permission(request):
130
+ return
131
+ label = f"{opts.app_label}.{opts.model_name}"
132
+ for segment, child in api_site.get_api_children(model_admin).items():
133
+ add(child, path.child(segment), [*ancestors, label])
134
+
135
+ for model, model_admin in api_site.exposed_admins():
136
+ add(model_admin, ModelPath(model._meta.app_label, model._meta.model_name), [])
137
+ app_list = sorted(app_dict.values(), key=lambda a: a["name"].lower())
138
+ for app in app_list:
139
+ app["models"].sort(key=lambda m: (m["name"].lower(), m.get("path", "")))
140
+ return {"version": api_site.version, "apps": app_list}
141
+
142
+
143
+ def child_links(request, model_admin, pk=None) -> list[dict]:
144
+ """The admins nested under ``model_admin`` that ``request.user`` may view.
145
+
146
+ ``[{"segment", "model" (path), "admin", "name", "name_plural"}]``, plus ``"parents"`` and
147
+ ``"url"`` (REST, ``None`` if not mounted) when the (encoded) ``pk`` of an object is given.
148
+ No queries.
149
+ """
150
+ target = getattr(request, "admin_api_target", None)
151
+ if target is None:
152
+ return []
153
+ base = _api_base(target.api_site) if pk is not None else None
154
+ out = []
155
+ for segment, child in target.api_site.get_api_children(model_admin).items():
156
+ if not child.has_view_or_change_permission(request): # includes token scopes
157
+ continue
158
+ path = target.path.child(segment)
159
+ opts = child.model._meta
160
+ link = {
161
+ "segment": segment,
162
+ "model": path.label,
163
+ "admin": child,
164
+ "name": str(opts.verbose_name),
165
+ "name_plural": str(opts.verbose_name_plural),
166
+ }
167
+ if pk is not None:
168
+ link["parents"] = [*target.parents, pk]
169
+ link["url"] = path.url(base, link["parents"]) if base else None
170
+ out.append(link)
171
+ return out
172
+
173
+
174
+ def changelist(api_site, model_admin, request) -> dict:
175
+ """Django's changelist as data. Filters, search, ordering and paging come from ``request.GET``
176
+ in the admin's own format; ``_shape`` and ``_per_page`` are API-owned."""
177
+ api_params = split_api_params(request)
178
+
179
+ shape = api_params.get(SHAPE_PARAM) or "objects"
180
+ if shape not in SHAPES:
181
+ raise BadLookup(f"{SHAPE_PARAM} must be one of: {', '.join(SHAPES)}.")
182
+ per_page = None
183
+ if PER_PAGE_PARAM in api_params:
184
+ try:
185
+ per_page = int(api_params[PER_PAGE_PARAM])
186
+ except (TypeError, ValueError):
187
+ per_page = 0
188
+ if not 1 <= per_page <= api_site.max_page_size:
189
+ raise BadLookup(f"{PER_PAGE_PARAM} must be between 1 and {api_site.max_page_size}.")
190
+
191
+ columns = get_columns(model_admin, request)
192
+ cl = build_changelist(model_admin, request, columns, per_page=per_page)
193
+
194
+ pk_name = model_admin.model._meta.pk.attname
195
+ rows = [
196
+ [encode_value(getattr(obj, pk_name))] + [c.value(obj, model_admin) for c in columns] for obj in cl.result_list
197
+ ]
198
+ keys = ["pk"] + [c.key for c in columns]
199
+
200
+ showing_all = (cl.show_all and cl.can_show_all) or not cl.multi_page
201
+ pages = 1 if showing_all else cl.paginator.num_pages
202
+ page = 1 if showing_all else cl.page_num
203
+ payload = {
204
+ "count": cl.result_count,
205
+ "page": page,
206
+ "pages": pages,
207
+ "per_page": cl.list_per_page,
208
+ "next": _page_url(request, page + 1) if page < pages else None,
209
+ "previous": _page_url(request, page - 1) if page > 1 else None,
210
+ }
211
+ if shape == "columnar":
212
+ payload["columns"] = keys
213
+ payload["rows"] = rows
214
+ else:
215
+ payload["results"] = [dict(zip(keys, row)) for row in rows]
216
+ return payload
217
+
218
+
219
+ def _page_url(request, page):
220
+ from django.contrib.admin.views.main import PAGE_VAR
221
+
222
+ query = request.api_query.copy()
223
+ query[PAGE_VAR] = page
224
+ return f"{request.path}?{query.urlencode()}"
225
+
226
+
227
+ def schema(api_site, model_admin, request) -> dict:
228
+ """What the list endpoint accepts and returns, plus form fields and actions."""
229
+ from django.contrib.admin.views.main import ALL_VAR, ORDER_VAR, PAGE_VAR, SEARCH_VAR
230
+
231
+ from .actions import describe_actions
232
+ from .jsonschema import input_schemas
233
+ from .writes import describe_form
234
+
235
+ split_api_params(request)
236
+ columns = get_columns(model_admin, request)
237
+ cl = build_changelist(model_admin, request, columns, schema_only=True)
238
+ opts = model_admin.model._meta
239
+ search_fields = list(model_admin.get_search_fields(request) or ())
240
+ payload = {
241
+ "model": {
242
+ "app_label": opts.app_label,
243
+ "model": opts.model_name,
244
+ "name": str(opts.verbose_name),
245
+ "name_plural": str(opts.verbose_name_plural),
246
+ "pk": opts.pk.attname,
247
+ },
248
+ "perms": model_admin.get_model_perms(request),
249
+ "columns": describe_columns(columns, model_admin, request),
250
+ "filters": describe_filters(cl),
251
+ "search": {
252
+ "enabled": bool(search_fields),
253
+ "param": SEARCH_VAR,
254
+ "help_text": str(model_admin.search_help_text or "") or None,
255
+ },
256
+ "ordering": {
257
+ "param": ORDER_VAR,
258
+ "format": "dot-separated order_index values, prefix '-' for descending, e.g. '2.-0'",
259
+ "default": [str(o) for o in (model_admin.get_ordering(request) or ())],
260
+ },
261
+ "date_hierarchy": model_admin.date_hierarchy,
262
+ "pagination": {
263
+ "page_param": PAGE_VAR,
264
+ "per_page": resolve(model_admin, "list_per_page", request),
265
+ "per_page_param": PER_PAGE_PARAM,
266
+ "max_per_page": api_site.max_page_size,
267
+ "show_all_param": ALL_VAR,
268
+ "max_show_all": model_admin.list_max_show_all,
269
+ },
270
+ "shapes": {"param": SHAPE_PARAM, "values": list(SHAPES), "default": "objects"},
271
+ "form": describe_form(model_admin, request) if model_admin.has_add_permission(request) else None,
272
+ "input_schema": input_schemas(model_admin, request),
273
+ "actions": describe_actions(model_admin, request),
274
+ }
275
+ payload["views"] = describe_views(model_admin, request)
276
+ target = getattr(request, "admin_api_target", None)
277
+ if target is not None and target.path.depth:
278
+ payload["model"]["path"] = target.path.label
279
+ payload["model"]["parents"] = list(target.parents)
280
+ children = child_links(request, model_admin)
281
+ if children:
282
+ payload["children"] = [{k: link[k] for k in ("segment", "model", "name", "name_plural")} for link in children]
283
+ return payload
284
+
285
+
286
+ def _changelist_url(request):
287
+ target = getattr(request, "admin_api_target", None)
288
+ if target is None:
289
+ return None
290
+ base = _api_base(target.api_site)
291
+ return target.path.url(base, target.parents) if base else None
292
+
293
+
294
+ def describe_views(model_admin, request) -> list[dict]:
295
+ """The custom views (``@admin_api.view``) ``request.user`` may run, with their REST url
296
+ (``{pk}`` stands for the object of a detail view)."""
297
+ from .custom_views import available_views
298
+
299
+ base = _changelist_url(request)
300
+ out = []
301
+ for spec in available_views(model_admin, request):
302
+ entry = spec.describe()
303
+ entry["methods"] = list(spec.methods)
304
+ if base is not None:
305
+ entry["url"] = f"{base}{{pk}}/views/{spec.name}/" if spec.detail else f"{base}views/{spec.name}/"
306
+ out.append(entry)
307
+ return out
308
+
309
+
310
+ def object_views(model_admin, request, obj, *, mcp=False, read_only=False) -> list:
311
+ """The detail views ``request.user`` may run on ``obj``."""
312
+ from .custom_views import available_views, has_view_permission
313
+
314
+ return [
315
+ spec
316
+ for spec in available_views(model_admin, request, mcp=mcp, read_only=read_only)
317
+ if spec.detail and has_view_permission(model_admin, request, spec, obj)
318
+ ]
319
+
320
+
321
+ def detail(model_admin, request, object_id) -> dict:
322
+ from .custom_views import view_url
323
+ from .detail import serialize_object
324
+
325
+ obj = get_object(model_admin, request, object_id)
326
+ if not model_admin.has_view_or_change_permission(request, obj):
327
+ raise PermissionDeniedError()
328
+ payload = serialize_object(model_admin, request, obj)
329
+ children = child_links(request, model_admin, payload["pk"])
330
+ if children:
331
+ payload["children"] = {link["segment"]: link["url"] for link in children}
332
+ views = object_views(model_admin, request, obj)
333
+ if views and "views" not in payload: # a model field named "views" wins
334
+ base = _changelist_url(request)
335
+ payload["views"] = {spec.name: view_url(spec, base, obj.pk) for spec in views}
336
+ return payload
337
+
338
+
339
+ # --------------------------------------------------------------------------------------------
340
+ # write
341
+ # --------------------------------------------------------------------------------------------
342
+ def _reloaded(model_admin, request, obj):
343
+ """``obj`` as stored after the save: signals and DB expressions may have changed it behind
344
+ the instance's back."""
345
+ fresh = model_admin.get_queryset(request).filter(pk=obj.pk).first()
346
+ if fresh is None: # saved, but outside the API queryset
347
+ obj.refresh_from_db()
348
+ return obj
349
+ return fresh
350
+
351
+
352
+ def _saved(model_admin, request, result, messages) -> dict:
353
+ from .detail import serialize_object, serialize_totals
354
+
355
+ obj = _reloaded(model_admin, request, result.obj)
356
+ payload = serialize_object(model_admin, request, obj)
357
+ totals = serialize_totals(model_admin, request, obj)
358
+ if totals:
359
+ payload["totals"] = totals
360
+ if messages:
361
+ payload["messages"] = messages
362
+ return payload
363
+
364
+
365
+ def _load(payload):
366
+ """Payloads may be passed lazily (a callable) so permission checks run before body parsing."""
367
+ return payload() if callable(payload) else payload
368
+
369
+
370
+ def create(model_admin, request, payload) -> dict:
371
+ from .writes import save_from_payload
372
+
373
+ if not model_admin.has_add_permission(request):
374
+ raise PermissionDeniedError()
375
+ scopes.check(request, model_admin.opts, "add")
376
+ result, messages = save_from_payload(model_admin, request, None, _load(payload), change=False, partial=False)
377
+ return _saved(model_admin, request, result, messages)
378
+
379
+
380
+ def update(model_admin, request, object_id, payload, *, partial: bool) -> dict:
381
+ from .writes import save_from_payload
382
+
383
+ obj = get_object(model_admin, request, object_id)
384
+ if not model_admin.has_change_permission(request, obj):
385
+ raise PermissionDeniedError()
386
+ scopes.check(request, model_admin.opts, "change")
387
+ result, messages = save_from_payload(model_admin, request, obj, _load(payload), change=True, partial=partial)
388
+ return _saved(model_admin, request, result, messages)
389
+
390
+
391
+ def delete(model_admin, request, object_id) -> dict:
392
+ from .deletion import delete_object
393
+
394
+ obj = get_object(model_admin, request, object_id)
395
+ if not model_admin.has_delete_permission(request, obj):
396
+ raise PermissionDeniedError()
397
+ scopes.check(request, model_admin.opts, "delete")
398
+ return {"deleted": delete_object(model_admin, request, obj)}
399
+
400
+
401
+ def delete_preview(model_admin, request, object_id) -> dict:
402
+ from .deletion import delete_preview as _preview
403
+
404
+ obj = get_object(model_admin, request, object_id)
405
+ if not model_admin.has_delete_permission(request, obj):
406
+ raise PermissionDeniedError()
407
+ scopes.check(request, model_admin.opts, "delete")
408
+ return _preview(model_admin, request, obj)
409
+
410
+
411
+ def run_view(model_admin, request, name: str, *, object_id=None, data=None) -> dict:
412
+ """Run a custom view (``@admin_api.view``); see :func:`admin_api.custom_views.run_view`."""
413
+ from .custom_views import run_view as _run
414
+
415
+ return _run(model_admin, request, name, object_id=object_id, data=data)
416
+
417
+
418
+ def run_action(model_admin, request, name: str, payload: dict) -> dict:
419
+ """Run an admin action on ``{"pks": [...]}`` or ``{"all": true}``; with ``all``, the
420
+ changelist filters in ``request.GET`` narrow the queryset."""
421
+ from .actions import run_action as _run
422
+
423
+ return _run(model_admin, request, name, payload)
admin_api/sites.py ADDED
@@ -0,0 +1,225 @@
1
+ from __future__ import annotations
2
+
3
+ from functools import wraps
4
+ from weakref import WeakSet
5
+
6
+ from django.contrib import admin
7
+ from django.urls import path
8
+ from django.views.decorators.csrf import csrf_exempt
9
+
10
+ from .auth import SessionAuthenticator, TokenAuthenticator
11
+ from .contrib.subadmin import SubAdminAdapter
12
+ from .errors import ApiError, MethodNotAllowed, NotAuthenticated, PermissionDeniedError
13
+ from .mixins import ApiAdminMixin
14
+
15
+ _all_sites: WeakSet = WeakSet()
16
+
17
+
18
+ def all_api_sites():
19
+ return list(_all_sites)
20
+
21
+
22
+ class AdminApiSite:
23
+ """Exposes the ModelAdmins of an existing ``AdminSite`` as a JSON API.
24
+
25
+ No separate registration: every admin registered on ``admin_site`` is exposed unless
26
+ ``is_exposed()`` says otherwise (default: ``model_admin.api_enabled`` is not ``False``).
27
+ Subclass to change site-wide behaviour, like you would subclass ``AdminSite``.
28
+ """
29
+
30
+ authenticators = [TokenAuthenticator, SessionAuthenticator]
31
+ version = "v1"
32
+ max_page_size = 500
33
+ # Nested admins (see admin_api.nested). Duck-typed: inactive unless the library is used.
34
+ nested_adapters = [SubAdminAdapter]
35
+
36
+ def __init__(
37
+ self,
38
+ admin_site: admin.AdminSite | None = None,
39
+ *,
40
+ name: str = "admin_api",
41
+ version: str | None = None,
42
+ register_token_admin: bool = True,
43
+ ):
44
+ self.admin_site = admin_site or admin.site
45
+ self.name = name
46
+ self._api_admins: dict = {}
47
+ self._adapters = [adapter() for adapter in self.nested_adapters]
48
+ if version is not None:
49
+ self.version = version
50
+ if register_token_admin:
51
+ self.register_token_admin()
52
+ _all_sites.add(self)
53
+
54
+ def register_token_admin(self):
55
+ """Register the API token admin on the wrapped admin site (once)."""
56
+ from .admin import ApiTokenAdmin
57
+ from .auth import get_token_model
58
+
59
+ model = get_token_model()
60
+ if not self.admin_site.is_registered(model):
61
+ self.admin_site.register(model, ApiTokenAdmin)
62
+
63
+ # --- policy hooks -----------------------------------------------------------------------
64
+ def is_exposed(self, model_admin) -> bool:
65
+ return getattr(model_admin, "api_enabled", True) is not False
66
+
67
+ def has_permission(self, request) -> bool:
68
+ return self.admin_site.has_permission(request)
69
+
70
+ def authenticate(self, request):
71
+ for authenticator_class in self.authenticators:
72
+ user = authenticator_class().authenticate(request)
73
+ if user is not None:
74
+ request.user = user
75
+ return user
76
+ raise NotAuthenticated()
77
+
78
+ def get_api_admin(self, model_admin):
79
+ """The admin instance the API uses.
80
+
81
+ Admins that already use ``ApiAdminMixin`` are used as-is. Others get a cached runtime
82
+ subclass ``(ApiAdminMixin, TheirAdmin)`` so that Django's internal getter calls
83
+ (ChangeList → get_queryset / get_search_results / get_ordering, get_form →
84
+ get_fieldsets, ...) see the api_ twins too. The mixin is therefore optional.
85
+ """
86
+ if isinstance(model_admin, ApiAdminMixin):
87
+ return model_admin
88
+ adapter = self.get_nested_adapter(model_admin)
89
+ # nested admins are cached per instance: the same class may be mounted under several parents
90
+ key = model_admin.model if adapter is None else ("nested", id(model_admin))
91
+ cached = self._api_admins.get(key)
92
+ if cached is None or cached[0] is not model_admin:
93
+ cls = type(model_admin)
94
+ api_cls = type(f"Api{cls.__name__}", (ApiAdminMixin, cls), {"__module__": cls.__module__})
95
+ if adapter is None:
96
+ api_admin = api_cls(model_admin.model, model_admin.admin_site)
97
+ else:
98
+ api_admin = api_cls(*adapter.init_args(model_admin))
99
+ cached = (model_admin, api_admin)
100
+ self._api_admins[key] = cached
101
+ return cached[1]
102
+
103
+ def get_model_admin(self, app_label: str, model_name: str):
104
+ for model, model_admin in self.admin_site._registry.items():
105
+ opts = model._meta
106
+ if opts.app_label == app_label and opts.model_name == model_name:
107
+ if self.is_exposed(model_admin):
108
+ return self.get_api_admin(model_admin)
109
+ break
110
+ return None
111
+
112
+ def exposed_admins(self):
113
+ for model, model_admin in self.admin_site._registry.items():
114
+ if self.is_exposed(model_admin):
115
+ yield model, self.get_api_admin(model_admin)
116
+
117
+ # --- nested admins (admin_api.nested) -----------------------------------------------------
118
+ def get_nested_adapter(self, model_admin):
119
+ """The adapter handling ``model_admin`` as a nested admin, or ``None`` for top-level admins."""
120
+ return next((a for a in self._adapters if a.is_child(model_admin)), None)
121
+
122
+ def get_api_children(self, model_admin) -> dict:
123
+ """``{segment: api_admin}`` of the exposed admins nested directly under ``model_admin``."""
124
+ children = {}
125
+ for adapter in self._adapters:
126
+ for child in adapter.get_children(model_admin):
127
+ segment = adapter.segment(child)
128
+ if segment not in children and self.is_exposed(child):
129
+ children[segment] = self.get_api_admin(child)
130
+ return children
131
+
132
+ def get_admin_chain(self, path) -> list | None:
133
+ """API admins from the root to the target of ``path`` (a :class:`~admin_api.nested.ModelPath`),
134
+ or ``None`` when any level is missing or not exposed (hiding an admin hides its children)."""
135
+ root = self.get_model_admin(path.app_label, path.model_name)
136
+ if root is None:
137
+ return None
138
+ chain = [root]
139
+ for segment in path.segments:
140
+ child = self.get_api_children(chain[-1]).get(segment)
141
+ if child is None:
142
+ return None
143
+ chain.append(child)
144
+ return chain
145
+
146
+ def prepare_nested_request(self, model_admin, request, parents: list) -> None:
147
+ """Let the nested ``model_admin``'s library load and check the ancestors for ``request``."""
148
+ adapter = self.get_nested_adapter(model_admin)
149
+ if adapter is not None:
150
+ adapter.prepare_request(model_admin, request, parents)
151
+
152
+ # --- view plumbing ----------------------------------------------------------------------
153
+ def api_view(self, view, methods=("GET",)):
154
+ """Wrap a view: mark request as API, check method, authenticate, check site permission,
155
+ and turn ``ApiError`` into JSON. CSRF is enforced by the session authenticator only."""
156
+
157
+ @csrf_exempt
158
+ @wraps(view)
159
+ def inner(request, *args, **kwargs):
160
+ request.is_api = True
161
+ try:
162
+ if request.method not in methods:
163
+ raise MethodNotAllowed(f"Allowed: {', '.join(methods)}")
164
+ self.authenticate(request)
165
+ if not self.has_permission(request):
166
+ raise PermissionDeniedError()
167
+ return view(request, *args, **kwargs)
168
+ except ApiError as exc:
169
+ return exc.as_response()
170
+
171
+ return inner
172
+
173
+ def get_urls(self):
174
+ from .views.changelist import ActionView, ChangeListView, SchemaView
175
+ from .views.custom import CustomViewView
176
+ from .views.detail import DeletePreviewView, ObjectView
177
+ from .views.nested import NESTED_METHODS, nested_view
178
+ from .views.registry import RegistryView
179
+
180
+ v = self.version
181
+ model = f"{v}/<str:app_label>/<str:model_name>/"
182
+ return [
183
+ path(f"{v}/", self.api_view(RegistryView.as_view(api_site=self)), name="index"),
184
+ path(
185
+ model,
186
+ self.api_view(ChangeListView.as_view(api_site=self), methods=("GET", "POST")),
187
+ name="changelist",
188
+ ),
189
+ path(f"{model}schema/", self.api_view(SchemaView.as_view(api_site=self)), name="schema"),
190
+ path(
191
+ f"{model}actions/<str:action_name>/",
192
+ self.api_view(ActionView.as_view(api_site=self), methods=("POST",)),
193
+ name="action",
194
+ ),
195
+ path(
196
+ f"{model}views/<str:view_name>/",
197
+ self.api_view(CustomViewView.as_view(api_site=self), methods=("GET", "POST")),
198
+ name="view",
199
+ ),
200
+ path(
201
+ f"{model}<str:object_id>/views/<str:view_name>/",
202
+ self.api_view(CustomViewView.as_view(api_site=self), methods=("GET", "POST")),
203
+ name="object_view",
204
+ ),
205
+ path(
206
+ f"{model}<str:object_id>/",
207
+ self.api_view(ObjectView.as_view(api_site=self), methods=("GET", "PATCH", "PUT", "DELETE")),
208
+ name="object",
209
+ ),
210
+ path(
211
+ f"{model}<str:object_id>/delete-preview/",
212
+ self.api_view(DeletePreviewView.as_view(api_site=self)),
213
+ name="delete_preview",
214
+ ),
215
+ # nested admins: <pk>/<child>/[<pk>/<child>/…] then the same tails as above
216
+ path(
217
+ f"{model}<path:nested>/",
218
+ self.api_view(nested_view(self), methods=NESTED_METHODS),
219
+ name="nested",
220
+ ),
221
+ ]
222
+
223
+ @property
224
+ def urls(self):
225
+ return self.get_urls(), "admin_api", self.name
File without changes