django-hostmap 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- django_hostmap-0.1.0.dist-info/METADATA +163 -0
- django_hostmap-0.1.0.dist-info/RECORD +20 -0
- django_hostmap-0.1.0.dist-info/WHEEL +5 -0
- django_hostmap-0.1.0.dist-info/licenses/LICENSE +21 -0
- django_hostmap-0.1.0.dist-info/top_level.txt +1 -0
- hostmap/__init__.py +4 -0
- hostmap/apps.py +61 -0
- hostmap/checks.py +252 -0
- hostmap/conf.py +60 -0
- hostmap/context.py +68 -0
- hostmap/management/__init__.py +0 -0
- hostmap/management/commands/__init__.py +0 -0
- hostmap/management/commands/hostmap.py +31 -0
- hostmap/map.py +194 -0
- hostmap/middleware.py +79 -0
- hostmap/resolvers.py +159 -0
- hostmap/testing/__init__.py +10 -0
- hostmap/testing/fixtures.py +18 -0
- hostmap/testing/helpers.py +33 -0
- hostmap/urls.py +196 -0
hostmap/urls.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""The single host-aware resolution code path and the explicit API.
|
|
2
|
+
|
|
3
|
+
Both the patched stock ``reverse()`` (via ``resolvers.py``) and the explicit
|
|
4
|
+
API (``hostmap.urls.reverse`` / ``build_absolute_uri``) delegate to the same
|
|
5
|
+
``_resolve()`` function. There are never two implementations of host-aware
|
|
6
|
+
resolution to keep in lockstep (03-services.md section 3, watch flag 2):
|
|
7
|
+
with ``HOSTMAP_PATCH_REVERSE = False`` the explicit API calls this logic
|
|
8
|
+
directly.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
from contextlib import contextmanager
|
|
15
|
+
|
|
16
|
+
from django.urls import NoReverseMatch
|
|
17
|
+
from django.urls import reverse as django_reverse
|
|
18
|
+
from django.urls.base import get_script_prefix
|
|
19
|
+
|
|
20
|
+
from hostmap import context
|
|
21
|
+
from hostmap import map as hostmap_map
|
|
22
|
+
from hostmap.conf import hostmap_settings
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger("hostmap.reverse")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def entry_order():
|
|
28
|
+
"""Cross-host resolution order (BR-HOSTMAP-005): the single source of truth.
|
|
29
|
+
|
|
30
|
+
Active host, then the default entry, then remaining entries in declaration
|
|
31
|
+
order. Duplicates removed while preserving first sight. Redirect and
|
|
32
|
+
wildcard entries never participate in cross-host reversing (BR-HOSTMAP-009);
|
|
33
|
+
wildcards are reachable only via ``use_host(host=...)``.
|
|
34
|
+
|
|
35
|
+
Both resolution paths, the explicit API here and the resolver seam
|
|
36
|
+
(``resolvers.HostAwareResolver``), consume this one ordering so there is
|
|
37
|
+
never a second implementation of BR-HOSTMAP-005 to keep in lockstep
|
|
38
|
+
(03-services.md, watch flag 2).
|
|
39
|
+
"""
|
|
40
|
+
entries = hostmap_map.resolved_entries()
|
|
41
|
+
ordered = []
|
|
42
|
+
seen = set()
|
|
43
|
+
|
|
44
|
+
def _add(entry):
|
|
45
|
+
if entry is None or entry.label in seen:
|
|
46
|
+
return
|
|
47
|
+
if entry.is_redirect or entry.wildcard:
|
|
48
|
+
return
|
|
49
|
+
seen.add(entry.label)
|
|
50
|
+
ordered.append(entry)
|
|
51
|
+
|
|
52
|
+
_add(context.get_active())
|
|
53
|
+
_add(hostmap_map.default_entry())
|
|
54
|
+
for entry in entries.values():
|
|
55
|
+
_add(entry)
|
|
56
|
+
return ordered
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _absolute_url(entry, path: str) -> str:
|
|
60
|
+
"""Compose ``scheme://host[:port]`` + ``path`` for a cross-host entry (BR-HOSTMAP-004).
|
|
61
|
+
|
|
62
|
+
``path`` already includes the script prefix (Django's ``reverse`` prepends
|
|
63
|
+
it), so it is used verbatim; this composes the authority only.
|
|
64
|
+
"""
|
|
65
|
+
host = entry.host
|
|
66
|
+
port = hostmap_settings.PORT
|
|
67
|
+
if port:
|
|
68
|
+
host = f"{host}:{port}"
|
|
69
|
+
return f"{hostmap_settings.SCHEME}://{host}{path}"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _resolve(name, args=None, kwargs=None, *, force_host_entry=None) -> str:
|
|
73
|
+
"""Host-aware reverse: the single resolution code path.
|
|
74
|
+
|
|
75
|
+
Reverses ``name`` against the active host first. On ``NoReverseMatch`` it
|
|
76
|
+
walks the other entries in BR-HOSTMAP-005 order and returns an absolute
|
|
77
|
+
URL for the first host that resolves the name. Raises ``NoReverseMatch``
|
|
78
|
+
naming the searched hosts if nothing resolves.
|
|
79
|
+
|
|
80
|
+
``force_host_entry`` pins resolution to one entry (used by ``use_host``
|
|
81
|
+
and ``build_absolute_uri(host=...)``); the result is always absolute.
|
|
82
|
+
"""
|
|
83
|
+
if force_host_entry is not None:
|
|
84
|
+
path = django_reverse(name, urlconf=force_host_entry.urlconf, args=args, kwargs=kwargs)
|
|
85
|
+
return _absolute_url(force_host_entry, path)
|
|
86
|
+
|
|
87
|
+
order = entry_order()
|
|
88
|
+
active = order[0] if order else None
|
|
89
|
+
|
|
90
|
+
# Try the active host first. A match here stays path-relative
|
|
91
|
+
# (BR-HOSTMAP-003, byte-identical to stock Django).
|
|
92
|
+
if active is not None:
|
|
93
|
+
try:
|
|
94
|
+
return django_reverse(name, urlconf=active.urlconf, args=args, kwargs=kwargs)
|
|
95
|
+
except NoReverseMatch:
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
# Cross-host fallback: first other entry that resolves wins.
|
|
99
|
+
for entry in order[1:]:
|
|
100
|
+
try:
|
|
101
|
+
path = django_reverse(name, urlconf=entry.urlconf, args=args, kwargs=kwargs)
|
|
102
|
+
except NoReverseMatch:
|
|
103
|
+
continue
|
|
104
|
+
logger.debug("hostmap cross-host reverse: %r -> host %s (%s)", name, entry.host, entry.label)
|
|
105
|
+
return _absolute_url(entry, path)
|
|
106
|
+
|
|
107
|
+
searched = ", ".join(e.host for e in order) or "(no hostmap entries)"
|
|
108
|
+
raise NoReverseMatch(f"Reverse for '{name}' not found on any hostmap host. Searched: {searched}.")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# --- Explicit API (03-services.md section 3) -------------------------------
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def reverse(name, args=None, kwargs=None) -> str:
|
|
115
|
+
"""Host-aware reverse with the same semantics as the patched stock reverse."""
|
|
116
|
+
return _resolve(name, args=args, kwargs=kwargs)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def build_absolute_uri(name_or_path, args=None, kwargs=None, host=None) -> str:
|
|
120
|
+
"""Return an absolute URL regardless of the active host.
|
|
121
|
+
|
|
122
|
+
``name_or_path`` is either a URL name (reversed with ``args``/``kwargs``)
|
|
123
|
+
or a ready-made path (starting with ``/``). ``host`` optionally pins the
|
|
124
|
+
entry by label or by literal host (for wildcard entries).
|
|
125
|
+
"""
|
|
126
|
+
entry = _host_to_entry(host) if host is not None else context.get_active()
|
|
127
|
+
|
|
128
|
+
if isinstance(name_or_path, str) and name_or_path.startswith("/"):
|
|
129
|
+
if entry is None:
|
|
130
|
+
raise NoReverseMatch("build_absolute_uri: no active or specified host to build an absolute URL against.")
|
|
131
|
+
return _absolute_url(entry, name_or_path)
|
|
132
|
+
|
|
133
|
+
if host is not None:
|
|
134
|
+
return _resolve(name_or_path, args=args, kwargs=kwargs, force_host_entry=entry)
|
|
135
|
+
|
|
136
|
+
# No pinned host: reverse host-aware, then force absolute against the
|
|
137
|
+
# active host when the result is still a same-host path.
|
|
138
|
+
result = _resolve(name_or_path, args=args, kwargs=kwargs)
|
|
139
|
+
if result.startswith("/") and entry is not None:
|
|
140
|
+
return _absolute_url(entry, result)
|
|
141
|
+
return result
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@contextmanager
|
|
145
|
+
def use_host(label=None, host=None):
|
|
146
|
+
"""Treat the given entry (or explicit host) as active for reversing.
|
|
147
|
+
|
|
148
|
+
The BR-HOSTMAP-006 override for emails, Celery tasks, API payloads and
|
|
149
|
+
webhooks. Pass ``label`` for a named entry or ``host`` for a wildcard's
|
|
150
|
+
concrete host (README open question 2).
|
|
151
|
+
"""
|
|
152
|
+
entry = _host_to_entry(host if host is not None else label, is_host=host is not None)
|
|
153
|
+
token = context.set_active(entry)
|
|
154
|
+
try:
|
|
155
|
+
yield entry
|
|
156
|
+
finally:
|
|
157
|
+
context.reset_active(token)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _host_to_entry(value, is_host=False):
|
|
161
|
+
"""Resolve a label or literal host string to a ``ResolvedEntry``.
|
|
162
|
+
|
|
163
|
+
For a wildcard host (a concrete host under a ``*`` entry), synthesise an
|
|
164
|
+
entry carrying that literal host and the wildcard's URLconf so
|
|
165
|
+
``use_host(host="tenant.example.com")`` reverses into it (BR-HOSTMAP-009).
|
|
166
|
+
"""
|
|
167
|
+
from hostmap.map import ResolvedEntry
|
|
168
|
+
|
|
169
|
+
entries = hostmap_map.resolved_entries()
|
|
170
|
+
|
|
171
|
+
if not is_host and value in entries:
|
|
172
|
+
return entries[value]
|
|
173
|
+
|
|
174
|
+
# Treat value as a literal host: exact match first.
|
|
175
|
+
normalised = hostmap_map._strip_port(str(value))
|
|
176
|
+
for entry in entries.values():
|
|
177
|
+
if not entry.wildcard and entry.host == normalised:
|
|
178
|
+
return entry
|
|
179
|
+
|
|
180
|
+
# Wildcard synthesis: the concrete host borrows the wildcard's URLconf.
|
|
181
|
+
for entry in entries.values():
|
|
182
|
+
if entry.wildcard and hostmap_map._wildcard_matches(entry, normalised):
|
|
183
|
+
return ResolvedEntry(
|
|
184
|
+
label=entry.label,
|
|
185
|
+
host=normalised,
|
|
186
|
+
urlconf=entry.urlconf,
|
|
187
|
+
redirect_to=None,
|
|
188
|
+
wildcard=False,
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
raise NoReverseMatch(f"use_host: {value!r} does not match any hostmap entry or host.")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# ``get_script_prefix`` is imported for the seam self-test (apps.py) to reverse
|
|
195
|
+
# a probe pattern through the same script-prefix machinery stock reverse uses.
|
|
196
|
+
__all__ = ["reverse", "build_absolute_uri", "use_host", "get_script_prefix"]
|