是否有任何使用Django Rest Framework路由APIViews
(即不 ViewSets
)的常见模式?
例如,如果我有一个带有可选参数的API视图:
class ReportView(APIView):
def get(self, request, report_name=None):
# … stuff …
return Response(report)
是否有任何标准模式 - 除了写出标准的Django URL路由器 - 用于路由该视图?
答案 0 :(得分:10)
能够添加简单的API视图对于在root-api
视图中显示网址非常有用。
以下是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视图和其他框架ViewSets:
router = DefaultRouterWithSimpleViews()
router.register(r'users', UserViewSet, 'users') # <- Viewset!
router.register(r'reset-pwd', ResetPasswordView, 'reset_pwd') # <- Simple view!
urlpatterns = router.urls
更新:添加了对格式后缀的支持(感谢alexander-klimenko)
答案 1 :(得分:8)
是否有任何标准模式 - 除了写出标准的Django URL路由器 - 用于路由该视图?
ViewSets&amp;如果您想要标准化路由,路由器 模式。
如果你正在使用视图,那么只需使用常规的Django URLconf。