Django REST Framework combining routers from different apps

前端 未结 6 1868
面向向阳花
面向向阳花 2020-12-12 14:33

I have a project that spans multiple apps:

./project/app1
./project/app2
./project/...

Each app has a router for Django REST Framework to i

6条回答
  •  孤街浪徒
    2020-12-12 14:52

    Another solution is to use SimpleRouter to define routers for individual apps. Then, use a customized DefaultRouter to include app specific routes. This way all of the app specific url definitions will stay in the corresponding app.

    Lets say you have two apps named "app1" and "app2" each of these apps have a directory named "api" and in this directory there is a file named "urls" that contain all your route definitions.

    ├── project/ │ ├── api_urls.py │ ├── app1 │ │ ├── api │ │ │ ├── urls.py │ ├── app2 │ │ ├── api │ │ │ ├── urls.py │ ├── patches │ │ ├── routers.py

    use patches/router.py to define a class named DefaultRouter that inherits from rest_framework.routers.DefaultRouter.

    from rest_framework import routers
    
    class DefaultRouter(routers.DefaultRouter):
        """
        Extends `DefaultRouter` class to add a method for extending url routes from another router.
        """
        def extend(self, router):
            """
            Extend the routes with url routes of the passed in router.
    
            Args:
                 router: SimpleRouter instance containing route definitions.
            """
            self.registry.extend(router.registry)
    

    Fill your api urls with route definitions like

    """
    URL definitions for the api.
    """
    from patches import routers
    
    from app1.api.urls import router as app1_router
    from app2.api.urls import router as app2_router
    
    router = routers.DefaultRouter()
    router.extend(app1_router)
    router.extend(app2_router)
    

提交回复
热议问题