Last active
October 25, 2023 22:08
-
-
Save dmwyatt/93f36c7efa9f9d7685cd to your computer and use it in GitHub Desktop.
[auto drf url registration] Using Django Rest Framework's DefaultRouter to build an API Root for urls.py files located in individual apps. #django #drf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# urls.py | |
def register_routes(router, apps): | |
""" | |
Register DRF router routes from urls.py in the provided apps. | |
>>> router = routers.DefaultRouter() | |
>>> register_routes(router, ['app1', 'app2', 'app3]) | |
""" | |
for app in apps: | |
urls = importlib.import_module(app+".urls") | |
try: | |
routes = urls.routes | |
except AttributeError: | |
continue | |
for route in routes: | |
router.register(*route) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment