Is it possible to add a prefix
or url_prefix
argument to SimpleRouter or BaseRouter like Flask Blueprint's url_prefix
argument
#9575
-
For example, I create a user app and define user's url.py like this: from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
urlpatterns = router.urls now I want add version info to url path, I need add version info to every register function, like this: from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'v1/users', UserViewSet)
router.register(r'v1/accounts', AccountViewSet)
urlpatterns = router.urls I don't find a simple way to do it, I remembered that Flask can do this by define Blueprint's from rest_framework import routers
router = routers.SimpleRouter(prefix="v1")
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
urlpatterns = router.urls I tried to update class SimpleRouter(BaseRouter):
def __init__(self, prefix="", trailing_slash=True, use_regex_path=True):
self.prefix = prefix
...
def get_urls(self):
...
for prefix, viewset, basename in self.registry:
prefix = f"{self.prefix}/{prefix}" if self.prefix else prefix
... it works, but maybe no strong enough. Is that a good suggestion? If so I'd like to continue to refine it. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I would receommend putting the v1 and v2 routers each in their own folder with a # apps/api/v1/urls.py
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r"users", UserViewSetV1)
urlpatterns = router.urls # apps/api/v2/urls.py
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r"users", UserViewSetV2)
urlpatterns = router.urls Then you can have a # apps/api/urls.py
from django.urls import include, path
from rest_framework.authtoken import views
urlpatterns = [
path("v1/", include("apps.api.v1.urls")),
path("v2/", include("apps.api.v2.urls")),
] Hope that helps |
Beta Was this translation helpful? Give feedback.
To answer your question:
I think the answer will be no. I'm not a maintainer, but DRF is unlikely to accept this kind of requests, as there is a good way of handling this case:
https://www.django-rest-framework.org/community/contributing/