24

Django Rest Framework是否有任何通用的路由模式APIViews(即不是)? ViewSets

例如,如果我有一个带有可选参数的 API 视图:

class ReportView(APIView):
    def get(self, request, report_name=None):
         # … stuff …
         return Response(report)

是否有任何标准模式——除了写出标准的 Django URL 路由器——来路由该视图?

4

2 回答 2

15

能够添加简单的 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

于 2015-11-28T12:00:13.263 回答
9

是否有任何标准模式——除了写出标准的 Django URL 路由器——来路由该视图?

如果你想要标准化的路由,ViewSets & Routers就是模式。

如果您使用视图,那么只需使用常规的 Django URLconf。

于 2013-09-16T08:41:51.083 回答