l0b0
l0b0

Reputation: 58858

How to get all Django REST Framework permission classes?

After starting a Django shell using ./manage.py shell I can't see any of the custom permission subclasses in the application:

In [1]: from rest_framework.permissions import BasePermission                                                                                                                                  
In [2]: BasePermission.__subclasses__()                                                                                                                                                        
Out[2]: 
[rest_framework.permissions.AllowAny,
 rest_framework.permissions.IsAuthenticated,
 rest_framework.permissions.IsAdminUser,
 rest_framework.permissions.IsAuthenticatedOrReadOnly,
 rest_framework.permissions.DjangoModelPermissions]

How can I get all the permission classes, including the custom ones?

I'm writing a custom management command to list all existing permissions and how they are used, so I need some way to load my entire application rather than importing each file separately.

Upvotes: 0

Views: 507

Answers (1)

A. J. Parr
A. J. Parr

Reputation: 8026

I think this is happening because you haven't imported those subclasses, so the python interpreter is not aware of there being any custom subclasses of BasePermission.

I initially tested this myself using the python manage.py shell_plus command from the django-extensions package, which imports all your models when it starts the shell. Then when I ran BasePermission.__subclasses__() it listed all my custom permissions.

Then I tried python manage.py shell, ran the same code, and the result was the same as yours.

So if you have all your permissions in a single file, or a file pattern such as <app_folder>/permissions.py, you should import all those permissions files (to the effect of from app_folder.permissions import *) and then try BasePermission.__subclasses__().

Upvotes: 1

Related Questions