2013-04-25 01:40:24 +04:00
|
|
|
"""
|
|
|
|
Routers provide a convenient and consistent way of automatically
|
|
|
|
determining the URL conf for your API.
|
|
|
|
|
|
|
|
They are used by simply instantiating a Router class, and then registering
|
|
|
|
all the required ViewSets with that router.
|
|
|
|
|
|
|
|
For example, you might have a `urls.py` that looks something like this:
|
|
|
|
|
|
|
|
router = routers.DefaultRouter()
|
|
|
|
router.register('users', UserViewSet, 'user')
|
|
|
|
router.register('accounts', AccountViewSet, 'account')
|
|
|
|
|
|
|
|
urlpatterns = router.urls
|
|
|
|
"""
|
2013-04-29 15:45:00 +04:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2013-04-26 17:59:21 +04:00
|
|
|
from collections import namedtuple
|
2013-04-04 23:00:44 +04:00
|
|
|
from django.conf.urls import url, patterns
|
2013-04-25 01:40:24 +04:00
|
|
|
from rest_framework.decorators import api_view
|
|
|
|
from rest_framework.response import Response
|
|
|
|
from rest_framework.reverse import reverse
|
|
|
|
from rest_framework.urlpatterns import format_suffix_patterns
|
2013-04-04 23:00:44 +04:00
|
|
|
|
|
|
|
|
2013-04-26 17:59:21 +04:00
|
|
|
Route = namedtuple('Route', ['url', 'mapping', 'name', 'initkwargs'])
|
|
|
|
|
|
|
|
|
2013-04-25 20:41:47 +04:00
|
|
|
def replace_methodname(format_string, methodname):
|
|
|
|
"""
|
|
|
|
Partially format a format_string, swapping out any
|
2013-04-26 18:09:55 +04:00
|
|
|
'{methodname}' or '{methodnamehyphen}' components.
|
2013-04-25 20:41:47 +04:00
|
|
|
"""
|
|
|
|
methodnamehyphen = methodname.replace('_', '-')
|
|
|
|
ret = format_string
|
|
|
|
ret = ret.replace('{methodname}', methodname)
|
|
|
|
ret = ret.replace('{methodnamehyphen}', methodnamehyphen)
|
|
|
|
return ret
|
|
|
|
|
|
|
|
|
2013-04-04 23:00:44 +04:00
|
|
|
class BaseRouter(object):
|
|
|
|
def __init__(self):
|
|
|
|
self.registry = []
|
|
|
|
|
2013-04-26 17:59:21 +04:00
|
|
|
def register(self, prefix, viewset, name):
|
|
|
|
self.registry.append((prefix, viewset, name))
|
2013-04-04 23:00:44 +04:00
|
|
|
|
2013-04-25 01:40:24 +04:00
|
|
|
def get_urls(self):
|
|
|
|
raise NotImplemented('get_urls must be overridden')
|
2013-04-04 23:00:44 +04:00
|
|
|
|
|
|
|
@property
|
2013-04-25 01:40:24 +04:00
|
|
|
def urls(self):
|
|
|
|
if not hasattr(self, '_urls'):
|
|
|
|
self._urls = patterns('', *self.get_urls())
|
|
|
|
return self._urls
|
|
|
|
|
|
|
|
|
|
|
|
class SimpleRouter(BaseRouter):
|
|
|
|
routes = [
|
|
|
|
# List route.
|
2013-04-26 17:59:21 +04:00
|
|
|
Route(
|
|
|
|
url=r'^{prefix}/$',
|
|
|
|
mapping={
|
2013-04-25 01:40:24 +04:00
|
|
|
'get': 'list',
|
|
|
|
'post': 'create'
|
|
|
|
},
|
2013-04-26 17:59:21 +04:00
|
|
|
name='{basename}-list',
|
|
|
|
initkwargs={'suffix': 'List'}
|
2013-04-25 01:40:24 +04:00
|
|
|
),
|
|
|
|
# Detail route.
|
2013-04-26 17:59:21 +04:00
|
|
|
Route(
|
|
|
|
url=r'^{prefix}/{lookup}/$',
|
|
|
|
mapping={
|
2013-04-25 01:40:24 +04:00
|
|
|
'get': 'retrieve',
|
|
|
|
'put': 'update',
|
|
|
|
'patch': 'partial_update',
|
|
|
|
'delete': 'destroy'
|
|
|
|
},
|
2013-04-26 17:59:21 +04:00
|
|
|
name='{basename}-detail',
|
|
|
|
initkwargs={'suffix': 'Instance'}
|
2013-04-25 01:40:24 +04:00
|
|
|
),
|
|
|
|
# Dynamically generated routes.
|
|
|
|
# Generated using @action or @link decorators on methods of the viewset.
|
2013-04-26 17:59:21 +04:00
|
|
|
Route(
|
|
|
|
url=r'^{prefix}/{lookup}/{methodname}/$',
|
|
|
|
mapping={
|
2013-04-25 01:40:24 +04:00
|
|
|
'{httpmethod}': '{methodname}',
|
|
|
|
},
|
2013-04-26 17:59:21 +04:00
|
|
|
name='{basename}-{methodnamehyphen}',
|
|
|
|
initkwargs={}
|
2013-04-25 01:40:24 +04:00
|
|
|
),
|
2013-04-04 23:00:44 +04:00
|
|
|
]
|
|
|
|
|
2013-04-25 01:40:24 +04:00
|
|
|
def get_routes(self, viewset):
|
|
|
|
"""
|
|
|
|
Augment `self.routes` with any dynamically generated routes.
|
|
|
|
|
2013-04-26 17:59:21 +04:00
|
|
|
Returns a list of the Route namedtuple.
|
2013-04-25 01:40:24 +04:00
|
|
|
"""
|
|
|
|
|
|
|
|
# Determine any `@action` or `@link` decorated methods on the viewset
|
|
|
|
dynamic_routes = {}
|
|
|
|
for methodname in dir(viewset):
|
|
|
|
attr = getattr(viewset, methodname)
|
|
|
|
httpmethod = getattr(attr, 'bind_to_method', None)
|
|
|
|
if httpmethod:
|
|
|
|
dynamic_routes[httpmethod] = methodname
|
|
|
|
|
2013-04-04 23:00:44 +04:00
|
|
|
ret = []
|
2013-04-26 17:59:21 +04:00
|
|
|
for route in self.routes:
|
|
|
|
if route.mapping == {'{httpmethod}': '{methodname}'}:
|
2013-04-25 20:41:47 +04:00
|
|
|
# Dynamic routes (@link or @action decorator)
|
2013-04-25 01:40:24 +04:00
|
|
|
for httpmethod, methodname in dynamic_routes.items():
|
2013-04-26 17:59:21 +04:00
|
|
|
initkwargs = route.initkwargs.copy()
|
|
|
|
initkwargs.update(getattr(viewset, methodname).kwargs)
|
|
|
|
ret.append(Route(
|
|
|
|
url=replace_methodname(route.url, methodname),
|
|
|
|
mapping={httpmethod: methodname},
|
|
|
|
name=replace_methodname(route.name, methodname),
|
|
|
|
initkwargs=initkwargs,
|
2013-04-25 01:40:24 +04:00
|
|
|
))
|
|
|
|
else:
|
|
|
|
# Standard route
|
2013-04-26 17:59:21 +04:00
|
|
|
ret.append(route)
|
2013-04-05 00:42:26 +04:00
|
|
|
|
2013-04-25 01:40:24 +04:00
|
|
|
return ret
|
2013-04-04 23:00:44 +04:00
|
|
|
|
2013-04-25 01:40:24 +04:00
|
|
|
def get_method_map(self, viewset, method_map):
|
|
|
|
"""
|
|
|
|
Given a viewset, and a mapping of http methods to actions,
|
|
|
|
return a new mapping which only includes any mappings that
|
|
|
|
are actually implemented by the viewset.
|
|
|
|
"""
|
|
|
|
bound_methods = {}
|
|
|
|
for method, action in method_map.items():
|
|
|
|
if hasattr(viewset, action):
|
|
|
|
bound_methods[method] = action
|
|
|
|
return bound_methods
|
|
|
|
|
|
|
|
def get_lookup_regex(self, viewset):
|
|
|
|
"""
|
|
|
|
Given a viewset, return the portion of URL regex that is used
|
|
|
|
to match against a single instance.
|
|
|
|
"""
|
|
|
|
base_regex = '(?P<{lookup_field}>[^/]+)'
|
|
|
|
lookup_field = getattr(viewset, 'lookup_field', 'pk')
|
|
|
|
return base_regex.format(lookup_field=lookup_field)
|
|
|
|
|
|
|
|
def get_urls(self):
|
|
|
|
"""
|
|
|
|
Use the registered viewsets to generate a list of URL patterns.
|
|
|
|
"""
|
|
|
|
ret = []
|
2013-04-04 23:00:44 +04:00
|
|
|
|
2013-04-25 01:40:24 +04:00
|
|
|
for prefix, viewset, basename in self.registry:
|
|
|
|
lookup = self.get_lookup_regex(viewset)
|
|
|
|
routes = self.get_routes(viewset)
|
2013-04-04 23:35:40 +04:00
|
|
|
|
2013-04-26 17:59:21 +04:00
|
|
|
for route in routes:
|
2013-04-04 23:38:42 +04:00
|
|
|
|
2013-04-25 01:40:24 +04:00
|
|
|
# Only actions which actually exist on the viewset will be bound
|
2013-04-26 17:59:21 +04:00
|
|
|
mapping = self.get_method_map(viewset, route.mapping)
|
|
|
|
if not mapping:
|
2013-04-04 23:35:40 +04:00
|
|
|
continue
|
|
|
|
|
|
|
|
# Build the url pattern
|
2013-04-26 17:59:21 +04:00
|
|
|
regex = route.url.format(prefix=prefix, lookup=lookup)
|
|
|
|
view = viewset.as_view(mapping, **route.initkwargs)
|
|
|
|
name = route.name.format(basename=basename)
|
2013-04-04 23:35:40 +04:00
|
|
|
ret.append(url(regex, view, name=name))
|
|
|
|
|
2013-04-04 23:00:44 +04:00
|
|
|
return ret
|
2013-04-25 01:40:24 +04:00
|
|
|
|
|
|
|
|
|
|
|
class DefaultRouter(SimpleRouter):
|
|
|
|
"""
|
|
|
|
The default router extends the SimpleRouter, but also adds in a default
|
|
|
|
API root view, and adds format suffix patterns to the URLs.
|
|
|
|
"""
|
|
|
|
include_root_view = True
|
|
|
|
include_format_suffixes = True
|
|
|
|
|
|
|
|
def get_api_root_view(self):
|
|
|
|
"""
|
|
|
|
Return a view to use as the API root.
|
|
|
|
"""
|
|
|
|
api_root_dict = {}
|
2013-04-26 17:59:21 +04:00
|
|
|
list_name = self.routes[0].name
|
2013-04-25 01:40:24 +04:00
|
|
|
for prefix, viewset, basename in self.registry:
|
|
|
|
api_root_dict[prefix] = list_name.format(basename=basename)
|
|
|
|
|
|
|
|
@api_view(('GET',))
|
|
|
|
def api_root(request, format=None):
|
|
|
|
ret = {}
|
|
|
|
for key, url_name in api_root_dict.items():
|
|
|
|
ret[key] = reverse(url_name, request=request, format=format)
|
|
|
|
return Response(ret)
|
|
|
|
|
|
|
|
return api_root
|
|
|
|
|
|
|
|
def get_urls(self):
|
|
|
|
"""
|
|
|
|
Generate the list of URL patterns, including a default root view
|
|
|
|
for the API, and appending `.json` style format suffixes.
|
|
|
|
"""
|
|
|
|
urls = []
|
|
|
|
|
|
|
|
if self.include_root_view:
|
|
|
|
root_url = url(r'^$', self.get_api_root_view(), name='api-root')
|
|
|
|
urls.append(root_url)
|
|
|
|
|
|
|
|
default_urls = super(DefaultRouter, self).get_urls()
|
|
|
|
urls.extend(default_urls)
|
|
|
|
|
|
|
|
if self.include_format_suffixes:
|
|
|
|
urls = format_suffix_patterns(urls)
|
|
|
|
|
|
|
|
return urls
|