Python rest_framework.routers.DefaultRouter() Examples

The following are 8 code examples of rest_framework.routers.DefaultRouter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.routers , or try the search function .
Example #1
Source File: api.py    From DCRM with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_router():
    router = routers.DefaultRouter()
    router.register(r'contenttypes', ContentTypeViewSet, 'contenttype')
    router.register(r'groups', GroupViewSet, 'group')
    router.register(r'users', UserViewSet, 'user')
    router.register(r'permissions', PermissionViewSet, 'permission')
    router.register(r'releases', ReleaseViewSet, 'release')
    router.register(r'sections', SectionViewSet, 'section')
    router.register(r'packages', PackageViewSet, 'package')
    router.register(r'versions', VersionViewSet, 'version')
    router.register(r'builds', BuildViewSet, 'build')
    router.register(r'device_types', DeviceTypeViewSet, 'device_type')
    router.register(r'os_versions', OSVersionViewSet, 'os_version')
    router.register(r'settings', SettingViewSet, 'setting')
    router.register(r'galleries', GalleryViewSet, 'gallery')
    router.register(r'photos', PhotoViewSet, 'photo')
    router.register(r'comments', CommentViewSet, 'comment')
    router.register(r'sites', SiteViewSet, 'site')
    return router 
Example #2
Source File: admin.py    From django-restful-admin with MIT License 6 votes vote down vote up
def get_urls(self):
        router = DefaultRouter()
        view_sets = []
        for model, view_set in self._registry.items():
            if view_set.queryset is None:
                view_set.queryset = model.objects.all()
            if view_set.serializer_class is None:
                serializer_class = type("%sModelSerializer" % model.__name__, (ModelSerializer,), {
                    "Meta": type("Meta", (object,), {
                        "model": model,
                        "fields": "__all__"
                    }),
                })
                view_set.serializer_class = serializer_class

            view_sets.append(view_set)
            router.register(self.get_model_url(model), view_set, self.get_model_basename(model))

        return router.urls + self._url_patterns 
Example #3
Source File: test_urlparser.py    From py2swagger with MIT License 5 votes vote down vote up
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)) 
Example #4
Source File: test_urlparser.py    From py2swagger with MIT License 5 votes vote down vote up
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)) 
Example #5
Source File: test_viewsets.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.router = DefaultRouter()
        self.router.register(r'locations', LocationViewSet)
        self.view = LocationViewSet.as_view({'get': 'list'}) 
Example #6
Source File: test_viewsets.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.router = DefaultRouter()
        self.router.register(r'rasters', RasterViewSet)
        self.view = RasterViewSet.as_view({'get': 'list'}) 
Example #7
Source File: api_views.py    From chicago-justice with GNU General Public License v3.0 5 votes vote down vote up
def router_urls():
    router = routers.DefaultRouter(trailing_slash=False)
    router.register(r'articles', ArticleViewSet)
    router.register(r'categories', CategoryViewSet)
    router.register(r'trained-codings', TrainedCodingViewSet)

    return router.urls 
Example #8
Source File: router.py    From openag-device-software with GNU General Public License v3.0 4 votes vote down vote up
def get_api_root_view(self, api_urls: List[str] = None) -> Dict:
        """Gets api root view."""
        self.logger.debug("Getting api root view")
        api_root_dict: Dict = OrderedDict()
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        class APIRootView(views.APIView):
            """ The default basic root view for DefaultRouter """

            _ignore_model_permissions = True
            schema = None  # exclude from schema
            api_root_dict: Dict = {}

            def get(self, request: Request, *args: Any, **kwargs: Any) -> Response:
                # Return a plain {"name": "hyperlink"} response.
                response: Dict = OrderedDict()
                namespace = request.resolver_match.namespace
                for key, url_name in self.api_root_dict.items():
                    if namespace:
                        url_name = namespace + ":" + url_name
                    try:
                        response[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

                # Add APIView endpoints
                endpoints = ["recipe/stop", "recipe/{uuid}/start/"]
                base = response["state"].split("api", 1)[0] + "api/"
                for endpoint in endpoints:
                    response[endpoint] = base + endpoint

                return Response(response, 200)

        return APIRootView.as_view(api_root_dict=api_root_dict)