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
admin_api_mcp/checks.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from django.conf import settings
|
|
2
|
+
from django.core import checks
|
|
3
|
+
|
|
4
|
+
MIDDLEWARE_PATH = "admin_api_mcp.middleware.ApiRequestMiddleware"
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@checks.register()
|
|
8
|
+
def check_middleware(app_configs=None, **kwargs):
|
|
9
|
+
if MIDDLEWARE_PATH not in getattr(settings, "MIDDLEWARE", []):
|
|
10
|
+
return [
|
|
11
|
+
checks.Error(
|
|
12
|
+
f"'{MIDDLEWARE_PATH}' must be in MIDDLEWARE.",
|
|
13
|
+
hint="It sets request.is_api = False on every request so admin code can branch on it.",
|
|
14
|
+
id="admin_api_mcp.E001",
|
|
15
|
+
)
|
|
16
|
+
]
|
|
17
|
+
return []
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@checks.register(checks.Tags.urls)
|
|
21
|
+
def check_mcp_view_tools(app_configs=None, **kwargs):
|
|
22
|
+
"""Names of the views published as MCP tools (``mcp_tool=``) must be unique per MCP site."""
|
|
23
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
24
|
+
from django.urls import get_resolver
|
|
25
|
+
|
|
26
|
+
get_resolver().url_patterns # noqa: B018 (import the URLconf, which creates the sites)
|
|
27
|
+
from .mcp.sites import all_mcp_sites
|
|
28
|
+
|
|
29
|
+
errors = []
|
|
30
|
+
for site in all_mcp_sites():
|
|
31
|
+
try:
|
|
32
|
+
site.get_tools()
|
|
33
|
+
except ImproperlyConfigured as exc:
|
|
34
|
+
errors.append(checks.Error(str(exc), obj=site, id="admin_api_mcp.E002"))
|
|
35
|
+
return errors
|
admin_api_mcp/confirm.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Confirm tokens for ``AdminApiSite(require_dry_run=True)``, used by REST and MCP through the services.
|
|
2
|
+
|
|
3
|
+
A token is a signed random ``jti`` stored in :class:`admin_api_mcp.models.McpConfirmation` with a SHA-256
|
|
4
|
+
fingerprint of the user, API token, operation, arguments and stored state of the write it allows.
|
|
5
|
+
The real write spends it in one conditional UPDATE: once, while that state is unchanged.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import secrets
|
|
13
|
+
from datetime import timedelta
|
|
14
|
+
|
|
15
|
+
from django.core import signing
|
|
16
|
+
from django.db import router
|
|
17
|
+
from django.utils import timezone
|
|
18
|
+
|
|
19
|
+
from .errors import ApiError
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DryRunRequired(ApiError):
|
|
23
|
+
"""A gated write was called without a confirm token."""
|
|
24
|
+
|
|
25
|
+
status = 409
|
|
26
|
+
code = "dry_run_required"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class InvalidConfirmToken(ApiError):
|
|
30
|
+
"""The confirm token is expired, used, forged, or for another write or state."""
|
|
31
|
+
|
|
32
|
+
status = 409
|
|
33
|
+
code = "invalid_confirm_token"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def object_state(obj, *, lock: bool = False) -> dict | None:
|
|
37
|
+
"""The stored row of ``obj`` (all concrete fields, read fresh from the database), or ``None``.
|
|
38
|
+
``lock`` selects it FOR UPDATE (inside the caller's transaction)."""
|
|
39
|
+
if obj is None:
|
|
40
|
+
return None
|
|
41
|
+
model = type(obj)
|
|
42
|
+
rows = model._base_manager.using(router.db_for_write(model)).filter(pk=obj.pk)
|
|
43
|
+
return (rows.select_for_update() if lock else rows).values().first()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def write_state(model_admin, request, obj, *, lock: bool = False) -> dict:
|
|
47
|
+
"""What a confirm token pins: the object's stored row and the admin's extra state, such as
|
|
48
|
+
the last row of a log the write appends to (``get_mcp_confirm_state``)."""
|
|
49
|
+
return {"row": object_state(obj, lock=lock), "extra": model_admin.get_mcp_confirm_state(request, obj)}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def fingerprint(request, operation: str, scope: dict, state) -> str:
|
|
53
|
+
"""SHA-256 of who writes (user, API token), the operation, its ``scope`` and the ``state`` it depends on."""
|
|
54
|
+
token = getattr(request, "api_token", None)
|
|
55
|
+
body = [request.user.pk, getattr(token, "pk", None), operation, scope, state]
|
|
56
|
+
encode = lambda v: bytes(v).hex() if isinstance(v, (bytes, memoryview)) else str(v)
|
|
57
|
+
return hashlib.sha256(json.dumps(body, sort_keys=True, default=encode).encode()).hexdigest()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _model():
|
|
61
|
+
"""The confirmation model (imported late: this module loads before the app registry)."""
|
|
62
|
+
from .models import McpConfirmation
|
|
63
|
+
|
|
64
|
+
return McpConfirmation
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def issue(api_site, request, operation: str, scope: dict, state) -> str:
|
|
68
|
+
"""A new token for this write on ``api_site``; expired rows are deleted on the way."""
|
|
69
|
+
model, now = _model(), timezone.now()
|
|
70
|
+
model.objects.filter(expires_at__lt=now).delete()
|
|
71
|
+
jti = secrets.token_urlsafe(32)
|
|
72
|
+
expires_at = now + timedelta(seconds=max(api_site.confirm_token_max_age, 0))
|
|
73
|
+
model.objects.create(jti=jti, fingerprint=fingerprint(request, operation, scope, state), expires_at=expires_at)
|
|
74
|
+
return signing.TimestampSigner(salt=api_site.confirm_salt).sign(jti)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def verify(api_site, token, request, operation: str, scope: dict, state) -> None:
|
|
78
|
+
"""Spend ``token`` for this write or raise. A token that does not match is left unspent."""
|
|
79
|
+
try:
|
|
80
|
+
jti = signing.TimestampSigner(salt=api_site.confirm_salt).unsign(
|
|
81
|
+
str(token), max_age=api_site.confirm_token_max_age
|
|
82
|
+
)
|
|
83
|
+
except signing.SignatureExpired:
|
|
84
|
+
raise InvalidConfirmToken("The confirm_token has expired. Repeat the dry run.") from None
|
|
85
|
+
except signing.BadSignature:
|
|
86
|
+
jti = None
|
|
87
|
+
model = _model()
|
|
88
|
+
expected = fingerprint(request, operation, scope, state)
|
|
89
|
+
if jti and model.objects.filter(jti=jti, fingerprint=expected, used_at__isnull=True).update(used_at=timezone.now()):
|
|
90
|
+
return
|
|
91
|
+
row = model.objects.filter(jti=jti).first() if jti else None
|
|
92
|
+
if row is not None and row.fingerprint == expected:
|
|
93
|
+
raise InvalidConfirmToken("The confirm_token was already used. Repeat the dry run.")
|
|
94
|
+
raise InvalidConfirmToken(
|
|
95
|
+
"The confirm_token does not belong to this write, or the object changed since the dry run. "
|
|
96
|
+
"Repeat the dry run with exactly the arguments you are about to save."
|
|
97
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Optional integrations with third-party admin libraries."""
|
|
File without changes
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from django.apps import AppConfig
|
|
2
|
+
from django.db.models.signals import post_delete, post_migrate, post_save
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class SearchConfig(AppConfig):
|
|
6
|
+
name = "admin_api_mcp.contrib.search"
|
|
7
|
+
label = "admin_api_mcp_search"
|
|
8
|
+
verbose_name = "Admin API search"
|
|
9
|
+
default_auto_field = "django.db.models.BigAutoField"
|
|
10
|
+
|
|
11
|
+
def ready(self):
|
|
12
|
+
from ...mcp.sites import AdminMcpSite
|
|
13
|
+
from . import checks # noqa: F401 (registers system checks)
|
|
14
|
+
from .backend import SearchEntityBackend
|
|
15
|
+
from .indexer import on_post_delete, on_post_migrate, on_post_save
|
|
16
|
+
|
|
17
|
+
AdminMcpSite.entity_backend_class = SearchEntityBackend # sites that set their own keep it
|
|
18
|
+
|
|
19
|
+
post_save.connect(on_post_save, dispatch_uid="admin_api_mcp_search_post_save")
|
|
20
|
+
post_delete.connect(on_post_delete, dispatch_uid="admin_api_mcp_search_post_delete")
|
|
21
|
+
post_migrate.connect(on_post_migrate, sender=self, dispatch_uid="admin_api_mcp_search_post_migrate")
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""The ``resolve_entities`` backend over the configured search engine: scopes from the tool's allowed
|
|
2
|
+
targets, candidates from the engine, scores from the tool's own match rules (see docs/DESIGN.md)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from ...mcp.resolve import CODE_FIELDS, CONFIDENCE, DEFAULT_LIMIT, Hit, _languages, match_text
|
|
7
|
+
from .conf import get_engine
|
|
8
|
+
from .engines.base import MODEL, OBJECT, Scope, SearchQuery
|
|
9
|
+
from .fold import fold
|
|
10
|
+
from .indexer import content_type_of, local_fields, model_names, owned_models
|
|
11
|
+
|
|
12
|
+
FUZZY_WEIGHT = 0.6 # a fuzzy hit's confidence is the engine's own score (0 to 1) times this
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SearchEntityBackend:
|
|
16
|
+
"""Finds ``resolve_entities`` candidates in the search index (``admin_api_mcp.contrib.search``)."""
|
|
17
|
+
|
|
18
|
+
post_filter_factor = 5
|
|
19
|
+
post_filter_pages = 3
|
|
20
|
+
|
|
21
|
+
def __init__(self, site):
|
|
22
|
+
self.site = site
|
|
23
|
+
self.engine = get_engine()
|
|
24
|
+
|
|
25
|
+
def _score(self, term: str, hit, code: bool) -> tuple[str, float]:
|
|
26
|
+
match = match_text(term, hit.norm, code=code)
|
|
27
|
+
if match:
|
|
28
|
+
return match, CONFIDENCE[match]
|
|
29
|
+
return "fuzzy", round(FUZZY_WEIGHT * hit.engine_score, 2)
|
|
30
|
+
|
|
31
|
+
# --- objects --------------------------------------------------------------------------------
|
|
32
|
+
def _scopes(self, targets) -> dict:
|
|
33
|
+
"""``{content type id: (target, scope)}`` for the targets with indexed search fields."""
|
|
34
|
+
registered = {m for m, a in self.site.api_site.exposed_admins() if self.site.is_exposed(a)}
|
|
35
|
+
registered |= {t.model for t in targets}
|
|
36
|
+
by_ct = {}
|
|
37
|
+
for target in targets:
|
|
38
|
+
fields = local_fields(target.model, target.search_fields)
|
|
39
|
+
if not fields:
|
|
40
|
+
continue
|
|
41
|
+
codes = CODE_FIELDS | frozenset(getattr(target.admin, "search_index_code_fields", None) or ())
|
|
42
|
+
owned = owned_models(target.model, registered)
|
|
43
|
+
scope = Scope([content_type_of(m) for m in owned], fields, codes, target.queryset)
|
|
44
|
+
for ct in scope.content_types:
|
|
45
|
+
by_ct[ct.pk] = (target, scope)
|
|
46
|
+
return by_ct
|
|
47
|
+
|
|
48
|
+
def search_objects(self, request, term: str, targets, limit: int = DEFAULT_LIMIT):
|
|
49
|
+
"""The best ``limit + 1`` candidates, best first, and ``False`` (the index is never capped)."""
|
|
50
|
+
wanted = fold(term)
|
|
51
|
+
by_ct = self._scopes(targets)
|
|
52
|
+
if not wanted or not by_ct:
|
|
53
|
+
return [], False
|
|
54
|
+
scopes = list({id(s): s for _t, s in by_ct.values()}.values())
|
|
55
|
+
count = max(limit + 1, 2) # two candidates decide between unique and ambiguous
|
|
56
|
+
if self.engine.scope_pushdown:
|
|
57
|
+
engine_hits = self.engine.search(SearchQuery(wanted, OBJECT, scopes, limit=count))
|
|
58
|
+
else:
|
|
59
|
+
engine_hits = self._post_filtered(wanted, scopes, by_ct, count)
|
|
60
|
+
best: dict = {}
|
|
61
|
+
for engine_hit in engine_hits:
|
|
62
|
+
target, scope = by_ct.get(engine_hit.content_type.pk, (None, None))
|
|
63
|
+
if target is None:
|
|
64
|
+
continue
|
|
65
|
+
match, confidence = self._score(wanted, engine_hit, engine_hit.field in scope.code_fields)
|
|
66
|
+
pk = target.model._meta.pk.to_python(engine_hit.object_pk)
|
|
67
|
+
key = (target.label, pk)
|
|
68
|
+
if key not in best or confidence > best[key].confidence:
|
|
69
|
+
best[key] = Hit(target, pk, match=match, confidence=confidence, matched_field=engine_hit.field)
|
|
70
|
+
hits = sorted(best.values(), key=lambda h: -h.confidence)
|
|
71
|
+
return hits[:count], False
|
|
72
|
+
|
|
73
|
+
def _post_filtered(self, wanted, scopes, by_ct, count) -> list:
|
|
74
|
+
"""Engine hits whose objects the admin querysets hold, paging until ``count`` candidates."""
|
|
75
|
+
page_size, kept, kept_keys = count * self.post_filter_factor, [], set()
|
|
76
|
+
for page in range(self.post_filter_pages):
|
|
77
|
+
hits = self.engine.search(SearchQuery(wanted, OBJECT, scopes, limit=page_size, offset=page * page_size))
|
|
78
|
+
located = [(hit, by_ct[hit.content_type.pk][0]) for hit in hits if hit.content_type.pk in by_ct]
|
|
79
|
+
pks_by_target: dict = {}
|
|
80
|
+
for hit, target in located:
|
|
81
|
+
pks_by_target.setdefault(id(target), (target, set()))[1].add(hit.object_pk)
|
|
82
|
+
visible = set()
|
|
83
|
+
for target, pks in pks_by_target.values():
|
|
84
|
+
found = target.queryset.filter(pk__in=[target.model._meta.pk.to_python(pk) for pk in pks])
|
|
85
|
+
visible.update((target.label, str(pk)) for pk in found.values_list("pk", flat=True))
|
|
86
|
+
for hit, target in located:
|
|
87
|
+
if (target.label, hit.object_pk) in visible:
|
|
88
|
+
kept.append(hit)
|
|
89
|
+
kept_keys.add((target.label, hit.object_pk))
|
|
90
|
+
if len(kept_keys) >= count or len({(h.content_type.pk, h.object_pk) for h in hits}) < page_size:
|
|
91
|
+
break
|
|
92
|
+
return kept
|
|
93
|
+
|
|
94
|
+
# --- models ---------------------------------------------------------------------------------
|
|
95
|
+
def search_models(self, request, term: str, targets, limit: int = DEFAULT_LIMIT) -> list[Hit]:
|
|
96
|
+
wanted = fold(term)
|
|
97
|
+
content_types = [content_type_of(t.model) for t in targets]
|
|
98
|
+
by_ct = {ct.pk: t for ct, t in zip(content_types, targets)}
|
|
99
|
+
if not wanted or not by_ct:
|
|
100
|
+
return []
|
|
101
|
+
scope = Scope(content_types)
|
|
102
|
+
engine_hits = self.engine.search(SearchQuery(wanted, MODEL, [scope], limit=max(limit + 1, 2)))
|
|
103
|
+
best: dict = {}
|
|
104
|
+
for engine_hit in engine_hits:
|
|
105
|
+
target = by_ct.get(engine_hit.content_type.pk)
|
|
106
|
+
if target is None:
|
|
107
|
+
continue
|
|
108
|
+
match, confidence = self._score(wanted, engine_hit, False)
|
|
109
|
+
if target.label not in best or confidence > best[target.label].confidence:
|
|
110
|
+
label, language = model_label_text(target, engine_hit.norm)
|
|
111
|
+
best[target.label] = Hit(target, match=match, confidence=confidence, label=label, language=language)
|
|
112
|
+
return sorted(best.values(), key=lambda h: -h.confidence)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def model_label_text(target, norm: str) -> tuple[str, str | None]:
|
|
116
|
+
"""The label string and language whose folded form is ``norm``, read live."""
|
|
117
|
+
for language in _languages():
|
|
118
|
+
for _field, name in model_names(target.model, [target.admin], language):
|
|
119
|
+
if fold(name) == norm:
|
|
120
|
+
return name, language
|
|
121
|
+
return norm, None
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from django.core import checks
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@checks.register(checks.Tags.database)
|
|
5
|
+
def check_engine(app_configs=None, databases=None, **kwargs):
|
|
6
|
+
"""The configured engine's own checks (``db``: the database ctype). Runs with ``--database``
|
|
7
|
+
and before ``migrate``."""
|
|
8
|
+
from .conf import get_engine
|
|
9
|
+
|
|
10
|
+
if not databases or "default" not in databases:
|
|
11
|
+
return []
|
|
12
|
+
return get_engine().check()
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""The ``ADMIN_API_SEARCH`` setting, merged over the defaults, and the configured engine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from functools import cache
|
|
6
|
+
|
|
7
|
+
from django.conf import settings
|
|
8
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
9
|
+
from django.core.signals import setting_changed
|
|
10
|
+
from django.dispatch import receiver
|
|
11
|
+
from django.utils.module_loading import import_string
|
|
12
|
+
|
|
13
|
+
DB_ENGINE = "admin_api_mcp.contrib.search.engines.db.DatabaseEngine"
|
|
14
|
+
DEFAULTS = {
|
|
15
|
+
"DEFAULT_ENGINE": "db",
|
|
16
|
+
"ENGINES": {"db": {"BACKEND": DB_ENGINE}},
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def search_settings() -> dict:
|
|
21
|
+
user = getattr(settings, "ADMIN_API_SEARCH", None) or {}
|
|
22
|
+
return {
|
|
23
|
+
"DEFAULT_ENGINE": user.get("DEFAULT_ENGINE", DEFAULTS["DEFAULT_ENGINE"]),
|
|
24
|
+
"ENGINES": {**DEFAULTS["ENGINES"], **user.get("ENGINES", {})},
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@cache
|
|
29
|
+
def get_engine():
|
|
30
|
+
"""The engine named by ``DEFAULT_ENGINE``, built once per process."""
|
|
31
|
+
conf = search_settings()
|
|
32
|
+
name = conf["DEFAULT_ENGINE"]
|
|
33
|
+
spec = conf["ENGINES"].get(name)
|
|
34
|
+
if not spec or not spec.get("BACKEND"):
|
|
35
|
+
raise ImproperlyConfigured(f"ADMIN_API_SEARCH: no engine {name!r} with a BACKEND in ENGINES.")
|
|
36
|
+
return import_string(spec["BACKEND"])(name, spec.get("OPTIONS"))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@receiver(setting_changed)
|
|
40
|
+
def _reset(setting, **kwargs):
|
|
41
|
+
if setting == "ADMIN_API_SEARCH":
|
|
42
|
+
get_engine.cache_clear()
|
|
File without changes
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""The interface every search engine implements, and the values it trades with the contrib core.
|
|
2
|
+
|
|
3
|
+
The core decides which rows exist (:mod:`..indexer`), which rows a request may see and how a hit
|
|
4
|
+
scores (:mod:`..backend`). An engine stores rows and finds candidates.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
from django.contrib.contenttypes.models import ContentType
|
|
12
|
+
from django.db.models import QuerySet
|
|
13
|
+
|
|
14
|
+
OBJECT = "object"
|
|
15
|
+
MODEL = "model"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Entry:
|
|
20
|
+
"""One row to store: an object's search field (``kind="object"``) or a model label under one
|
|
21
|
+
language (``kind="model"``, ``object_pk=None``)."""
|
|
22
|
+
|
|
23
|
+
kind: str
|
|
24
|
+
content_type: ContentType
|
|
25
|
+
object_pk: str | None
|
|
26
|
+
field: str
|
|
27
|
+
language: str
|
|
28
|
+
text: str
|
|
29
|
+
norm: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Hit:
|
|
34
|
+
"""One stored row an engine found. ``engine_score`` is the engine's own relevance, 0 to 1."""
|
|
35
|
+
|
|
36
|
+
content_type: ContentType
|
|
37
|
+
object_pk: str | None
|
|
38
|
+
field: str
|
|
39
|
+
norm: str
|
|
40
|
+
engine_score: float = 0.0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Scope:
|
|
45
|
+
"""Rows of these content types and fields that the request may see. ``queryset`` is the admin's
|
|
46
|
+
``get_queryset(request)`` (narrowed for ``for_field``); engines with ``scope_pushdown`` filter
|
|
47
|
+
by it, the others leave it to the core."""
|
|
48
|
+
|
|
49
|
+
content_types: list[ContentType]
|
|
50
|
+
fields: tuple[str, ...] = ()
|
|
51
|
+
code_fields: frozenset = frozenset()
|
|
52
|
+
queryset: QuerySet | None = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class SearchQuery:
|
|
57
|
+
"""``text`` is folded. ``limit`` counts distinct candidates (objects or models), ``offset``
|
|
58
|
+
skips that many for the core's post-filter paging."""
|
|
59
|
+
|
|
60
|
+
text: str
|
|
61
|
+
kind: str
|
|
62
|
+
scopes: list[Scope] = field(default_factory=list)
|
|
63
|
+
limit: int = 6
|
|
64
|
+
offset: int = 0
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class SearchEngine:
|
|
68
|
+
"""Base class of search engines, configured under ``ADMIN_API_SEARCH["ENGINES"]``.
|
|
69
|
+
``scope_pushdown``: :meth:`search` applies each scope's ``queryset`` itself."""
|
|
70
|
+
|
|
71
|
+
scope_pushdown = False
|
|
72
|
+
|
|
73
|
+
def __init__(self, name: str = "", options: dict | None = None):
|
|
74
|
+
self.name = name
|
|
75
|
+
self.options = dict(options or {})
|
|
76
|
+
|
|
77
|
+
def upsert(self, entries: list[Entry]) -> None:
|
|
78
|
+
"""Insert object rows, or update the stored ones with the same (content type, pk, field)."""
|
|
79
|
+
raise NotImplementedError
|
|
80
|
+
|
|
81
|
+
def delete_rows(self, content_type: ContentType, object_pk: str, fields) -> None:
|
|
82
|
+
"""Delete the rows of an object's ``fields``."""
|
|
83
|
+
raise NotImplementedError
|
|
84
|
+
|
|
85
|
+
def replace_model_rows(self, rows: list[Entry]) -> None:
|
|
86
|
+
"""Replace every stored model row with ``rows``."""
|
|
87
|
+
raise NotImplementedError
|
|
88
|
+
|
|
89
|
+
def prune(self, content_types: list[ContentType], older_than) -> int:
|
|
90
|
+
"""Delete the object rows of ``content_types`` last written before ``older_than``."""
|
|
91
|
+
raise NotImplementedError
|
|
92
|
+
|
|
93
|
+
def search(self, query: SearchQuery) -> list[Hit]:
|
|
94
|
+
"""Rows of the best ``query.limit`` candidates after ``query.offset``, best first."""
|
|
95
|
+
raise NotImplementedError
|
|
96
|
+
|
|
97
|
+
def check(self) -> list:
|
|
98
|
+
"""System check messages about this engine's setup."""
|
|
99
|
+
return []
|