How to override get_swagger_view to enable django-rest-swagger to display all endpoints?
Asked Answered
V

1

8

By default django-rest-swagger displays my views which do not require authentication(JWT Auth in this case). I tried to override the default get_swagger_view shortcut by adding IsAuthenticated in the permission classes to include the views which require authentication also. But as soon as I visit the rendered docs this time, I get No operations defined in spec!

How do I display both the views which do and do not require authentication.

Viceroy answered 22/8, 2018 at 17:48 Comment(0)
T
0

You can use patch from unittest module to solve the problem.

During schema generation, the request object is being checked for each view based on the list of permissions. We declare them in permission_classes attribute and they typically have has_permission method which is being called during generation. And if it raises some(exceptions.APIException, Http404, PermissionDenied) exceptions, generator skips that view.

If you want to patch the method of IsAuthenticated class you can do it this way:

from unittest.mock import patch

from rest_framework_swagger.views import get_swagger_view

def patch_the_method(func):
    def inner(*args, **kwargs):
        with patch('rest_framework.permissions.IsAuthenticated.has_permission', return_value=True):
            response = func(*args, **kwargs)
        return response
    return inner

schema_view = patch_the_method(get_swagger_view(title='Some API'))

Note that this won't include views with other permissions into the schema. To avoid patching all permissions classes you can patch a method from SchemaGenerator class called has_view_permissions.

Here is how:

...
with patch('rest_framework.schemas.SchemaGenerator.has_view_permissions', return_value=True):
...
Toitoiboid answered 19/12, 2019 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.