Exclude URLs from Django REST Swagger

后端 未结 6 2143
再見小時候
再見小時候 2020-12-31 05:27

I have a few URLs that I want to exclude from my REST API documentation. I\'m using Django REST Swagger and the only documentation I can find (https://github.com/marcgibbons

6条回答
  •  佛祖请我去吃肉
    2020-12-31 06:05

    A more flexible solution would be:

    from django.contrib import admin
    from django.urls import include, path
    from rest_framework_swagger.views import get_swagger_view
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('users/', include('user.urls', namespace="user")),
        path('locations/', include('location.urls')),
        path('departments/', include('department.urls', namespace="department")),
        path('my_secret_api/', include('secret.urls', namespace="secret_api")),
    ]
    
    to_exclude = ['secret_api',] # some more namespaces here
    swagger_urls = [item for item in urlpatterns if hasattr(item,"namespace") and item.namespace not in to_exclude]
    schema_view = get_swagger_view(title='Highky', patterns=swagger_urls)
    urlpatterns += [
            path('api/docs/', schema_view),
    ]
    

    urlpatterns will have all five paths, but swagger_urls will have four paths excluding secret_api.

    All of your URLs and includes will continue to work as they were, except we are now passing our modified urlpatterns that we want to show in the Swagger docs. The checks will also cover the include where you don't specify a namespace (like in our case, where the namespace is not defined in the location).

提交回复
热议问题