1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| class SimpleRouter(BaseRouter): routes = [ Route( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'list', 'post': 'create' }, name='{basename}-list', detail=False, initkwargs={'suffix': 'List'} ),
def __init__(self, trailing_slash=True): self.trailing_slash = '/' if trailing_slash else '' super().__init__()
def get_default_basename(self, viewset): """ If `basename` is not specified, attempt to automatically determine it from the viewset. """ queryset = getattr(viewset, 'queryset', None)
assert queryset is not None, '`basename` argument not specified, and could ' \ 'not automatically determine the name from the viewset, as ' \ 'it does not have a `.queryset` attribute.'
return queryset.model._meta.object_name.lower()
def get_routes(self, viewset): known_actions = list(flatten([route.mapping.values() for route in self.routes if isinstance(route, Route)])) extra_actions = viewset.get_extra_actions()
not_allowed = [ action.__name__ for action in extra_actions if action.__name__ in known_actions ] if not_allowed: msg = ('Cannot use the @action decorator on the following ' 'methods, as they are existing routes: %s') raise ImproperlyConfigured(msg % ', '.join(not_allowed))
detail_actions = [action for action in extra_actions if action.detail] list_actions = [action for action in extra_actions if not action.detail]
routes = [] for route in self.routes: if isinstance(route, DynamicRoute) and route.detail: routes += [self._get_dynamic_route(route, action) for action in detail_actions] elif isinstance(route, DynamicRoute) and not route.detail: routes += [self._get_dynamic_route(route, action) for action in list_actions] else: routes.append(route)
return routes
def get_urls(self): """ Use the registered viewsets to generate a list of URL patterns. """ ret = [] for prefix, viewset, basename in self.registry: lookup = self.get_lookup_regex(viewset) routes = self.get_routes(viewset) for route in routes:
mapping = self.get_method_map(viewset, route.mapping) if not mapping: continue
regex = route.url.format( prefix=prefix, lookup=lookup, trailing_slash=self.trailing_slash )
if not prefix and regex[:2] == '^/': regex = '^' + regex[2:]
initkwargs = route.initkwargs.copy() initkwargs.update({ 'basename': basename, 'detail': route.detail, })
view = viewset.as_view(mapping, **initkwargs) name = route.name.format(basename=basename) ret.append(url(regex, view, name=name))
return ret
|