Wednesday, January 31, 2018

Extending custom router to default router across apps in Django Rest Framework

Leave a Comment

I have come across a problem regarding having the API apps seperate, while still being able to use the browsable API for navigation.

I have previously used a seperate routers.py file in my main application containing the following extension of the DefaultRouter.

class DefaultRouter(routers.DefaultRouter):     def extend(self, router):         self.registry.extend(router.registry) 

Followed by adding the other application routers like this:

from . routers import DefaultRouter from app1.urls import router as app1_router  # Default Router mainAppRouter = DefaultRouter() mainAppRouter.extend(app1_router) 

where the app1_router is a new SimpleRouter object.

Now the problem occurs when I want to modify the SimpleRouter and create my own App1Router, such as this

class App1Router(SimpleRouter):      routes = [         Route(             url = r'^{prefix}{trailing_slash}$',             mapping = {                 'get': 'retrieve',                 'post': 'create',                 'patch': 'partial_update',             },             name = '{basename}-user',             initkwargs = {}         ),     ] 

This will not handle my extension correctly. As an example, GET and PATCH are not recognized as allowed methods whenever I extend the router, but when I dont extend, but only use the custom router, everything works fine.

My question is therefor, how can I handle extending custom routers across seperate applications, but still maintain a good browsable API?

0 Answers

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment