Registering API in apps

前端 未结 4 1752
独厮守ぢ
独厮守ぢ 2021-02-04 10:46

With django-rest-framework I\'m using the DefaultRouter

I want to provide APIs to several apps, so my question is can I do this in a django manner and put m

4条回答
  •  無奈伤痛
    2021-02-04 11:07

    Both options are possible. You can either expose the router or the urls in each app, and merge those into your global urls. I usually prefer using urls (option 2) because it gives more flexibility in each app: you can define extra non-api URLs as needed.

    Option 1

    In your global urls.py:

    from app1.api.routers import router1
    from app2.api.routers import router2
    
    urlpatterns = patterns('',
        url(r'^snippets/', include('snippets.urls', namespace="snippets"))
        ...
        url(r'^app1/api/', include(router1.urls)),
        url(r'^app2/api/', include(router2.urls)),
    )
    

    You can as easily use the same endpoint for both routers (as long as you're careful not to use conflicting routes):

    urlpatterns = patterns('',
        url(r'^snippets/', include('snippets.urls', namespace="snippets"))
        ...
        url(r'^api/', include(router1.urls)),
        url(r'^api/', include(router2.urls)),
    )
    

    Option 2

    In appN/api/urls.py:

    router = DefaultRouter()
    router.register(r'users', views.UserViewSet)
    router.register(include('app1.apis')
    
    urlpatterns = patterns('',
        url(r'^', include(router.urls)),
        url(r'^misc/', some_other_view),
    )
    

    In your global urls.py:

    urlpatterns = patterns('',
        url(r'^snippets/', include('snippets.urls', namespace="snippets"))
        ...
        url(r'^api/', include('app1.api.urls')),
        url(r'^api/', include('app2.api.urls')),
    )
    

    Note that the urls modules do not need to be the same as the urls for standard views.

提交回复
热议问题