dmr-controller-group 0.0.1__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,12 @@
1
+ from dmr_controller_group.decorators import delete, get, patch, post, put
2
+ from dmr_controller_group.groups import ControllerGroup
3
+
4
+
5
+ __all__ = [
6
+ "ControllerGroup",
7
+ "delete",
8
+ "get",
9
+ "patch",
10
+ "post",
11
+ "put",
12
+ ]
@@ -0,0 +1,11 @@
1
+ import importlib.metadata
2
+
3
+
4
+ __all__ = ["__title__", "__version__"]
5
+
6
+ _metadata = importlib.metadata.metadata("dmr_controller_group")
7
+
8
+ __title__ = _metadata["Name"]
9
+ """Name of the project."""
10
+ __version__ = _metadata["Version"]
11
+ """Version of the project."""
@@ -0,0 +1,79 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from types import new_class
5
+ from typing import TYPE_CHECKING, Any, cast
6
+
7
+ from dmr import Controller
8
+ from dmr.decorators import dispatch_decorator
9
+ from dmr.types import is_safe_subclass
10
+
11
+ from dmr_controller_group.endpoints import RoutedEndpoint
12
+ from dmr_controller_group.exceptions import RouteConfigurationError
13
+
14
+
15
+ if TYPE_CHECKING:
16
+ from dmr.serializer import BaseSerializer
17
+
18
+ from dmr_controller_group._routes import RouteGroup
19
+ from dmr_controller_group.groups import ControllerGroup
20
+
21
+
22
+ def has_http_handlers(
23
+ controller_cls: type[Controller[BaseSerializer]],
24
+ ) -> bool:
25
+ return any(
26
+ callable(getattr(controller_cls, method, None))
27
+ for method in controller_cls.allowed_http_methods
28
+ if method != "meta"
29
+ )
30
+
31
+
32
+ def validate_base_controller(group: type[ControllerGroup[Any]], base_controller_cls: type[Controller[Any]]) -> None:
33
+ """Validate that a custom base is an abstract DMR controller without HTTP handlers."""
34
+ if not is_safe_subclass(base_controller_cls, Controller):
35
+ msg = f"{group.__qualname__}.base_controller_cls must be a DMR Controller subclass." # type: ignore[unreachable]
36
+ raise RouteConfigurationError(msg)
37
+
38
+ if not base_controller_cls.is_abstract or has_http_handlers(base_controller_cls):
39
+ msg = f"{base_controller_cls.__qualname__} must be abstract and have no HTTP handlers (except meta)."
40
+ raise RouteConfigurationError(msg)
41
+
42
+
43
+ def build_controller(
44
+ group: type[ControllerGroup],
45
+ base_controller_cls: type[Controller[BaseSerializer]],
46
+ routes: RouteGroup,
47
+ ) -> type[Controller[BaseSerializer]]:
48
+ """Create a concrete controller; DMR builds and validates its endpoints."""
49
+ methods: dict[str, Any] = {endpoint.method.lower(): endpoint.as_method() for endpoint in routes.endpoints}
50
+
51
+ # A descriptor named `get` or `post` must not leak into unrelated paths.
52
+ for method in base_controller_cls.allowed_http_methods:
53
+ if method not in methods and isinstance(getattr(group, method, None), RoutedEndpoint):
54
+ methods[method] = None
55
+
56
+ name = f"{group.__name__}Controller"
57
+ controller = cast(
58
+ "type[Controller[BaseSerializer]]",
59
+ new_class(
60
+ name,
61
+ (group, base_controller_cls),
62
+ exec_body=lambda namespace: namespace.update(
63
+ {
64
+ **methods,
65
+ "__module__": group.__module__,
66
+ "__qualname__": f"{group.__qualname__}Controller",
67
+ "__doc__": group.__doc__,
68
+ "is_abstract": False,
69
+ }
70
+ ),
71
+ ),
72
+ )
73
+
74
+ if group.controller_decorators and controller.is_async and not inspect.iscoroutinefunction(controller.dispatch):
75
+ controller = dispatch_decorator(inspect.markcoroutinefunction)(controller)
76
+
77
+ for decorator in reversed(group.controller_decorators):
78
+ controller = decorator(controller)
79
+ return controller
@@ -0,0 +1,96 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from types import FunctionType
5
+ from typing import TYPE_CHECKING
6
+
7
+ from dmr import Controller
8
+
9
+ from dmr_controller_group.endpoints import AnyRoutedEndpoint, RoutedEndpoint
10
+ from dmr_controller_group.exceptions import RouteConfigurationError
11
+
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Iterator
15
+
16
+
17
+ _HTTP_METHOD_NAMES = Controller.allowed_http_methods | {"options"}
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class RouteGroup:
22
+ path: str
23
+ name: str | None
24
+ endpoints: tuple[AnyRoutedEndpoint, ...]
25
+
26
+
27
+ def collect_routes(group: type) -> list[RouteGroup]:
28
+ """Compile group declarations into validated routes in declaration and MRO order."""
29
+ paths: dict[str, list[AnyRoutedEndpoint]] = {}
30
+
31
+ for endpoint in _iter_endpoints(group):
32
+ paths.setdefault(endpoint.path, []).append(endpoint)
33
+
34
+ return [_build_route_group(path, endpoints) for path, endpoints in paths.items()]
35
+
36
+
37
+ def _iter_endpoints(group: type) -> Iterator[AnyRoutedEndpoint]:
38
+ """Yield effective route declarations without invoking descriptors."""
39
+ routed_attributes = {
40
+ attribute
41
+ for base in group.__mro__
42
+ for attribute, value in vars(base).items()
43
+ if isinstance(value, RoutedEndpoint)
44
+ }
45
+ seen: set[str] = set()
46
+
47
+ for base in group.__mro__:
48
+ for attribute, value in vars(base).items():
49
+ if attribute in seen:
50
+ continue
51
+
52
+ seen.add(attribute)
53
+ label = f"{group.__qualname__}.{attribute}"
54
+
55
+ if isinstance(value, (staticmethod, classmethod)) and isinstance(value.__func__, RoutedEndpoint):
56
+ msg = f"{label}: routes require instance methods."
57
+ raise RouteConfigurationError(msg)
58
+
59
+ if isinstance(value, RoutedEndpoint):
60
+ if hasattr(value, "__dmr_payload__"):
61
+ msg = f"{label}: place the route decorator above DMR decorators."
62
+ raise RouteConfigurationError(msg)
63
+ yield value
64
+
65
+ elif attribute in routed_attributes:
66
+ msg = f"{label} overrides a routed method; repeat its route decorator."
67
+ raise RouteConfigurationError(msg)
68
+
69
+ elif attribute in _HTTP_METHOD_NAMES and isinstance(value, FunctionType):
70
+ msg = f"{label} must have an explicit route decorator."
71
+ raise RouteConfigurationError(msg)
72
+
73
+
74
+ def _build_route_group(path: str, endpoints: list[AnyRoutedEndpoint]) -> RouteGroup:
75
+ """Require one handler per HTTP method and one URL name for an exact path."""
76
+ methods: dict[str, AnyRoutedEndpoint] = {}
77
+ names: set[str] = set()
78
+
79
+ for endpoint in endpoints:
80
+ if previous := methods.get(endpoint.method):
81
+ msg = (
82
+ f"Duplicate route {endpoint.method} {path!r}: "
83
+ f"{previous.function.__qualname__} and {endpoint.function.__qualname__}."
84
+ )
85
+ raise RouteConfigurationError(msg)
86
+
87
+ methods[endpoint.method] = endpoint
88
+
89
+ if endpoint.name is not None:
90
+ names.add(endpoint.name)
91
+
92
+ if len(names) > 1:
93
+ msg = f"Conflicting URL names for path {path!r}: {sorted(names)!r}."
94
+ raise RouteConfigurationError(msg)
95
+
96
+ return RouteGroup(path, next(iter(names), None), tuple(endpoints))
@@ -0,0 +1,173 @@
1
+ from collections.abc import Callable
2
+ from http import HTTPMethod
3
+ from types import FunctionType
4
+ from typing import Any, Concatenate, ParamSpec, TypeVar, overload
5
+
6
+ from dmr_controller_group.endpoints import RoutedEndpoint
7
+ from dmr_controller_group.exceptions import RouteConfigurationError
8
+
9
+
10
+ _Params = ParamSpec("_Params")
11
+ _ReturnT = TypeVar("_ReturnT")
12
+
13
+
14
+ def _route(
15
+ method: str,
16
+ path: str | Callable[Concatenate[Any, _Params], _ReturnT],
17
+ *,
18
+ name: str | None,
19
+ ) -> (
20
+ RoutedEndpoint[_Params, _ReturnT]
21
+ | Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]
22
+ ):
23
+ route_path = "" if callable(path) else path
24
+
25
+ def decorate(
26
+ function: Callable[Concatenate[Any, _Params], _ReturnT],
27
+ ) -> RoutedEndpoint[_Params, _ReturnT]:
28
+ if not isinstance(function, FunctionType):
29
+ msg = "Route decorators require instance methods and cannot be stacked."
30
+ raise RouteConfigurationError(msg)
31
+ return RoutedEndpoint(function, method=method, path=route_path, name=name)
32
+
33
+ return decorate(path) if callable(path) else decorate
34
+
35
+
36
+ @overload
37
+ def get(
38
+ path: Callable[Concatenate[Any, _Params], _ReturnT],
39
+ *,
40
+ name: str | None = None,
41
+ ) -> RoutedEndpoint[_Params, _ReturnT]: ...
42
+
43
+
44
+ @overload
45
+ def get(
46
+ path: str = "",
47
+ *,
48
+ name: str | None = None,
49
+ ) -> Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]: ...
50
+
51
+
52
+ def get(
53
+ path: str | Callable[Concatenate[Any, _Params], _ReturnT] = "",
54
+ *,
55
+ name: str | None = None,
56
+ ) -> (
57
+ RoutedEndpoint[_Params, _ReturnT]
58
+ | Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]
59
+ ):
60
+ """Declare a GET endpoint, above DMR's method decorators."""
61
+ return _route(HTTPMethod.GET, path, name=name)
62
+
63
+
64
+ @overload
65
+ def post(
66
+ path: Callable[Concatenate[Any, _Params], _ReturnT],
67
+ *,
68
+ name: str | None = None,
69
+ ) -> RoutedEndpoint[_Params, _ReturnT]: ...
70
+
71
+
72
+ @overload
73
+ def post(
74
+ path: str = "",
75
+ *,
76
+ name: str | None = None,
77
+ ) -> Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]: ...
78
+
79
+
80
+ def post(
81
+ path: str | Callable[Concatenate[Any, _Params], _ReturnT] = "",
82
+ *,
83
+ name: str | None = None,
84
+ ) -> (
85
+ RoutedEndpoint[_Params, _ReturnT]
86
+ | Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]
87
+ ):
88
+ """Declare a POST endpoint, above DMR's method decorators."""
89
+ return _route(HTTPMethod.POST, path, name=name)
90
+
91
+
92
+ @overload
93
+ def put(
94
+ path: Callable[Concatenate[Any, _Params], _ReturnT],
95
+ *,
96
+ name: str | None = None,
97
+ ) -> RoutedEndpoint[_Params, _ReturnT]: ...
98
+
99
+
100
+ @overload
101
+ def put(
102
+ path: str = "",
103
+ *,
104
+ name: str | None = None,
105
+ ) -> Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]: ...
106
+
107
+
108
+ def put(
109
+ path: str | Callable[Concatenate[Any, _Params], _ReturnT] = "",
110
+ *,
111
+ name: str | None = None,
112
+ ) -> (
113
+ RoutedEndpoint[_Params, _ReturnT]
114
+ | Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]
115
+ ):
116
+ """Declare a PUT endpoint, above DMR's method decorators."""
117
+ return _route(HTTPMethod.PUT, path, name=name)
118
+
119
+
120
+ @overload
121
+ def patch(
122
+ path: Callable[Concatenate[Any, _Params], _ReturnT],
123
+ *,
124
+ name: str | None = None,
125
+ ) -> RoutedEndpoint[_Params, _ReturnT]: ...
126
+
127
+
128
+ @overload
129
+ def patch(
130
+ path: str = "",
131
+ *,
132
+ name: str | None = None,
133
+ ) -> Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]: ...
134
+
135
+
136
+ def patch(
137
+ path: str | Callable[Concatenate[Any, _Params], _ReturnT] = "",
138
+ *,
139
+ name: str | None = None,
140
+ ) -> (
141
+ RoutedEndpoint[_Params, _ReturnT]
142
+ | Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]
143
+ ):
144
+ """Declare a PATCH endpoint, above DMR's method decorators."""
145
+ return _route(HTTPMethod.PATCH, path, name=name)
146
+
147
+
148
+ @overload
149
+ def delete(
150
+ path: Callable[Concatenate[Any, _Params], _ReturnT],
151
+ *,
152
+ name: str | None = None,
153
+ ) -> RoutedEndpoint[_Params, _ReturnT]: ...
154
+
155
+
156
+ @overload
157
+ def delete(
158
+ path: str = "",
159
+ *,
160
+ name: str | None = None,
161
+ ) -> Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]: ...
162
+
163
+
164
+ def delete(
165
+ path: str | Callable[Concatenate[Any, _Params], _ReturnT] = "",
166
+ *,
167
+ name: str | None = None,
168
+ ) -> (
169
+ RoutedEndpoint[_Params, _ReturnT]
170
+ | Callable[[Callable[Concatenate[Any, _Params], _ReturnT]], RoutedEndpoint[_Params, _ReturnT]]
171
+ ):
172
+ """Declare a DELETE endpoint, above DMR's method decorators."""
173
+ return _route(HTTPMethod.DELETE, path, name=name)
@@ -0,0 +1,87 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from functools import cached_property
5
+ from types import FunctionType, MethodType
6
+ from typing import TYPE_CHECKING, Any, Concatenate, Generic, ParamSpec, Self, TypeVar, cast, overload
7
+
8
+ from dmr_controller_group.exceptions import RouteConfigurationError
9
+
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Callable
13
+
14
+
15
+ _Params = ParamSpec("_Params")
16
+ _ReturnT_co = TypeVar("_ReturnT_co", covariant=True)
17
+
18
+
19
+ class RoutedEndpoint(Generic[_Params, _ReturnT_co]):
20
+ """An endpoint declaration that binds like the original instance method."""
21
+
22
+ def __init__(
23
+ self,
24
+ function: Callable[Concatenate[Any, _Params], _ReturnT_co],
25
+ *,
26
+ method: str,
27
+ path: str,
28
+ name: str | None,
29
+ ) -> None:
30
+ if not isinstance(path, str) or path.startswith("/"): # type: ignore[redundant-expr]
31
+ msg = "Route paths must be relative strings using Django path() syntax."
32
+ raise RouteConfigurationError(msg)
33
+
34
+ if name is not None and (not isinstance(name, str) or not name): # type: ignore[redundant-expr]
35
+ msg = "A URL name must be a nonempty string or None."
36
+ raise RouteConfigurationError(msg)
37
+
38
+ self.function = function
39
+ self.method = method
40
+ self.path = path
41
+ self.name = name
42
+ self.owner: type | None = None
43
+ self.attribute: str | None = None
44
+
45
+ @cached_property
46
+ def is_async(self) -> bool:
47
+ """Whether the declared handler is a coroutine function."""
48
+ return inspect.iscoroutinefunction(self.function)
49
+
50
+ def __set_name__(self, owner: type, name: str) -> None:
51
+ self.owner = owner
52
+ self.attribute = name
53
+
54
+ @overload
55
+ def __get__(self, instance: None, owner: type | None = None) -> Self: ...
56
+
57
+ @overload
58
+ def __get__(self, instance: object, owner: type | None = None) -> Callable[_Params, _ReturnT_co]: ...
59
+
60
+ def __get__(self, instance: object | None, owner: type | None = None) -> Self | Callable[_Params, _ReturnT_co]:
61
+ if instance is None:
62
+ return self
63
+ return cast("Callable[_Params, _ReturnT_co]", MethodType(self.function, instance))
64
+
65
+ def __call__(self, instance: object, /, *args: _Params.args, **kwargs: _Params.kwargs) -> _ReturnT_co:
66
+ return self.function(instance, *args, **kwargs)
67
+
68
+ def as_method(self) -> FunctionType:
69
+ """Clone the handler under its HTTP name, isolating DMR's mutations."""
70
+ original = self.function
71
+
72
+ clone = FunctionType(
73
+ original.__code__, original.__globals__, self.method.lower(), original.__defaults__, original.__closure__
74
+ )
75
+ clone.__kwdefaults__ = None if original.__kwdefaults__ is None else original.__kwdefaults__.copy()
76
+ clone.__module__ = original.__module__
77
+ clone.__qualname__ = original.__qualname__
78
+ clone.__doc__ = original.__doc__
79
+ clone.__type_params__ = original.__type_params__
80
+ clone.__annotate__ = original.__annotate__
81
+ if original.__annotate__ is None:
82
+ clone.__annotations__ = original.__annotations__.copy()
83
+ clone.__dict__.update(original.__dict__)
84
+ return clone
85
+
86
+
87
+ AnyRoutedEndpoint = RoutedEndpoint[..., Any]
@@ -0,0 +1,2 @@
1
+ class RouteConfigurationError(ValueError):
2
+ """An invalid routed controller declaration."""
@@ -0,0 +1,137 @@
1
+ from __future__ import annotations
2
+
3
+ from types import GenericAlias
4
+ from typing import TYPE_CHECKING, Any, ClassVar, Generic, Protocol, TypeVar, cast
5
+
6
+ from dmr import Controller
7
+ from dmr.routing import path
8
+ from dmr.serializer import BaseSerializer
9
+ from dmr.types import infer_annotation, safe_typevar
10
+
11
+ from dmr_controller_group._controllers import build_controller, validate_base_controller
12
+ from dmr_controller_group._routes import collect_routes
13
+ from dmr_controller_group.exceptions import RouteConfigurationError
14
+
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Mapping, Sequence, Set as AbstractSet
18
+ from http import HTTPStatus
19
+
20
+ from django.http import HttpRequest, HttpResponse
21
+ from django.urls import URLPattern
22
+ from django_stubs_ext import StrOrPromise
23
+ from dmr.cookies import NewCookie
24
+ from dmr.endpoint import Endpoint
25
+ from dmr.errors import ErrorType
26
+ from dmr.metadata import ResponseSpec
27
+ from dmr.openapi.objects import Callback, ExternalDocumentation, Reference, SecurityRequirement, Server
28
+ from dmr.renderers import Renderer
29
+ from dmr.types import EMPTY
30
+
31
+
32
+ _ControllerT = TypeVar("_ControllerT", bound=Controller[BaseSerializer])
33
+ _SerializerT_co = TypeVar("_SerializerT_co", bound=BaseSerializer, covariant=True, default=BaseSerializer)
34
+
35
+
36
+ class ControllerDecorator(Protocol):
37
+ """A decorator applied to each completed DMR controller."""
38
+
39
+ def __call__(self, controller: type[_ControllerT], /) -> type[_ControllerT]: ...
40
+
41
+
42
+ class ControllerGroup(Generic[_SerializerT_co]):
43
+ """Declare related routes compiled into ordinary DMR controllers per path."""
44
+
45
+ base_controller_cls: ClassVar[type[Controller[BaseSerializer]] | None] = None
46
+ controller_decorators: ClassVar[Sequence[ControllerDecorator]] = ()
47
+
48
+ @classmethod
49
+ def as_urls(cls) -> list[URLPattern]:
50
+ """Build independent controllers and URL patterns in declaration order."""
51
+ base_controller_cls = cls.base_controller_cls
52
+
53
+ if base_controller_cls is None:
54
+ serializer = infer_annotation(safe_typevar("_SerializerT_co"), cls)
55
+ if serializer is BaseSerializer:
56
+ msg = f"{cls.__qualname__} requires ControllerGroup[Serializer] or base_controller_cls."
57
+ raise RouteConfigurationError(msg)
58
+
59
+ # Default to the standard Controller base with the group's serializer.
60
+ base_controller_cls = cast("type[Controller[BaseSerializer]]", GenericAlias(Controller, serializer))
61
+ else:
62
+ validate_base_controller(cls, base_controller_cls)
63
+
64
+ routes = collect_routes(cls)
65
+
66
+ if not routes:
67
+ msg = f"{cls.__qualname__} requires at least one route."
68
+ raise RouteConfigurationError(msg)
69
+
70
+ return [
71
+ path(route.path, build_controller(cls, base_controller_cls, route).as_view(), name=route.name)
72
+ for route in routes
73
+ ]
74
+
75
+ # These members are supplied by the DMR base on generated instances.
76
+ # No runtime stubs: they would mask the actual DMR implementations in the MRO.
77
+ if TYPE_CHECKING:
78
+ summary: ClassVar[StrOrPromise | EMPTY | None]
79
+ description: ClassVar[StrOrPromise | EMPTY | None]
80
+ tags: ClassVar[Sequence[str] | EMPTY | None]
81
+ servers: ClassVar[Sequence[Server] | EMPTY | None]
82
+ security: ClassVar[Sequence[SecurityRequirement] | EMPTY | None]
83
+ deprecated: ClassVar[bool | EMPTY]
84
+ external_docs: ClassVar[ExternalDocumentation | EMPTY | None]
85
+ callbacks: ClassVar[Mapping[str, Callback | Reference] | EMPTY | None]
86
+ x_extensions: ClassVar[Mapping[str, Any] | None]
87
+ ignore_from_spec: ClassVar[bool]
88
+
89
+ endpoint_cls: ClassVar[type[Endpoint]]
90
+ responses: ClassVar[Sequence[ResponseSpec] | EMPTY | None]
91
+ semantic_schema: ClassVar[bool | EMPTY]
92
+ semantic_responses: ClassVar[bool | EMPTY]
93
+ exclude_semantic_responses: ClassVar[AbstractSet[HTTPStatus] | EMPTY | None]
94
+ semantic_auth: bool | EMPTY
95
+ exclude_semantic_auth: AbstractSet[str] | EMPTY | None
96
+
97
+ request: HttpRequest
98
+ args: tuple[Any, ...]
99
+ kwargs: dict[str, Any]
100
+ api_endpoints: ClassVar[Mapping[str, Endpoint]]
101
+ is_async: ClassVar[bool | None]
102
+
103
+ def to_response(
104
+ self,
105
+ raw_data: Any,
106
+ *,
107
+ status_code: HTTPStatus | None = None,
108
+ headers: Mapping[str, str] | None = None,
109
+ cookies: Mapping[str, NewCookie] | None = None,
110
+ renderer: Renderer | None = None,
111
+ ) -> HttpResponse: ...
112
+
113
+ def to_error(
114
+ self,
115
+ raw_data: Any,
116
+ *,
117
+ status_code: HTTPStatus,
118
+ headers: Mapping[str, str] | None = None,
119
+ cookies: Mapping[str, NewCookie] | None = None,
120
+ renderer: Renderer | None = None,
121
+ ) -> HttpResponse: ...
122
+
123
+ def format_error(
124
+ self,
125
+ error: str | Exception,
126
+ *,
127
+ loc: str | list[str | int] | None = None,
128
+ error_type: str | ErrorType | None = None,
129
+ ) -> Any: ...
130
+
131
+ def handle_error(
132
+ self, endpoint: Endpoint, controller: Controller[BaseSerializer], exc: Exception
133
+ ) -> HttpResponse: ...
134
+
135
+ async def handle_async_error(
136
+ self, endpoint: Endpoint, controller: Controller[BaseSerializer], exc: Exception
137
+ ) -> HttpResponse: ...
File without changes
@@ -0,0 +1,195 @@
1
+ Metadata-Version: 2.5
2
+ Name: dmr-controller-group
3
+ Version: 0.0.1
4
+ Summary: Route decorators for django-modern-rest controller methods
5
+ Author-email: Demin Vadim <demin02vadim@gmail.com>
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: django-modern-rest<0.18,>=0.17
9
+ Requires-Dist: django<6.2,>=5
10
+ Description-Content-Type: text/markdown
11
+
12
+ # dmr-controller-group
13
+
14
+ <div align="left">
15
+
16
+ [![Modern REST](https://img.shields.io/badge/Modern%20REST-0C4B33?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4MCIgaGVpZ2h0PSIxMDgwIiB2aWV3Qm94PSIwIDAgMTA4MCAxMDgwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMiA3MDQuMDJMMTQ1LjQ1OSA0NjYuMTlMMjc3Ljg4MyA3MDQuMDJMMTQ1LjQ1OSA5NDEuODQ5TDIgNzA0LjAyWiIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTE0NS40NTkgOTQxLjg0OUwyIDcwNC4wMkgyNzcuODgzTDE0NS40NTkgOTQxLjg0OVoiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik02NzguOTQ4IDcwNC4wMzVMMzQxLjIzIDEzOEwyMjcuMDcxIDMyOC4yNjRMNDM2LjM2MiA3MDQuMDM1TDMwMy4xNzcgOTQxLjg2NEg1MzYuMjVMNjc4Ljk0OCA3MDQuMDM1WiIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTY3OC45MzcgNzA0LjAyNkg0MzYuMzVMMzAzLjE2NiA5NDEuODU2SDUzNi4yMzlMNjc4LjkzNyA3MDQuMDI2WiIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTEwNzguMTcgNzA0LjAzNUw3NDAuNDUxIDEzOEw2MjYuMjkzIDMyOC4yNjRMODM1LjU4MyA3MDQuMDM1TDcwMi4zOTkgOTQxLjg2NEg5MzUuNDcyTDEwNzguMTcgNzA0LjAzNVoiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGQ9Ik0xMDc4LjE3IDcwNC4wMzVIODM1LjU4M0w3MDIuMzk5IDk0MS44NjRIOTM1LjQ3MkwxMDc4LjE3IDcwNC4wMzVaIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K&color=35544A)](https://github.com/wemake-services/django-modern-rest)
17
+ [![Supported Python Version](https://img.shields.io/pypi/pyversions/django-modern-rest.svg)](https://pypi.org/project/django-modern-rest/)
18
+
19
+ </div>
20
+
21
+ An extension for [django-modern-rest](https://github.com/wemake-services/django-modern-rest)
22
+ that groups related endpoints in a single `ControllerGroup` class,
23
+ lets you name handlers freely, and defines HTTP methods and routes through decorators.
24
+
25
+ Calling `as_urls()` creates a separate `Controller` class for each unique path.
26
+ Handlers with the same path and different HTTP methods share a controller.
27
+ DMR's mechanisms remain unchanged: endpoint creation, validation, serialization,
28
+ authentication, throttling, dispatch, and OpenAPI generation are handled by DMR.
29
+ Handlers support standard DMR decorators: `modify`, `validate`, their `.lazy`
30
+ variants, and `endpoint_decorator`. Place the route decorator (`@get`, `@post`,
31
+ and others) above them. Use `base_controller_cls` to provide a custom abstract
32
+ `Controller` with shared settings, methods, and schema hooks.
33
+
34
+ Works for:
35
+ - CPython 3.11+
36
+ - Django >=5.0,<6.2
37
+ - django-modern-rest 0.17
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ pip install dmr-controller-group
43
+ ```
44
+
45
+ See the [installation guide](https://dmr-controller-group.readthedocs.io/en/latest/pages/installation.html) for uv and Poetry commands.
46
+
47
+ ## Example
48
+
49
+ ```python
50
+ import uuid
51
+ from http import HTTPStatus
52
+
53
+ from dmr import Body, Path, modify
54
+ from dmr.plugins.pydantic import PydanticSerializer
55
+ from dmr.routing import Router
56
+ from pydantic import BaseModel
57
+
58
+ from dmr_controller_group import ControllerGroup, delete, get, post
59
+
60
+
61
+ class NewPost(BaseModel):
62
+ title: str
63
+
64
+
65
+ class PostUid(BaseModel):
66
+ post_uid: uuid.UUID
67
+
68
+
69
+ class Posts(ControllerGroup[PydanticSerializer]):
70
+ tags = ("Posts",)
71
+
72
+ @get(name="posts")
73
+ def listing(self) -> list[str]:
74
+ return ["First post"]
75
+
76
+ @post
77
+ def create(self, parsed_body: Body[NewPost]) -> NewPost:
78
+ return parsed_body
79
+
80
+ @post("<uuid:post_uid>/approve/", name="post-approve")
81
+ @modify(status_code=HTTPStatus.OK)
82
+ def approve(self, parsed_path: Path[PostUid]) -> str:
83
+ return f"Approved {parsed_path.post_uid}"
84
+
85
+ @post("<uuid:post_uid>/reject/", name="post-reject")
86
+ @modify(status_code=HTTPStatus.OK)
87
+ def reject(self, parsed_path: Path[PostUid]) -> str:
88
+ return f"Rejected {parsed_path.post_uid}"
89
+
90
+ @delete("<uuid:post_uid>/")
91
+ @modify(status_code=HTTPStatus.NO_CONTENT)
92
+ def destroy(self, parsed_path: Path[PostUid]) -> None:
93
+ return None
94
+
95
+
96
+ router = Router("api/posts/", Posts.as_urls())
97
+ urlpatterns = [router.to_urlpatterns()]
98
+ ```
99
+
100
+ ## Route decorators
101
+
102
+ The example above creates four controller classes: one with `get` and `post` for the empty path,
103
+ two with `post` for the approval and rejection paths, and one with `delete` for the object path.
104
+
105
+ The following route decorators are available:
106
+
107
+ - `@get` — declares a handler for `GET` requests.
108
+ - `@post` — declares a handler for `POST` requests.
109
+ - `@put` — declares a handler for `PUT` requests.
110
+ - `@patch` — declares a handler for `PATCH` requests.
111
+ - `@delete` — declares a handler for `DELETE` requests.
112
+
113
+ > [!TIP]
114
+ > All decorators default to `path=""`: you can write
115
+ > `@get()`, `@post()`, `@put()`, `@patch()`, and `@delete()`.
116
+ > With no arguments, parentheses are optional: `@get`, `@post`, `@put`, `@patch`,
117
+ > and `@delete` are equivalent to calls with an empty path. Use parentheses
118
+ > to pass `path` or `name`: `@get("details/")`, `@get(name="posts")`.
119
+
120
+ ## Configuration and error handling
121
+
122
+ `ControllerGroup[Serializer]` uses the standard DMR `Controller`.
123
+ The serializer type parameter is inherited and can be specialized in subclasses.
124
+ A custom `base_controller_cls` takes priority and lets you omit the type parameter.
125
+ If neither a serializer nor a base controller is provided, `as_urls()` raises a configuration error.
126
+
127
+ > [!NOTE]
128
+ > You can override configurable `Controller` attributes directly on the group:
129
+ > `auth`, `throttling`, `parsers`, `renderers`, `responses`, `validate_responses`,
130
+ > `endpoint_cls`, OpenAPI settings, and others. They apply to every path in the group
131
+ > and take priority over values from `base_controller_cls`.
132
+
133
+ ```python
134
+ from dmr import Controller
135
+ from dmr.plugins.pydantic import PydanticSerializer
136
+ from dmr.routing import Router
137
+
138
+ from dmr_controller_group import ControllerGroup, get
139
+
140
+
141
+ class ProjectController(Controller[PydanticSerializer]):
142
+ is_abstract = True
143
+
144
+
145
+ class CustomPosts(ControllerGroup):
146
+ base_controller_cls = ProjectController
147
+ tags = ("Posts",)
148
+ validate_responses = True
149
+
150
+ @get(name="posts")
151
+ def listing(self) -> list[str]:
152
+ return ["First post"]
153
+
154
+
155
+ router = Router("api/posts/", CustomPosts.as_urls())
156
+ urlpatterns = [router.to_urlpatterns()]
157
+ ```
158
+
159
+ `ProjectController` provides the DMR base and serializer, while `CustomPosts`
160
+ declares routes through `ControllerGroup`. The `base_controller_cls` attribute connects them.
161
+
162
+ > [!IMPORTANT]
163
+ > The base controller must be abstract, have a concrete serializer, and define no
164
+ > HTTP handlers. The `meta` method and DMR's OPTIONS mixins are allowed.
165
+
166
+ Generated controllers inherit from the group and the selected base controller,
167
+ including its settings, methods, and schema hooks. The group can define `handle_error`
168
+ (sync) and `handle_async_error` (async); otherwise, the base controller's hooks are used.
169
+ Declare custom base methods on the group for type checking when needed.
170
+ See [configuration and error handling](https://dmr-controller-group.readthedocs.io/en/latest/pages/configuration.html) for details.
171
+
172
+ ## Routing and OpenAPI
173
+
174
+ Methods with route decorators can still be called through an instance and `super()`.
175
+ Paths are relative and use Django's `path()` syntax.
176
+
177
+ - Each path has one controller and one URL name; setting `name` on one handler is enough.
178
+ Duplicate path and HTTP method pairs are not allowed.
179
+ - Routes declared on the group precede inherited routes, in declaration order.
180
+ Repeat the route decorator when overriding a handler.
181
+ - `HEAD` and `OPTIONS` are not added automatically. Enable OPTIONS through the base controller.
182
+
183
+ > [!IMPORTANT]
184
+ > Handlers for the same path, including `meta`, must all use `def` or all use `async def`.
185
+ > A group can combine `def` and `async def` handlers for different paths.
186
+
187
+ Each `as_urls()` call creates independent controllers and URL patterns with stable class names.
188
+ See the [routing rules](https://dmr-controller-group.readthedocs.io/en/latest/pages/routing.html) for details.
189
+
190
+ ## Documentation
191
+
192
+ [Full documentation](https://dmr-controller-group.readthedocs.io/en/latest/)
193
+
194
+ ## License
195
+ [MIT](LICENSE)
@@ -0,0 +1,13 @@
1
+ dmr_controller_group/__init__.py,sha256=4Ss_GUDc6nqd6SbIxi1iootg9WzX40PEQh52JPHd0cI,230
2
+ dmr_controller_group/__metadata__.py,sha256=nYU7qoEPeUIs3oq2BRo7J5dlXXGxmh7tL9B268J2EzU,255
3
+ dmr_controller_group/_controllers.py,sha256=MUHtJ8M_ELkhe1pJ-Aptx2plI5ZIUmOnr8jcLya59UQ,2999
4
+ dmr_controller_group/_routes.py,sha256=apQZ0BPYVra1bEob9Q53WTWe5mlqs7e6duP7aR8QJUo,3346
5
+ dmr_controller_group/decorators.py,sha256=U5Bff1cTPPdrXKxK8MO5i2Ex3qTYl-m5HxxSV0qxJBc,4734
6
+ dmr_controller_group/endpoints.py,sha256=r8yoyT-3cl9HEqJOLnlUEBbBLJ0zjKHO8dHr7z34ge4,3249
7
+ dmr_controller_group/exceptions.py,sha256=4CUGnZ0PM_Rs5bgrCfeEM8PIsWh_YpQRltJXW_rSXbU,95
8
+ dmr_controller_group/groups.py,sha256=NgknGNa4vguOgxzDVwvYXWlQW3Oc5jxN5r9GMsSdMDc,5441
9
+ dmr_controller_group/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ dmr_controller_group-0.0.1.dist-info/METADATA,sha256=A14KxfGIwZKpPeXbiHW-QGyCAiaB82fv2jaIGYZyzBg,8112
11
+ dmr_controller_group-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ dmr_controller_group-0.0.1.dist-info/licenses/LICENSE,sha256=vw3e72AQCvHGMAYwtEp230rIa0qT4fJ3RJRS3jwj-Hg,1077
13
+ dmr_controller_group-0.0.1.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,20 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2026 Demin Vadim
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
20
+ OR OTHER DEALINGS IN THE SOFTWARE.