|
| 1 | +from django import VERSION as DJANGO_VERSION |
| 2 | +from django.db import models |
| 3 | +from django.urls import path |
| 4 | +from django.utils.decorators import classonlymethod |
| 5 | +from django.views.decorators.csrf import csrf_exempt |
| 6 | + |
| 7 | +from rest_framework.views import APIView |
| 8 | + |
| 9 | + |
| 10 | +class RESTViewMethod: |
| 11 | + |
| 12 | + def __init__( |
| 13 | + self, |
| 14 | + http_method: str, |
| 15 | + path: str, |
| 16 | + url_name: str, |
| 17 | + view_method |
| 18 | + ): |
| 19 | + self.http_method = http_method |
| 20 | + self.path = path |
| 21 | + self.url_name = url_name |
| 22 | + self.view_method = view_method |
| 23 | + |
| 24 | + |
| 25 | +def get(path: str, url_name: str): |
| 26 | + def decorator(view_method): |
| 27 | + return RESTViewMethod( |
| 28 | + http_method='get', |
| 29 | + path=path, |
| 30 | + url_name=url_name, |
| 31 | + view_method=view_method, |
| 32 | + ) |
| 33 | + |
| 34 | + return decorator |
| 35 | + |
| 36 | + |
| 37 | +def post(path: str, url_name: str): |
| 38 | + def decorator(view_method): |
| 39 | + return RESTViewMethod( |
| 40 | + http_method='post', |
| 41 | + path=path, |
| 42 | + url_name=url_name, |
| 43 | + view_method=view_method, |
| 44 | + ) |
| 45 | + |
| 46 | + return decorator |
| 47 | + |
| 48 | + |
| 49 | +def put(path: str, url_name: str): |
| 50 | + def decorator(view_method): |
| 51 | + return RESTViewMethod( |
| 52 | + http_method='put', |
| 53 | + path=path, |
| 54 | + url_name=url_name, |
| 55 | + view_method=view_method, |
| 56 | + ) |
| 57 | + |
| 58 | + return decorator |
| 59 | + |
| 60 | + |
| 61 | +def patch(path: str, url_name: str): |
| 62 | + def decorator(view_method): |
| 63 | + return RESTViewMethod( |
| 64 | + http_method='patch', |
| 65 | + path=path, |
| 66 | + url_name=url_name, |
| 67 | + view_method=view_method, |
| 68 | + ) |
| 69 | + |
| 70 | + return decorator |
| 71 | + |
| 72 | + |
| 73 | +def delete(path: str, url_name: str): |
| 74 | + def decorator(view_method): |
| 75 | + return RESTViewMethod( |
| 76 | + http_method='delete', |
| 77 | + path=path, |
| 78 | + url_name=url_name, |
| 79 | + view_method=view_method, |
| 80 | + ) |
| 81 | + |
| 82 | + return decorator |
| 83 | + |
| 84 | + |
| 85 | +class RESTViewMetaclass(type): |
| 86 | + |
| 87 | + def __new__(cls, name, bases, attrs): |
| 88 | + _all_actions: dict[str, list[tuple[str, str, str]]] = {} |
| 89 | + http_method_path_pairs = set() |
| 90 | + url_names_by_path = {} |
| 91 | + |
| 92 | + for key, value in attrs.items(): |
| 93 | + if isinstance(value, RESTViewMethod): |
| 94 | + if (value.http_method, value.path) in http_method_path_pairs: |
| 95 | + raise ValueError(f"{cls.__name__} has multiple methods with the same HTTP method and path") |
| 96 | + |
| 97 | + http_method_path_pairs.add((value.http_method, value.path)) |
| 98 | + |
| 99 | + url_names_by_path.setdefault(value.path, set()).add(value.url_name) |
| 100 | + if len(url_names_by_path[value.path]) > 1: |
| 101 | + raise ValueError( |
| 102 | + f"{cls.__name__} has multiple methods with the same path {value.path}, but different URL names" |
| 103 | + ) |
| 104 | + |
| 105 | + http_method_path_pairs.add((value.http_method, value.path)) |
| 106 | + _all_actions.setdefault(value.path, []) |
| 107 | + _all_actions[value.path].append((value.http_method, value.view_method.__name__, value.url_name)) |
| 108 | + attrs[key] = value.view_method |
| 109 | + |
| 110 | + attrs['_all_actions'] = _all_actions |
| 111 | + return type.__new__(cls, name, bases, attrs) |
| 112 | + |
| 113 | + |
| 114 | +class RESTView(APIView, metaclass=RESTViewMetaclass): |
| 115 | + """ |
| 116 | + A View that allows handling any HTTP methods and URL paths. Use special decorators to specify URl path |
| 117 | + and URl name for handlers. These decorators moved to a class attribute at runtime. |
| 118 | +
|
| 119 | + Example: |
| 120 | + class UserAPI(RESTView): |
| 121 | +
|
| 122 | + @get(path='/v1/users/', url_name='users') |
| 123 | + def list(self, request): |
| 124 | + ... |
| 125 | +
|
| 126 | + @get(path='/v1/users/<int:user_id>/', url_name='user_detail') |
| 127 | + def retrieve(self, request, user_id: int): |
| 128 | + ... |
| 129 | +
|
| 130 | + @post(path='/v1/users/', url_name='users') |
| 131 | + def create(self, request): |
| 132 | + ... |
| 133 | +
|
| 134 | + @patch(path='/v1/users/<int:user_id>/change_password/', url_name='user_change_password') |
| 135 | + def change_password(self, request, user_id: int): |
| 136 | + ... |
| 137 | +
|
| 138 | + To use this View, you have to comply with these rules: |
| 139 | + 1. Use special decorators for all handlers |
| 140 | + 2. All identical URL paths must have identical URL names |
| 141 | + 3. Special decorators have to be the last in order |
| 142 | + 4. All custom decorators have to be wrapped with functools.wraps or manually copy the docstrings |
| 143 | + """ |
| 144 | + |
| 145 | + @classonlymethod |
| 146 | + def unwrap_url_patterns(cls, **initkwargs): |
| 147 | + """ |
| 148 | + Create classes for all URL paths for Django urlpatterns interface |
| 149 | +
|
| 150 | + Example: |
| 151 | + urlpatterns = [ |
| 152 | + *UserAPI.unwrap_url_patterns(), |
| 153 | + ] |
| 154 | + """ |
| 155 | + urlpatterns = [] |
| 156 | + for url_path, attrs in cls._all_actions.items(): |
| 157 | + view = cls.as_view(url_path=url_path, **initkwargs) |
| 158 | + urlpatterns.append(path(url_path, view, name=attrs[0][2])) |
| 159 | + |
| 160 | + return urlpatterns |
| 161 | + |
| 162 | + @classmethod |
| 163 | + def as_view(cls, url_path: str, **initkwargs): |
| 164 | + """ |
| 165 | + Store the generated class on the view function for URL path. Don't use this method. |
| 166 | + """ |
| 167 | + if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet): |
| 168 | + def force_evaluation(): |
| 169 | + raise RuntimeError( |
| 170 | + 'Do not evaluate the `.queryset` attribute directly, ' |
| 171 | + 'as the result will be cached and reused between requests. ' |
| 172 | + 'Use `.all()` or call `.get_queryset()` instead.' |
| 173 | + ) |
| 174 | + cls.queryset._fetch_all = force_evaluation |
| 175 | + |
| 176 | + fork_cls = type(cls.__name__, cls.__bases__, dict(cls.__dict__)) |
| 177 | + actions = {} |
| 178 | + for http_method, view_method_name, url_name in cls._all_actions[url_path]: |
| 179 | + actions[http_method] = view_method_name |
| 180 | + |
| 181 | + if 'get' in actions and 'head' not in actions: |
| 182 | + actions['head'] = actions['get'] |
| 183 | + |
| 184 | + if 'options' not in actions: |
| 185 | + # use ApiView.options |
| 186 | + actions['options'] = 'options' |
| 187 | + |
| 188 | + fork_cls.actions = actions |
| 189 | + view = super(APIView, fork_cls).as_view(**initkwargs) |
| 190 | + view.cls = fork_cls |
| 191 | + view.initkwargs = initkwargs |
| 192 | + |
| 193 | + # Exempt all DRF views from Django's LoginRequiredMiddleware. Users should set |
| 194 | + # DEFAULT_PERMISSION_CLASSES to 'rest_framework.permissions.IsAuthenticated' instead |
| 195 | + if DJANGO_VERSION >= (5, 1): |
| 196 | + view.login_required = False |
| 197 | + |
| 198 | + # Note: session based authentication is explicitly CSRF validated, |
| 199 | + # all other authentication is CSRF exempt. |
| 200 | + return csrf_exempt(view) |
| 201 | + |
| 202 | + def dispatch(self, request, *args, **kwargs): |
| 203 | + """ |
| 204 | + `.dispatch()` is pretty much the same as ApiView dispatch |
| 205 | + """ |
| 206 | + self.args = args |
| 207 | + self.kwargs = kwargs |
| 208 | + request = self.initialize_request(request, *args, **kwargs) |
| 209 | + self.request = request |
| 210 | + self.headers = self.default_response_headers # deprecate? |
| 211 | + |
| 212 | + try: |
| 213 | + self.initial(request, *args, **kwargs) |
| 214 | + |
| 215 | + view_method_name = self.actions.get(request.method.lower()) |
| 216 | + handler = ( |
| 217 | + getattr(self, view_method_name, self.http_method_not_allowed) |
| 218 | + if view_method_name |
| 219 | + else self.http_method_not_allowed |
| 220 | + ) |
| 221 | + response = handler(request, *args, **kwargs) |
| 222 | + |
| 223 | + except Exception as exc: |
| 224 | + response = self.handle_exception(exc) |
| 225 | + |
| 226 | + self.response = self.finalize_response(request, response, *args, **kwargs) |
| 227 | + return self.response |
| 228 | + |
| 229 | + |
| 230 | +__all__ = ['get', 'post', 'put', 'patch', 'delete', 'RESTView'] |
0 commit comments