Debian Codegraph @

rest_framework/routers.py

raw
1 """
2 Routers provide a convenient and consistent way of automatically
3 determining the URL conf for your API.
4
5 They are used by simply instantiating a Router class, and then registering
6 all the required ViewSets with that router.
7
8 For example, you might have a `urls.py` that looks something like this:
9
10 router = routers.DefaultRouter()
11 router.register('users', UserViewSet, 'user')
12 router.register('accounts', AccountViewSet, 'account')
13
14 urlpatterns = router.urls
15 """
16 import itertools
17 from collections import namedtuple
18
19 from django.core.exceptions import ImproperlyConfigured
20 from django.urls import NoReverseMatch, path, re_path
21
22 from rest_framework import views
23 from rest_framework.response import Response
24 from rest_framework.reverse import reverse
25 from rest_framework.schemas import SchemaGenerator
26 from rest_framework.schemas.views import SchemaView
27 from rest_framework.settings import api_settings
28 from rest_framework.urlpatterns import format_suffix_patterns
29
30 Route = namedtuple('Route', ['url', 'mapping', 'name', 'detail', 'initkwargs'])
31 DynamicRoute = namedtuple('DynamicRoute', ['url', 'name', 'detail', 'initkwargs'])
32
33
34 def escape_curly_brackets(url_path):
35 """
36 Double brackets in regex of url_path for escape string formatting
37 """
38 return url_path.replace('{', '{{').replace('}', '}}')
39
40
41 def flatten(list_of_lists):
42 """
43 Takes an iterable of iterables, returns a single iterable containing all items
44 """
45 return itertools.chain(*list_of_lists)
46
47
48 class BaseRouter:
49 def __init__(self):
50 self.registry = []
51
52 def register(self, prefix, viewset, basename=None):
53 if basename is None:
54 basename = self.get_default_basename(viewset)
55
56 if self.is_already_registered(basename):
57 msg = (f'Router with basename "{basename}" is already registered. '
58 f'Please provide a unique basename for viewset "{viewset}"')
59 raise ImproperlyConfigured(msg)
60
61 self.registry.append((prefix, viewset, basename))
62
63 # invalidate the urls cache
64 if hasattr(self, '_urls'):
65 del self._urls
66
67 def is_already_registered(self, new_basename):
68 """
69 Check if `basename` is already registered
70 """
71 return any(basename == new_basename for _prefix, _viewset, basename in self.registry)
72
73 def get_default_basename(self, viewset):
74 """
75 If `basename` is not specified, attempt to automatically determine
76 it from the viewset.
77 """
78 raise NotImplementedError('get_default_basename must be overridden')
79
80 def get_urls(self):
81 """
82 Return a list of URL patterns, given the registered viewsets.
83 """
84 raise NotImplementedError('get_urls must be overridden')
85
86 @property
87 def urls(self):
88 if not hasattr(self, '_urls'):
89 self._urls = self.get_urls()
90 return self._urls
91
92
93 class SimpleRouter(BaseRouter):
94
95 routes = [
96 # List route.
97 Route(
98 url=r'^{prefix}{trailing_slash}$',
99 mapping={
100 'get': 'list',
101 'post': 'create'
102 },
103 name='{basename}-list',
104 detail=False,
105 initkwargs={'suffix': 'List'}
106 ),
107 # Dynamically generated list routes. Generated using
108 # @action(detail=False) decorator on methods of the viewset.
109 DynamicRoute(
110 url=r'^{prefix}/{url_path}{trailing_slash}$',
111 name='{basename}-{url_name}',
112 detail=False,
113 initkwargs={}
114 ),
115 # Detail route.
116 Route(
117 url=r'^{prefix}/{lookup}{trailing_slash}$',
118 mapping={
119 'get': 'retrieve',
120 'put': 'update',
121 'patch': 'partial_update',
122 'delete': 'destroy'
123 },
124 name='{basename}-detail',
125 detail=True,
126 initkwargs={'suffix': 'Instance'}
127 ),
128 # Dynamically generated detail routes. Generated using
129 # @action(detail=True) decorator on methods of the viewset.
130 DynamicRoute(
131 url=r'^{prefix}/{lookup}/{url_path}{trailing_slash}$',
132 name='{basename}-{url_name}',
133 detail=True,
134 initkwargs={}
135 ),
136 ]
137
138 def __init__(self, trailing_slash=True, use_regex_path=True):
139 self.trailing_slash = '/' if trailing_slash else ''
140 self._use_regex = use_regex_path
141 if use_regex_path:
142 self._base_pattern = '(?P<{lookup_prefix}{lookup_url_kwarg}>{lookup_value})'
143 self._default_value_pattern = '[^/.]+'
144 self._url_conf = re_path
145 else:
146 self._base_pattern = '<{lookup_value}:{lookup_prefix}{lookup_url_kwarg}>'
147 self._default_value_pattern = 'str'
148 self._url_conf = path
149 # remove regex characters from routes
150 _routes = []
151 for route in self.routes:
152 url_param = route.url
153 if url_param[0] == '^':
154 url_param = url_param[1:]
155 if url_param[-1] == '$':
156 url_param = url_param[:-1]
157
158 _routes.append(route._replace(url=url_param))
159 self.routes = _routes
160
161 super().__init__()
162
163 def get_default_basename(self, viewset):
164 """
165 If `basename` is not specified, attempt to automatically determine
166 it from the viewset.
167 """
168 queryset = getattr(viewset, 'queryset', None)
169
170 assert queryset is not None, '`basename` argument not specified, and could ' \
171 'not automatically determine the name from the viewset, as ' \
172 'it does not have a `.queryset` attribute.'
173
174 return queryset.model._meta.object_name.lower()
175
176 def get_routes(self, viewset):
177 """
178 Augment `self.routes` with any dynamically generated routes.
179
180 Returns a list of the Route namedtuple.
181 """
182 # converting to list as iterables are good for one pass, known host needs to be checked again and again for
183 # different functions.
184 known_actions = list(flatten([route.mapping.values() for route in self.routes if isinstance(route, Route)]))
185 extra_actions = viewset.get_extra_actions()
186
187 # checking action names against the known actions list
188 not_allowed = [
189 action.__name__ for action in extra_actions
190 if action.__name__ in known_actions
191 ]
192 if not_allowed:
193 msg = ('Cannot use the @action decorator on the following '
194 'methods, as they are existing routes: %s')
195 raise ImproperlyConfigured(msg % ', '.join(not_allowed))
196
197 # partition detail and list actions
198 detail_actions = [action for action in extra_actions if action.detail]
199 list_actions = [action for action in extra_actions if not action.detail]
200
201 routes = []
202 for route in self.routes:
203 if isinstance(route, DynamicRoute) and route.detail:
204 routes += [self._get_dynamic_route(route, action) for action in detail_actions]
205 elif isinstance(route, DynamicRoute) and not route.detail:
206 routes += [self._get_dynamic_route(route, action) for action in list_actions]
207 else:
208 routes.append(route)
209
210 return routes
211
212 def _get_dynamic_route(self, route, action):
213 initkwargs = route.initkwargs.copy()
214 initkwargs.update(action.kwargs)
215
216 url_path = escape_curly_brackets(action.url_path)
217
218 return Route(
219 url=route.url.replace('{url_path}', url_path),
220 mapping=action.mapping,
221 name=route.name.replace('{url_name}', action.url_name),
222 detail=route.detail,
223 initkwargs=initkwargs,
224 )
225
226 def get_method_map(self, viewset, method_map):
227 """
228 Given a viewset, and a mapping of http methods to actions,
229 return a new mapping which only includes any mappings that
230 are actually implemented by the viewset.
231 """
232 bound_methods = {}
233 for method, action in method_map.items():
234 if hasattr(viewset, action):
235 bound_methods[method] = action
236 return bound_methods
237
238 def get_lookup_regex(self, viewset, lookup_prefix=''):
239 """
240 Given a viewset, return the portion of URL regex that is used
241 to match against a single instance.
242
243 Note that lookup_prefix is not used directly inside REST rest_framework
244 itself, but is required in order to nicely support nested router
245 implementations, such as drf-nested-routers.
246
247 https://github.com/alanjds/drf-nested-routers
248 """
249 # Use `pk` as default field, unset set. Default regex should not
250 # consume `.json` style suffixes and should break at '/' boundaries.
251 lookup_field = getattr(viewset, 'lookup_field', 'pk')
252 lookup_url_kwarg = getattr(viewset, 'lookup_url_kwarg', None) or lookup_field
253 lookup_value = None
254 if not self._use_regex:
255 # try to get a more appropriate attribute when not using regex
256 lookup_value = getattr(viewset, 'lookup_value_converter', None)
257 if lookup_value is None:
258 # fallback to legacy
259 lookup_value = getattr(viewset, 'lookup_value_regex', self._default_value_pattern)
260 return self._base_pattern.format(
261 lookup_prefix=lookup_prefix,
262 lookup_url_kwarg=lookup_url_kwarg,
263 lookup_value=lookup_value
264 )
265
266 def get_urls(self):
267 """
268 Use the registered viewsets to generate a list of URL patterns.
269 """
270 ret = []
271
272 for prefix, viewset, basename in self.registry:
273 lookup = self.get_lookup_regex(viewset)
274 routes = self.get_routes(viewset)
275
276 for route in routes:
277
278 # Only actions which actually exist on the viewset will be bound
279 mapping = self.get_method_map(viewset, route.mapping)
280 if not mapping:
281 continue
282
283 # Build the url pattern
284 regex = route.url.format(
285 prefix=prefix,
286 lookup=lookup,
287 trailing_slash=self.trailing_slash
288 )
289
290 # If there is no prefix, the first part of the url is probably
291 # controlled by project's urls.py and the router is in an app,
292 # so a slash in the beginning will (A) cause Django to give
293 # warnings and (B) generate URLS that will require using '//'.
294 if not prefix:
295 if self._url_conf is path:
296 if regex[0] == '/':
297 regex = regex[1:]
298 elif regex[:2] == '^/':
299 regex = '^' + regex[2:]
300
301 initkwargs = route.initkwargs.copy()
302 initkwargs.update({
303 'basename': basename,
304 'detail': route.detail,
305 })
306
307 view = viewset.as_view(mapping, **initkwargs)
308 name = route.name.format(basename=basename)
309 ret.append(self._url_conf(regex, view, name=name))
310
311 return ret
312
313
314 class APIRootView(views.APIView):
315 """
316 The default basic root view for DefaultRouter
317 """
318 _ignore_model_permissions = True
319 schema = None # exclude from schema
320 api_root_dict = None
321
322 def get(self, request, *args, **kwargs):
323 # Return a plain {"name": "hyperlink"} response.
324 ret = {}
325 namespace = request.resolver_match.namespace
326 for key, url_name in self.api_root_dict.items():
327 if namespace:
328 url_name = namespace + ':' + url_name
329 try:
330 ret[key] = reverse(
331 url_name,
332 args=args,
333 kwargs=kwargs,
334 request=request,
335 format=kwargs.get('format')
336 )
337 except NoReverseMatch:
338 # Don't bail out if eg. no list routes exist, only detail routes.
339 continue
340
341 return Response(ret)
342
343
344 class DefaultRouter(SimpleRouter):
345 """
346 The default router extends the SimpleRouter, but also adds in a default
347 API root view, and adds format suffix patterns to the URLs.
348 """
349 include_root_view = True
350 include_format_suffixes = True
351 root_view_name = 'api-root'
352 default_schema_renderers = None
353 APIRootView = APIRootView
354 APISchemaView = SchemaView
355 SchemaGenerator = SchemaGenerator
356
357 def __init__(self, *args, **kwargs):
358 if 'root_renderers' in kwargs:
359 self.root_renderers = kwargs.pop('root_renderers')
360 else:
361 self.root_renderers = list(api_settings.DEFAULT_RENDERER_CLASSES)
362 super().__init__(*args, **kwargs)
363
364 def get_api_root_view(self, api_urls=None):
365 """
366 Return a basic root view.
367 """
368 api_root_dict = {}
369 list_name = self.routes[0].name
370 for prefix, viewset, basename in self.registry:
371 api_root_dict[prefix] = list_name.format(basename=basename)
372
373 return self.APIRootView.as_view(api_root_dict=api_root_dict)
374
375 def get_urls(self):
376 """
377 Generate the list of URL patterns, including a default root view
378 for the API, and appending `.json` style format suffixes.
379 """
380 urls = super().get_urls()
381
382 if self.include_root_view:
383 view = self.get_api_root_view(api_urls=urls)
384 root_url = path('', view, name=self.root_view_name)
385 urls.append(root_url)
386
387 if self.include_format_suffixes:
388 urls = format_suffix_patterns(urls)
389
390 return urls