Skip to content

Instantly share code, notes, and snippets.

@scottx611x
Created March 2, 2017 20:51
Show Gist options
  • Save scottx611x/6278cd8d49068685dbfb5bcf32cd95f7 to your computer and use it in GitHub Desktop.
Save scottx611x/6278cd8d49068685dbfb5bcf32cd95f7 to your computer and use it in GitHub Desktop.
Django Rest Framework Router combiner
from rest_framework.routers import DefaultRouter
class RouterCombiner(DefaultRouter):
"""
Extends `DefaultRouter` class to add a method for extending url routes
from another router.
Allows for app-specific url definitions to stay inside their own apps.
"""
def extend(self, router):
"""
Extend the routes with url routes of the passed in router.
router: DRF Router instance containing route definitions.
"""
self.urls.extend(router.urls)
self.registry.extend(router.registry)
"""
Ex:
If app_a and app_b have their own DefaultRouters defined,
one can consolidate their url & registry information like so:
"""
from app_a import DefaultRouter as router_a
from app_b import DefaultRouter as router_b
router_combiner = RouterCombiner()
router_combiner.extend(router_a)
router_combiner.extend(router_b)
urlpatterns += patterns(
'', url(r"^api/", include(router_combiner.urls))
)
"""
This way url definitions can reside individual Django apps and be
acted upon in one main urls.py file
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment