django-multiurl 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.5
2
+ Name: django-multiurl
3
+ Version: 2.0.0
4
+ Summary: Allow multiple views to match the same URL.
5
+ Project-URL: Homepage, https://github.com/raiderrobert/django-multiurl
6
+ Project-URL: Issues, https://github.com/raiderrobert/django-multiurl/issues
7
+ Author-email: Robert Roskam <raiderrobert@gmail.com>
8
+ License-Expression: BSD-3-Clause
9
+ License-File: LICENSE.txt
10
+ Keywords: django,urls
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: Django
14
+ Classifier: Framework :: Django :: 4.2
15
+ Classifier: Framework :: Django :: 5.2
16
+ Classifier: Framework :: Django :: 6.0
17
+ Classifier: Framework :: Django :: 6.1
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: Natural Language :: English
20
+ Classifier: Programming Language :: Python
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3 :: Only
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Programming Language :: Python :: 3.14
28
+ Requires-Python: >=3.10
29
+ Requires-Dist: django>=4.2
30
+ Description-Content-Type: text/markdown
31
+
32
+ # django-multiurl
33
+
34
+ [![CI](https://github.com/raiderrobert/django-multiurl/actions/workflows/ci.yml/badge.svg)](https://github.com/raiderrobert/django-multiurl/actions/workflows/ci.yml)
35
+ [![PyPI](https://img.shields.io/pypi/v/django-multiurl.svg)](https://pypi.org/project/django-multiurl/)
36
+
37
+ Have you ever wanted multiple views to match to the same URL? Now you can.
38
+
39
+ You may once have tried something like this:
40
+
41
+ ```python
42
+ urlpatterns = [
43
+ path("app/<str:name>/", app.views.people),
44
+ path("app/<str:name>/", app.views.place),
45
+ ]
46
+ ```
47
+
48
+ However, if you try this, `/app/san-francisco/` will only map to
49
+ `app.views.people`. Raising an `Http404` from `app.views.people` doesn't
50
+ help: you only get a 404 in the browser because Django stops resolving
51
+ URLs at the first match.
52
+
53
+ Well, `django-multiurl` solves this problem. Just `pip install django-multiurl`,
54
+ then do this:
55
+
56
+ ```python
57
+ from django.urls import path
58
+ from multiurl import multiurl
59
+
60
+ urlpatterns = [
61
+ multiurl(
62
+ path("app/<str:name>/", app.views.people),
63
+ path("app/<str:name>/", app.views.place),
64
+ ),
65
+ ]
66
+ ```
67
+
68
+ Now in your views, raise `multiurl.ContinueResolving` anywhere you'd like
69
+ to break out of the view and keep resolving. For example, here's what
70
+ `app.views.people` might look like:
71
+
72
+ ```python
73
+ from multiurl import ContinueResolving
74
+
75
+
76
+ def people(request, name):
77
+ try:
78
+ person = Person.objects.get(name=name)
79
+ except Person.DoesNotExist:
80
+ raise ContinueResolving
81
+ return render(...)
82
+ ```
83
+
84
+ That's it! `ContinueResolving` will cause `multiurl` to continue onto the
85
+ next view (`app.views.place`, in this example).
86
+
87
+ A few notes to round things out:
88
+
89
+ - If you don't want to use `ContinueResolving` (perhaps you'd rather keep
90
+ using `get_object_or_404`, or you're using third-party views that you
91
+ can't modify to raise `ContinueResolving`), you can pass a `catch`
92
+ argument into `multiurl` to control which exceptions are considered
93
+ "continue" statements. For example, to allow `Http404` exceptions to
94
+ continue resolving, do this:
95
+
96
+ ```python
97
+ urlpatterns = [
98
+ multiurl(
99
+ path("app/<str:name>/", app.views.people),
100
+ path("app/<str:name>/", app.views.place),
101
+ catch=(Http404, ContinueResolving),
102
+ ),
103
+ ]
104
+ ```
105
+
106
+ As you can see, `catch` should be a tuple of exceptions. It's probably a
107
+ good idea to always include `ContinueResolving` in the tuple.
108
+
109
+ - If the last view in a `multiurl` raises `ContinueResolving` (or another
110
+ "continuing" exception), a 404 will be raised instead. That is, if resolving
111
+ "falls off the end" of some multi-urls, you'll get the 404 you expect.
112
+
113
+ - `path()` and `re_path()` both work, as does nesting `multiurl` inside
114
+ `include()` (namespaces and captured prefix arguments are passed through).
115
+
116
+ - Async views work, and can be mixed with sync views in one `multiurl`.
117
+
118
+ - `@csrf_exempt` and `@login_not_required` are honored only when every view
119
+ in the `multiurl` has them, since middleware runs before it's known which
120
+ view will answer.
121
+
122
+ - Reverse URL resolution just works as expected. Name your sub-URLs and then
123
+ reverse your heart out.
124
+
125
+ ## Supported versions
126
+
127
+ | django-multiurl | Python | Django |
128
+ | --------------- | ----------- | --------------------- |
129
+ | 2.x | 3.10 – 3.14 | 4.2, 5.2, 6.0, 6.1 |
130
+ | 1.x | 2.7, 3.4+ | 1.11 – 3.2 |
131
+
132
+ ## Contributing
133
+
134
+ Development takes place
135
+ [on GitHub](https://github.com/raiderrobert/django-multiurl); pull requests
136
+ are welcome. The project uses [uv](https://docs.astral.sh/uv/):
137
+
138
+ ```sh
139
+ uv run pytest # run the tests
140
+ uv run --with "django==5.2.*" pytest # against a specific Django
141
+ uv run ruff check . && uv run ruff format --check . && uv run ty check
142
+ ```
143
+
144
+ PR titles must follow [Conventional Commits](https://www.conventionalcommits.org/)
145
+ (`fix: …`, `feat: …`, `feat!: …` for breaking changes): PRs are squash-merged
146
+ and [release-please](https://github.com/googleapis/release-please) uses the
147
+ titles to pick the next version and write the changelog.
@@ -0,0 +1,5 @@
1
+ multiurl.py,sha256=DCBGavfi7DtiAqcfFw5ya4AjodJ7RAyZRNvfB_I-YbY,4971
2
+ django_multiurl-2.0.0.dist-info/METADATA,sha256=QfJD0JwVRqT53zU5VtdtjdGa5G9jWYGmx0j8W-6WLB0,5348
3
+ django_multiurl-2.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ django_multiurl-2.0.0.dist-info/licenses/LICENSE.txt,sha256=DyWS1qoNRny58KBELWL5XpQfaFH-wu-aY35Kerh07d8,1520
5
+ django_multiurl-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2013, Jacob Kaplan-Moss
2
+
3
+ All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without modification,
6
+ are permitted provided that the following conditions are met:
7
+
8
+ * Redistributions of source code must retain the above copyright notice,
9
+ this list of conditions and the following disclaimer.
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+ * Neither the name of django-multiurl nor the names of its contributors
14
+ may be used to endorse or promote products derived from this software
15
+ without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
21
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
multiurl.py ADDED
@@ -0,0 +1,130 @@
1
+ from asgiref.sync import iscoroutinefunction, sync_to_async
2
+ from django.urls import Resolver404, ResolverMatch, URLResolver
3
+ from django.urls.resolvers import RegexPattern
4
+ from django.utils.functional import cached_property
5
+
6
+
7
+ class ContinueResolving(Exception):
8
+ pass
9
+
10
+
11
+ def multiurl(*urls, catch=(ContinueResolving,)):
12
+ return MultiRegexURLResolver(urls, catch)
13
+
14
+
15
+ class MultiRegexURLResolver(URLResolver):
16
+ def __init__(self, urls, exceptions):
17
+ super().__init__(RegexPattern(""), None)
18
+ self._urls = urls
19
+ self._exceptions = exceptions
20
+
21
+ @cached_property
22
+ def url_patterns(self):
23
+ return self._urls
24
+
25
+ def resolve(self, path):
26
+ tried = []
27
+ matched = []
28
+ patterns_matched = []
29
+
30
+ # This is a simplified version of URLResolver.resolve. It doesn't
31
+ # support a regex prefix, and it doesn't need to handle include(),
32
+ # so it's simpler, but otherwise this mirrors Django's version.
33
+ for pattern in self.url_patterns:
34
+ try:
35
+ sub_match = pattern.resolve(path)
36
+ except Resolver404:
37
+ sub_match = None
38
+ if sub_match:
39
+ # Here's the part that's different: instead of returning the
40
+ # first match, build up a list of all matches.
41
+ matched.append(sub_match)
42
+ patterns_matched.append([pattern])
43
+ tried.append([pattern])
44
+ if matched:
45
+ return MultiResolverMatch(matched, self._exceptions, patterns_matched, path)
46
+ raise Resolver404({"tried": tried, "path": path})
47
+
48
+
49
+ class MultiResolverMatch:
50
+ def __init__(
51
+ self,
52
+ matches: list[ResolverMatch],
53
+ exceptions,
54
+ patterns_matched,
55
+ path,
56
+ route=None,
57
+ tried=None,
58
+ captured_kwargs=None,
59
+ extra_kwargs=None,
60
+ ):
61
+ self.matches = matches
62
+ self.exceptions = exceptions
63
+ self.patterns_matched = patterns_matched
64
+ self.path = path
65
+ # Every match resolved the same path, so report the first one's route
66
+ # (Django joins it with any outer include() prefix).
67
+ self.route = route if route is not None else (matches[0].route or "")
68
+ self.tried = tried
69
+
70
+ # Attributes to emulate ResolverMatch. Each sub-match carries its own
71
+ # args/kwargs, so the outer resolver only contributes prefix kwargs.
72
+ self.kwargs = {}
73
+ self.args = ()
74
+ self.captured_kwargs = captured_kwargs if captured_kwargs is not None else {}
75
+ self.extra_kwargs = extra_kwargs if extra_kwargs is not None else {}
76
+ self.url_name = None
77
+ self.app_names = []
78
+ self.app_name = None
79
+ self.namespaces = []
80
+
81
+ def _view_arguments(self, match, args, kwargs):
82
+ # args/kwargs come from enclosing patterns, e.g. the <section> in
83
+ # path("<str:section>/", include([multiurl(...)])). Same rule as
84
+ # Django's URLResolver: if there are any kwargs, the outer positional
85
+ # args are dropped, but the sub-pattern's own args are kept.
86
+ view_kwargs = {**kwargs, **match.kwargs}
87
+ view_args = tuple(match.args) if view_kwargs else args + tuple(match.args)
88
+ return view_args, view_kwargs
89
+
90
+ def _not_found(self):
91
+ return Resolver404({"tried": self.patterns_matched, "path": self.path})
92
+
93
+ @property
94
+ def func(self):
95
+ funcs = [match.func for match in self.matches]
96
+
97
+ if any(iscoroutinefunction(f) for f in funcs):
98
+
99
+ async def multiview(request, *args, **kwargs):
100
+ for match in self.matches:
101
+ view_args, view_kwargs = self._view_arguments(match, args, kwargs)
102
+ view = match.func
103
+ if not iscoroutinefunction(view):
104
+ view = sync_to_async(view)
105
+ try:
106
+ return await view(request, *view_args, **view_kwargs)
107
+ except self.exceptions:
108
+ continue
109
+ raise self._not_found()
110
+
111
+ else:
112
+
113
+ def multiview(request, *args, **kwargs):
114
+ for match in self.matches:
115
+ view_args, view_kwargs = self._view_arguments(match, args, kwargs)
116
+ try:
117
+ return match.func(request, *view_args, **view_kwargs)
118
+ except self.exceptions:
119
+ continue
120
+ raise self._not_found()
121
+
122
+ attrs = {"multi_resolver_match": self}
123
+ # Middleware only sees multiview, so carry over view-decorator flags,
124
+ # but only where every sub-view agrees (otherwise keep the safe default).
125
+ if all(getattr(f, "csrf_exempt", False) for f in funcs):
126
+ attrs["csrf_exempt"] = True
127
+ if all(getattr(f, "login_required", True) is False for f in funcs):
128
+ attrs["login_required"] = False
129
+ multiview.__dict__.update(attrs)
130
+ return multiview