Python rest_framework.routers 模块,DefaultRouter() 实例源码

我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用rest_framework.routers.DefaultRouter()

项目:django-rest-witchcraft    作者:shosca    | 项目源码 | 文件源码
def get_lookup_regex(self, viewset, lookup_prefix=''):
        """
        Given a viewset, return the portion of the url regex that is used to match against a single instance.

        Can be overwritten by providing a `lookup_url_regex` on the viewset.
        """

        lookup_url_regex = getattr(viewset, 'lookup_url_regex', None)
        if lookup_url_regex:
            return lookup_url_regex

        model = getattr(viewset, 'get_model', lambda: None)()
        if model:
            info = model_info(model)
            base_regex = '(?P<{lookup_prefix}{lookup_url_kwarg}>{lookup_value})'

            regexes = []
            for key, _ in info.primary_keys.items():
                regexes.append(
                    base_regex.format(lookup_prefix=lookup_prefix, lookup_url_kwarg=key, lookup_value='[^/.]+')
                )

            return '/'.join(regexes)

        return super(DefaultRouter, self).get_lookup_regex(viewset, lookup_prefix)
项目:apimas    作者:grnet    | 项目源码 | 文件源码
def construct_endpoint(self, instance, spec, loc, context):
        """
        Constructor of '.endpoint' predicate.

        It gets the generated views and it maps them with urlpatterns which
        will later be used from django.
        """
        parent_name = context.get('parent_name')
        collections = self.get_structural_elements(instance)
        if not collections:
            raise utils.DRFAdapterException(
                '.endpoint without any collection found.', loc=loc)
        router = routers.DefaultRouter()
        for collection in collections:
            collection_spec = instance.get(collection)
            view = collection_spec.get(self.ADAPTER_CONF)
            basename = parent_name + '_' + collection
            router.register(collection, view, base_name=basename)
        self.urls[parent_name] = url(
            r'^' + parent_name + '/', include(router.urls))
项目:Code_python    作者:RoJoHub    | 项目源码 | 文件源码
def registerApi():
    router = routers.DefaultRouter()
    router.register(r'users', UserViewSet)
    return router
项目:Code_python    作者:RoJoHub    | 项目源码 | 文件源码
def registerApi():
    router = routers.DefaultRouter()
    router.register(r'users', UserViewSet)
    # router.register(r'Others', TestSet1)
    return router
项目:Code_python    作者:RoJoHub    | 项目源码 | 文件源码
def registerApi():
    router = routers.DefaultRouter()
    router.register(r'users', UserViewSet)
    # router.register(r'Others', TestSet1)
    return router
项目:django-oscar-bluelight    作者:thelabnyc    | 项目源码 | 文件源码
def get_urls(self):
        base_urls = super().get_urls()

        router = routers.DefaultRouter()
        router.register(r'offergroups', OfferGroupViewSet, base_name='api-offergroup')

        custom_urls = [
            # API
            url(r'^api/', include(router.urls)),

            # Benefits
            url(r'^benefits/$', self.benefit_list_view.as_view(), name='benefit-list'),
            url(r'^benefits/new/$', self.benefit_create_view.as_view(), name='benefit-create'),
            url(r'^benefits/(?P<pk>[0-9]+)/$', self.benefit_update_view.as_view(), name='benefit-update'),
            url(r'^benefits/(?P<pk>[0-9]+)/delete/$', self.benefit_delete_view.as_view(), name='benefit-delete'),

            # Conditions
            url(r'^conditions/$', self.condition_list_view.as_view(), name='condition-list'),
            url(r'^conditions/new/$', self.condition_create_view.as_view(), name='condition-create'),
            url(r'^conditions/new-compound/$', self.compound_condition_create_view.as_view(), name='condition-create-compound'),
            url(r'^conditions/(?P<pk>[0-9]+)/$', self.condition_update_view.as_view(), name='condition-update'),
            url(r'^conditions/(?P<pk>[0-9]+)/delete/$', self.condition_delete_view.as_view(), name='condition-delete'),

            # Offer Groups
            url(r'^offer_group/$', self.offergroup_list_view.as_view(), name='offergroup-list'),
            url(r'^offer_group/new/$', self.offergroup_create_view.as_view(), name='offergroup-create'),
            url(r'^offer_group/(?P<pk>[0-9]+)/$', self.offergroup_update_view.as_view(), name='offergroup-update'),
            url(r'^offer_group/(?P<pk>[0-9]+)/delete/$', self.offergroup_delete_view.as_view(), name='offergroup-delete'),
        ]
        return base_urls + self.post_process_urls(custom_urls)
项目:pathways-backend    作者:pg-irc    | 项目源码 | 文件源码
def build_urls_from_view_sets():
    router = routers.DefaultRouter()
    router.register(r'^questions', viewsets.QuestionViewSet)
    router.register(r'^questions/(?P<question_id>[0-9]+)/choices', viewsets.ChoiceViewSet, 'choice')
    return router.urls
项目:pathways-backend    作者:pg-irc    | 项目源码 | 文件源码
def build_router():
    router = routers.DefaultRouter()
    router.register(r'organizations', OrganizationViewSet, base_name='organization')
    router.register(r'organizations/(?P<organization_id>[0-9a-zA-Z_]+)/locations', LocationViewSetUnderOrganizations, base_name='organization-location')
    router.register(r'locations', LocationViewSet, base_name='location')
    router.register(r'search', SearchViewSet, base_name='search')
    return router
项目:django-chemtrails    作者:inonit    | 项目源码 | 文件源码
def get_urls(self):

        router = routers.DefaultRouter()
        router.register(r'access-rules', AccessRuleViewSet)
        router.register(r'meta-graph', MetaGraphView, base_name='metagraph')

        info = self.model._meta.app_label, self.model._meta.model_name
        urlpatterns = [
            url(r'^neo4j/nodelist/$', self.get_nodelist_api_view, name='%s_%s_nodelist' % info),  # Deprecated
            url(r'^neo4j/', include(router.urls))
        ] + super(AccessRuleAdmin, self).get_urls()
        return urlpatterns
项目:py2swagger    作者:Arello-Mobile    | 项目源码 | 文件源码
def test_format_api_patterns_url_import_with_routers(self):

        class MockApiViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            model = User
            queryset = User.objects.all()

        class AnotherMockApiViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            model = User
            queryset = User.objects.all()

        router = DefaultRouter()
        router.register(r'other_views', MockApiViewSet, base_name='test_base_name')
        router.register(r'more_views', AnotherMockApiViewSet, base_name='test_base_name')

        urls_app = patterns('', url(r'^', include(router.urls)))
        urls = patterns(
            '',
            url(r'api/', include(urls_app)),
            url(r'test/', include(urls_app))
        )
        apis = self.urlparser.get_apis(urls)

        self.assertEqual(
            4, sum(api['path'].find('api') != -1 for api in apis))
        self.assertEqual(
            4, sum(api['path'].find('test') != -1 for api in apis))
项目:py2swagger    作者:Arello-Mobile    | 项目源码 | 文件源码
def test_exclude_router_api_root(self):
        class MyViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            queryset = User.objects.all()
            model = User

        router = DefaultRouter()
        router.register('test', MyViewSet, base_name='test_base_name')

        urls_created = len(router.urls)

        apis = self.urlparser.get_apis(router.urls)

        self.assertEqual(4, urls_created - len(apis))
项目:django-rest-framework-mongoengine-example    作者:BurkovBA    | 项目源码 | 文件源码
def get_api_root_view(self):
        # callgraph:
        # HybridRouter.get_urls
        # DefaultRouter.get_urls
        # HybridRouter.get_api_root_view

        # Copy the following block from Default Router
        api_root_dict = {}
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        # In addition to that:
        api_view_urls = self._api_view_urls

        class APIRoot(views.APIView):
            _ignore_model_permissions = True

            def get(self, request, *args, **kwargs):
                ret = OrderedDict()
                namespace = request.resolver_match.namespace
                for key, url_name in api_root_dict.items():
                    if namespace:
                        url_name = namespace + ':' + url_name
                    try:
                        ret[key] = reverse(
                            url_name,
                            args=args,
                            kwargs=kwargs,
                            request=request,
                            format=kwargs.get('format', None)
                        )
                    except NoReverseMatch:
                        # Don't bail out if eg. no list routes exist, only detail routes.
                        continue

                # In addition to what had been added, now add the APIView urls
                for api_view_key in api_view_urls.keys():
                    # originally was: reverse(api_view_urls[api_view_key].name, request=request, format=format)
                    namespace = request.resolver_match.namespace
                    if namespace:
                        url_name = namespace + ":" + api_view_key
                    try:
                        ret[api_view_key] = reverse(
                            url_name,
                            args=args,
                            kwargs=kwargs,
                            request=request,
                            format=kwargs.get('format', None)
                        )
                    except NoReverseMatch:
                        continue

                return response.Response(ret)

        return APIRoot.as_view()