Django REST Framework combining routers from different apps

前端 未结 6 1861
面向向阳花
面向向阳花 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 15:01

    This gets all the ViewSet routes listed on the base API URL.

    It defines the routes as a list in the respective included app.urls so they can be registered elsewhere.

    After including them in the base urls.py, the nested list of lists is built and looped through to register all routes at the same level in the API

    # foo.urls
    routeList = (
        (r'foos', FooViewSet),
    )
    
    # barBaz.urls
    routeList = (
        (r'bars', BarViewSet),
        (r'bazs', BazViewSet),
    )
    
    # urls
    from rest_framework import routers
    from foo import urls as fooUrls
    from barBaz import urls as barBazUrls
    
    routeLists = [
        fooUrls.routeList,
        barBazUrls.routeList,
    ]
    
    router = routers.DefaultRouter()
    for routeList in routeLists:
        for route in routeList:
            router.register(route[0], route[1])
    

    Results:

    {
        "foo": "http://localhost:8000/foos/",
        "bar": "http://localhost:8000/bars/",
        "baz": "http://localhost:8000/bazs/",
    }
    

    This also has less repetition in each file, and arguably makes it easier to read.

    Also, it remains completely decoupled.

    If the included app is used elsewhere, the same method can be used internally to register it's own routes without being included anywhere.

    Just drop the outside loop

    routeList = (
        (r'bars', BarViewSet),
        (r'bazs', BazViewSet),
    )
    
    router = routers.DefaultRouter()
    for route in routeList:
        router.register(route[0], route[1])
    

提交回复
热议问题