django-rules
django-rules copied to clipboard
added two DRF generic views to the check in get_permission_object()
This is a small patch to make rules a bit more compatible with DRF. See also https://github.com/highpost/rules_test
Hmm... it looks like the build is broken because I'm using DRF 3.10 which no longer supports Python 2.7.
This looks good, I guess, but it can’t really be importing “rest_framework” like that as it’ll break things for everyone else that only needs to use rules with Django. What’s potentially better is having a new class put into the “rest_framework” module that extends this one. Even then though, I’m not sure importing DRF without having it in requirements.txt makes sense, and I’m not really inclined to add it as a dependency. So all in all, it feels to me this can’t be added to rules, but could easily be in an external package.
On the other hand, we don’t declare a dependency on Django as well, so the second option might not be too much of a stretch to include.
How about something more direct?
from pkgutil import iter_modules
if "rest_framework" in (name for loader, name, ispkg in iter_modules()):
has_drf = True
from rest_framework.generics import CreateAPIView, ListAPIView
else:
has_drf = False
...
if has_drf:
class_list = (BaseCreateView, CreateAPIView, ListAPIView)
else:
class_list = (BaseCreateView,)
if not isinstance(self, class_list):
I've run into a problem with getting DRF working with Rules. I have a test project in https://github.com/highpost/rules_test with a bunch of tests that I use to help make sure that I'm doing equivalent things in Django views and DRF views. Reading through it I saw that my tests for object permissions had a bug.
I was testing the scenario where an author has both explicitly granted permission as well as implied permission from the is_book_author predicate. Since the test user had explicit permission the test would always pass. And when I changed the test data so that the test user only has the implied permission, the test passed for the Django view but not for the DRF view.
I'll spend some time over the weekend or next week trying to figure this out.
This is more complex than I thought. I believe that get_permission_object() is failing because it uses WSGIRequest and DRF requires rest_framework.request.Request. See the following:
https://stackoverflow.com/a/51747714/1953757 https://github.com/encode/django-rest-framework/issues/918
Getting this straightened out is beyond me. Without a solution to this problem and something like the patch proposed above I don't think we can say that Rules works with DRF. And the section https://github.com/dfunckt/django-rules#permissions-in-django-rest-framework is ultimately misleading.