能够添加简单的 API 视图对于在root-api
视图中显示 url 非常有用。
这是最简单的扩展,DefaultRouter
不仅可以注册视图集,还可以注册简单的 API 视图:
from django.conf.urls import url
from rest_framework import routers, viewsets
from rest_framework.urlpatterns import format_suffix_patterns
class DefaultRouterWithSimpleViews(routers.DefaultRouter):
"""
Extends functionality of DefaultRouter adding possibility
to register simple API views, not just Viewsets.
"""
def get_routes(self, viewset):
"""
Checks if the viewset is an instance of ViewSet,
otherwise assumes it's a simple view and does not run
original `get_routes` code.
"""
if issubclass(viewset, viewsets.ViewSetMixin):
return super(DefaultRouterWithSimpleViews, self).get_routes(viewset)
return []
def get_urls(self):
"""
Append non-viewset views to the urls
generated by the original `get_urls` method.
"""
# URLs for simple views
ret = []
for prefix, viewset, basename in self.registry:
# Skip viewsets
if issubclass(viewset, viewsets.ViewSetMixin):
continue
# URL regex
regex = '{prefix}{trailing_slash}$'.format(
prefix=prefix,
trailing_slash=self.trailing_slash
)
# The view name has to have suffix "-list" due to specifics
# of the DefaultRouter implementation.
ret.append(url(
regex, viewset.as_view(),
name='{0}-list'.format(basename)
))
# Format suffixes
ret = format_suffix_patterns(ret, allowed=['json', 'html'])
# Prepend URLs for viewsets and return
return super(DefaultRouterWithSimpleViews, self).get_urls() + ret
现在您可以将简单的 Django 视图与其余框架 ViewSet 一起使用:
router = DefaultRouterWithSimpleViews()
router.register(r'users', UserViewSet, 'users') # <- Viewset!
router.register(r'reset-pwd', ResetPasswordView, 'reset_pwd') # <- Simple view!
urlpatterns = router.urls
更新:增加了对格式后缀的支持(感谢alexander-klimenko)