Debian Codegraph @

rest_framework/viewsets.py

raw
1 """
2 ViewSets are essentially just a type of class based view, that doesn't provide
3 any method handlers, such as `get()`, `post()`, etc... but instead has actions,
4 such as `list()`, `retrieve()`, `create()`, etc...
5
6 Actions are only bound to methods at the point of instantiating the views.
7
8 user_list = UserViewSet.as_view({'get': 'list'})
9 user_detail = UserViewSet.as_view({'get': 'retrieve'})
10
11 Typically, rather than instantiate views from viewsets directly, you'll
12 register the viewset with a router and let the URL conf be determined
13 automatically.
14
15 router = DefaultRouter()
16 router.register(r'users', UserViewSet, 'user')
17 urlpatterns = router.urls
18 """
19 from functools import update_wrapper
20 from inspect import getmembers
21
22 from django.urls import NoReverseMatch
23 from django.utils.decorators import classonlymethod
24 from django.views.decorators.csrf import csrf_exempt
25
26 from rest_framework import generics, mixins, views
27 from rest_framework.decorators import MethodMapper
28 from rest_framework.reverse import reverse
29
30
31 def _is_extra_action(attr):
32 return hasattr(attr, 'mapping') and isinstance(attr.mapping, MethodMapper)
33
34
35 def _check_attr_name(func, name):
36 assert func.__name__ == name, (
37 'Expected function (`{func.__name__}`) to match its attribute name '
38 '(`{name}`). If using a decorator, ensure the inner function is '
39 'decorated with `functools.wraps`, or that `{func.__name__}.__name__` '
40 'is otherwise set to `{name}`.').format(func=func, name=name)
41 return func
42
43
44 class ViewSetMixin:
45 """
46 This is the magic.
47
48 Overrides `.as_view()` so that it takes an `actions` keyword that performs
49 the binding of HTTP methods to actions on the Resource.
50
51 For example, to create a concrete view binding the 'GET' and 'POST' methods
52 to the 'list' and 'create' actions...
53
54 view = MyViewSet.as_view({'get': 'list', 'post': 'create'})
55 """
56
57 @classonlymethod
58 def as_view(cls, actions=None, **initkwargs):
59 """
60 Because of the way class based views create a closure around the
61 instantiated view, we need to totally reimplement `.as_view`,
62 and slightly modify the view function that is created and returned.
63 """
64 # The name and description initkwargs may be explicitly overridden for
65 # certain route configurations. eg, names of extra actions.
66 cls.name = None
67 cls.description = None
68
69 # The suffix initkwarg is reserved for displaying the viewset type.
70 # This initkwarg should have no effect if the name is provided.
71 # eg. 'List' or 'Instance'.
72 cls.suffix = None
73
74 # The detail initkwarg is reserved for introspecting the viewset type.
75 cls.detail = None
76
77 # Setting a basename allows a view to reverse its action urls. This
78 # value is provided by the router through the initkwargs.
79 cls.basename = None
80
81 # actions must not be empty
82 if not actions:
83 raise TypeError("The `actions` argument must be provided when "
84 "calling `.as_view()` on a ViewSet. For example "
85 "`.as_view({'get': 'list'})`")
86
87 # sanitize keyword arguments
88 for key in initkwargs:
89 if key in cls.http_method_names:
90 raise TypeError("You tried to pass in the %s method name as a "
91 "keyword argument to %s(). Don't do that."
92 % (key, cls.__name__))
93 if not hasattr(cls, key):
94 raise TypeError("%s() received an invalid keyword %r" % (
95 cls.__name__, key))
96
97 # name and suffix are mutually exclusive
98 if 'name' in initkwargs and 'suffix' in initkwargs:
99 raise TypeError("%s() received both `name` and `suffix`, which are "
100 "mutually exclusive arguments." % (cls.__name__))
101
102 def view(request, *args, **kwargs):
103 self = cls(**initkwargs)
104
105 if 'get' in actions and 'head' not in actions:
106 actions['head'] = actions['get']
107
108 # We also store the mapping of request methods to actions,
109 # so that we can later set the action attribute.
110 # eg. `self.action = 'list'` on an incoming GET request.
111 self.action_map = actions
112
113 # Bind methods to actions
114 # This is the bit that's different to a standard view
115 for method, action in actions.items():
116 handler = getattr(self, action)
117 setattr(self, method, handler)
118
119 self.request = request
120 self.args = args
121 self.kwargs = kwargs
122
123 # And continue as usual
124 return self.dispatch(request, *args, **kwargs)
125
126 # take name and docstring from class
127 update_wrapper(view, cls, updated=())
128
129 # and possible attributes set by decorators
130 # like csrf_exempt from dispatch
131 update_wrapper(view, cls.dispatch, assigned=())
132
133 # We need to set these on the view function, so that breadcrumb
134 # generation can pick out these bits of information from a
135 # resolved URL.
136 view.cls = cls
137 view.initkwargs = initkwargs
138 view.actions = actions
139
140 # Exempt from Django's LoginRequiredMiddleware. Users should set
141 # DEFAULT_PERMISSION_CLASSES to 'rest_framework.permissions.IsAuthenticated' instead
142 view.login_required = False
143
144 return csrf_exempt(view)
145
146 def initialize_request(self, request, *args, **kwargs):
147 """
148 Set the `.action` attribute on the view, depending on the request method.
149 """
150 request = super().initialize_request(request, *args, **kwargs)
151 method = request.method.lower()
152 if method == 'options':
153 # This is a special case as we always provide handling for the
154 # options method in the base `View` class.
155 # Unlike the other explicitly defined actions, 'metadata' is implicit.
156 self.action = 'metadata'
157 else:
158 self.action = self.action_map.get(method)
159 return request
160
161 def reverse_action(self, url_name, *args, **kwargs):
162 """
163 Reverse the action for the given `url_name`.
164 """
165 url_name = '%s-%s' % (self.basename, url_name)
166 namespace = None
167 if self.request and self.request.resolver_match:
168 namespace = self.request.resolver_match.namespace
169 if namespace:
170 url_name = namespace + ':' + url_name
171 kwargs.setdefault('request', self.request)
172
173 return reverse(url_name, *args, **kwargs)
174
175 @classmethod
176 def get_extra_actions(cls):
177 """
178 Get the methods that are marked as an extra ViewSet `@action`.
179 """
180 return [_check_attr_name(method, name)
181 for name, method
182 in getmembers(cls, _is_extra_action)]
183
184 def get_extra_action_url_map(self):
185 """
186 Build a map of {names: urls} for the extra actions.
187
188 This method will noop if `detail` was not provided as a view initkwarg.
189 """
190 action_urls = {}
191
192 # exit early if `detail` has not been provided
193 if self.detail is None:
194 return action_urls
195
196 # filter for the relevant extra actions
197 actions = [
198 action for action in self.get_extra_actions()
199 if action.detail == self.detail
200 ]
201
202 for action in actions:
203 try:
204 url_name = '%s-%s' % (self.basename, action.url_name)
205 namespace = self.request.resolver_match.namespace
206 if namespace:
207 url_name = '%s:%s' % (namespace, url_name)
208
209 url = reverse(url_name, self.args, self.kwargs, request=self.request)
210 view = self.__class__(**action.kwargs)
211 action_urls[view.get_view_name()] = url
212 except NoReverseMatch:
213 pass # URL requires additional arguments, ignore
214
215 return action_urls
216
217
218 class ViewSet(ViewSetMixin, views.APIView):
219 """
220 The base ViewSet class does not provide any actions by default.
221 """
222 pass
223
224
225 class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
226 """
227 The GenericViewSet class does not provide any actions by default,
228 but does include the base set of generic view behavior, such as
229 the `get_object` and `get_queryset` methods.
230 """
231 pass
232
233
234 class ReadOnlyModelViewSet(mixins.RetrieveModelMixin,
235 mixins.ListModelMixin,
236 GenericViewSet):
237 """
238 A viewset that provides default `list()` and `retrieve()` actions.
239 """
240 pass
241
242
243 class ModelViewSet(mixins.CreateModelMixin,
244 mixins.RetrieveModelMixin,
245 mixins.UpdateModelMixin,
246 mixins.DestroyModelMixin,
247 mixins.ListModelMixin,
248 GenericViewSet):
249 """
250 A viewset that provides default `create()`, `retrieve()`, `update()`,
251 `partial_update()`, `destroy()` and `list()` actions.
252 """
253 pass