| 1 |
""" |
| 2 |
The most important decorator in this module is `@api_view`, which is used |
| 3 |
for writing function-based views with REST framework. |
| 4 |
|
| 5 |
There are also various decorators for setting the API policies on function |
| 6 |
based views, as well as the `@action` decorator, which is used to annotate |
| 7 |
methods on viewsets that should be included by routers. |
| 8 |
""" |
| 9 |
import types |
| 10 |
|
| 11 |
from django.forms.utils import pretty_name |
| 12 |
|
| 13 |
from rest_framework.views import APIView |
| 14 |
|
| 15 |
|
| 16 |
def api_view(http_method_names=None): |
| 17 |
""" |
| 18 |
Decorator that converts a function-based view into an APIView subclass. |
| 19 |
Takes a list of allowed methods for the view as an argument. |
| 20 |
""" |
| 21 |
http_method_names = ['GET'] if (http_method_names is None) else http_method_names |
| 22 |
|
| 23 |
def decorator(func): |
| 24 |
|
| 25 |
WrappedAPIView = type( |
| 26 |
'WrappedAPIView', |
| 27 |
(APIView,), |
| 28 |
{'__doc__': func.__doc__} |
| 29 |
) |
| 30 |
|
| 31 |
# Note, the above allows us to set the docstring. |
| 32 |
# It is the equivalent of: |
| 33 |
# |
| 34 |
# class WrappedAPIView(APIView): |
| 35 |
# pass |
| 36 |
# WrappedAPIView.__doc__ = func.doc <--- Not possible to do this |
| 37 |
|
| 38 |
# api_view applied without (method_names) |
| 39 |
assert not isinstance(http_method_names, types.FunctionType), \ |
| 40 |
'@api_view missing list of allowed HTTP methods' |
| 41 |
|
| 42 |
# api_view applied with eg. string instead of list of strings |
| 43 |
assert isinstance(http_method_names, (list, tuple)), \ |
| 44 |
'@api_view expected a list of strings, received %s' % type(http_method_names).__name__ |
| 45 |
|
| 46 |
allowed_methods = set(http_method_names) | {'options'} |
| 47 |
WrappedAPIView.http_method_names = [method.lower() for method in allowed_methods] |
| 48 |
|
| 49 |
def handler(self, *args, **kwargs): |
| 50 |
return func(*args, **kwargs) |
| 51 |
|
| 52 |
for method in http_method_names: |
| 53 |
setattr(WrappedAPIView, method.lower(), handler) |
| 54 |
|
| 55 |
WrappedAPIView.__name__ = func.__name__ |
| 56 |
WrappedAPIView.__module__ = func.__module__ |
| 57 |
|
| 58 |
WrappedAPIView.renderer_classes = getattr(func, 'renderer_classes', |
| 59 |
APIView.renderer_classes) |
| 60 |
|
| 61 |
WrappedAPIView.parser_classes = getattr(func, 'parser_classes', |
| 62 |
APIView.parser_classes) |
| 63 |
|
| 64 |
WrappedAPIView.authentication_classes = getattr(func, 'authentication_classes', |
| 65 |
APIView.authentication_classes) |
| 66 |
|
| 67 |
WrappedAPIView.throttle_classes = getattr(func, 'throttle_classes', |
| 68 |
APIView.throttle_classes) |
| 69 |
|
| 70 |
WrappedAPIView.throttle_scope = getattr(func, 'throttle_scope', |
| 71 |
None) |
| 72 |
|
| 73 |
WrappedAPIView.permission_classes = getattr(func, 'permission_classes', |
| 74 |
APIView.permission_classes) |
| 75 |
|
| 76 |
WrappedAPIView.content_negotiation_class = getattr(func, 'content_negotiation_class', |
| 77 |
APIView.content_negotiation_class) |
| 78 |
|
| 79 |
WrappedAPIView.metadata_class = getattr(func, 'metadata_class', |
| 80 |
APIView.metadata_class) |
| 81 |
|
| 82 |
WrappedAPIView.versioning_class = getattr(func, "versioning_class", |
| 83 |
APIView.versioning_class) |
| 84 |
|
| 85 |
WrappedAPIView.schema = getattr(func, 'schema', |
| 86 |
APIView.schema) |
| 87 |
|
| 88 |
return WrappedAPIView.as_view() |
| 89 |
|
| 90 |
return decorator |
| 91 |
|
| 92 |
|
| 93 |
def _check_decorator_order(func, decorator_name): |
| 94 |
""" |
| 95 |
Check if an API policy decorator is being applied after @api_view. |
| 96 |
""" |
| 97 |
# Check if func is actually a view function (result of APIView.as_view()) |
| 98 |
if hasattr(func, 'cls') and issubclass(func.cls, APIView): |
| 99 |
raise TypeError( |
| 100 |
f"@{decorator_name} must come after (below) the @api_view decorator. " |
| 101 |
"The correct order is:\n\n" |
| 102 |
" @api_view(['GET'])\n" |
| 103 |
f" @{decorator_name}(...)\n" |
| 104 |
" def my_view(request):\n" |
| 105 |
" ...\n\n" |
| 106 |
"See https://www.django-rest-framework.org/api-guide/views/#api-policy-decorators" |
| 107 |
) |
| 108 |
|
| 109 |
|
| 110 |
def renderer_classes(renderer_classes): |
| 111 |
def decorator(func): |
| 112 |
_check_decorator_order(func, 'renderer_classes') |
| 113 |
func.renderer_classes = renderer_classes |
| 114 |
return func |
| 115 |
return decorator |
| 116 |
|
| 117 |
|
| 118 |
def parser_classes(parser_classes): |
| 119 |
def decorator(func): |
| 120 |
_check_decorator_order(func, 'parser_classes') |
| 121 |
func.parser_classes = parser_classes |
| 122 |
return func |
| 123 |
return decorator |
| 124 |
|
| 125 |
|
| 126 |
def authentication_classes(authentication_classes): |
| 127 |
def decorator(func): |
| 128 |
_check_decorator_order(func, 'authentication_classes') |
| 129 |
func.authentication_classes = authentication_classes |
| 130 |
return func |
| 131 |
return decorator |
| 132 |
|
| 133 |
|
| 134 |
def throttle_classes(throttle_classes): |
| 135 |
def decorator(func): |
| 136 |
_check_decorator_order(func, 'throttle_classes') |
| 137 |
func.throttle_classes = throttle_classes |
| 138 |
return func |
| 139 |
return decorator |
| 140 |
|
| 141 |
|
| 142 |
def throttle_scope(throttle_scope): |
| 143 |
def decorator(func): |
| 144 |
_check_decorator_order(func, 'throttle_scope') |
| 145 |
func.throttle_scope = throttle_scope |
| 146 |
return func |
| 147 |
return decorator |
| 148 |
|
| 149 |
|
| 150 |
def permission_classes(permission_classes): |
| 151 |
def decorator(func): |
| 152 |
_check_decorator_order(func, 'permission_classes') |
| 153 |
func.permission_classes = permission_classes |
| 154 |
return func |
| 155 |
return decorator |
| 156 |
|
| 157 |
|
| 158 |
def content_negotiation_class(content_negotiation_class): |
| 159 |
def decorator(func): |
| 160 |
_check_decorator_order(func, 'content_negotiation_class') |
| 161 |
func.content_negotiation_class = content_negotiation_class |
| 162 |
return func |
| 163 |
return decorator |
| 164 |
|
| 165 |
|
| 166 |
def metadata_class(metadata_class): |
| 167 |
def decorator(func): |
| 168 |
_check_decorator_order(func, 'metadata_class') |
| 169 |
func.metadata_class = metadata_class |
| 170 |
return func |
| 171 |
return decorator |
| 172 |
|
| 173 |
|
| 174 |
def versioning_class(versioning_class): |
| 175 |
def decorator(func): |
| 176 |
_check_decorator_order(func, 'versioning_class') |
| 177 |
func.versioning_class = versioning_class |
| 178 |
return func |
| 179 |
return decorator |
| 180 |
|
| 181 |
|
| 182 |
def schema(view_inspector): |
| 183 |
def decorator(func): |
| 184 |
_check_decorator_order(func, 'schema') |
| 185 |
func.schema = view_inspector |
| 186 |
return func |
| 187 |
return decorator |
| 188 |
|
| 189 |
|
| 190 |
def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs): |
| 191 |
""" |
| 192 |
Mark a ViewSet method as a routable action. |
| 193 |
|
| 194 |
`@action`-decorated functions will be endowed with a `mapping` property, |
| 195 |
a `MethodMapper` that can be used to add additional method-based behaviors |
| 196 |
on the routed action. |
| 197 |
|
| 198 |
:param methods: A list of HTTP method names this action responds to. |
| 199 |
Defaults to GET only. |
| 200 |
:param detail: Required. Determines whether this action applies to |
| 201 |
instance/detail requests or collection/list requests. |
| 202 |
:param url_path: Define the URL segment for this action. Defaults to the |
| 203 |
name of the method decorated. |
| 204 |
:param url_name: Define the internal (`reverse`) URL name for this action. |
| 205 |
Defaults to the name of the method decorated with underscores |
| 206 |
replaced with dashes. |
| 207 |
:param kwargs: Additional properties to set on the view. This can be used |
| 208 |
to override viewset-level *_classes settings, equivalent to |
| 209 |
how the `@renderer_classes` etc. decorators work for function- |
| 210 |
based API views. |
| 211 |
""" |
| 212 |
methods = ['get'] if methods is None else methods |
| 213 |
methods = [method.lower() for method in methods] |
| 214 |
|
| 215 |
assert detail is not None, ( |
| 216 |
"@action() missing required argument: 'detail'" |
| 217 |
) |
| 218 |
|
| 219 |
# name and suffix are mutually exclusive |
| 220 |
if 'name' in kwargs and 'suffix' in kwargs: |
| 221 |
raise TypeError("`name` and `suffix` are mutually exclusive arguments.") |
| 222 |
|
| 223 |
def decorator(func): |
| 224 |
func.mapping = MethodMapper(func, methods) |
| 225 |
|
| 226 |
func.detail = detail |
| 227 |
func.url_path = url_path if url_path else func.__name__ |
| 228 |
func.url_name = url_name if url_name else func.__name__.replace('_', '-') |
| 229 |
|
| 230 |
# These kwargs will end up being passed to `ViewSet.as_view()` within |
| 231 |
# the router, which eventually delegates to Django's CBV `View`, |
| 232 |
# which assigns them as instance attributes for each request. |
| 233 |
func.kwargs = kwargs |
| 234 |
|
| 235 |
# Set descriptive arguments for viewsets |
| 236 |
if 'name' not in kwargs and 'suffix' not in kwargs: |
| 237 |
func.kwargs['name'] = pretty_name(func.__name__) |
| 238 |
func.kwargs['description'] = func.__doc__ or None |
| 239 |
|
| 240 |
return func |
| 241 |
return decorator |
| 242 |
|
| 243 |
|
| 244 |
class MethodMapper(dict): |
| 245 |
""" |
| 246 |
Enables mapping HTTP methods to different ViewSet methods for a single, |
| 247 |
logical action. |
| 248 |
|
| 249 |
Example usage: |
| 250 |
|
| 251 |
class MyViewSet(ViewSet): |
| 252 |
|
| 253 |
@action(detail=False) |
| 254 |
def example(self, request, **kwargs): |
| 255 |
... |
| 256 |
|
| 257 |
@example.mapping.post |
| 258 |
def create_example(self, request, **kwargs): |
| 259 |
... |
| 260 |
""" |
| 261 |
|
| 262 |
def __init__(self, action, methods): |
| 263 |
self.action = action |
| 264 |
for method in methods: |
| 265 |
self[method] = self.action.__name__ |
| 266 |
|
| 267 |
def _map(self, method, func): |
| 268 |
assert method not in self, ( |
| 269 |
"Method '%s' has already been mapped to '.%s'." % (method, self[method])) |
| 270 |
assert func.__name__ != self.action.__name__, ( |
| 271 |
"Method mapping does not behave like the property decorator. You " |
| 272 |
"cannot use the same method name for each mapping declaration.") |
| 273 |
|
| 274 |
self[method] = func.__name__ |
| 275 |
|
| 276 |
return func |
| 277 |
|
| 278 |
def get(self, func): |
| 279 |
return self._map('get', func) |
| 280 |
|
| 281 |
def post(self, func): |
| 282 |
return self._map('post', func) |
| 283 |
|
| 284 |
def put(self, func): |
| 285 |
return self._map('put', func) |
| 286 |
|
| 287 |
def patch(self, func): |
| 288 |
return self._map('patch', func) |
| 289 |
|
| 290 |
def delete(self, func): |
| 291 |
return self._map('delete', func) |
| 292 |
|
| 293 |
def head(self, func): |
| 294 |
return self._map('head', func) |
| 295 |
|
| 296 |
def options(self, func): |
| 297 |
return self._map('options', func) |
| 298 |
|
| 299 |
def trace(self, func): |
| 300 |
return self._map('trace', func) |