在 Django REST 框架中,默认权限 类 如何与 per-view(set) 结合使用?

In the Django REST framework, how are the default permission classes combined with per-view(set) ones?

我正在阅读 http://www.django-rest-framework.org/api-guide/permissions/ and trying to relate it to the OAuth2 toolkit documentation, http://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html。后者有一个示例,其中在 settings.py 中指定

REST_FRAMEWORK = {
    # ...

    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

此外,IsAuthenticated也被指定添加到ModelViewSetpermission_classes列表中:

class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    queryset = User.objects.all()
    serializer_class = UserSerializer

我是否从这个例子中正确地推断出 DEFAULT_PERMISSION_CLASSES 没有被添加/添加到 ModelViewSet 的权限 类,而是被它替换了?

In the Django REST framework, how are the default permission classes combined with per-view(set) ones?

它们没有合并。

... the DEFAULT_PERMISSION_CLASSES are not prepended / postpended to a ModelViewSet's permission classes, but are instead replaced by it?

正确。

Do I infer correctly from this example that the DEFAULT_PERMISSION_CLASSES are not prepended / postpended to a ModelViewSet's permission classes, but are instead replaced by it?

DEFAULT_PERMISSION_CLASSES 用于 views/viewsets,其中 permission_classes 未定义。在定义它们的情况下,将使用它们,而不是默认值。

像这样在您的自定义权限中添加代码class

class ObjectWritePermission(BasePermission):
    # you will see this function in IsAuthenticated Permission class
    def has_permission(self, request, view):
        return bool(request.user and request.user.is_authenticated)

    def has_object_permission(self, request, view, obj):
        return obj.user == request.user

如果您确实想扩展默认权限,这似乎可行。

免责声明:我是通过查看 DRF 的代码找到它的,但不确定它是否已记录在案。

from rest_framework.settings import api_settings

class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [*api_settings.DEFAULT_PERMISSION_CLASSES, TokenHasReadWriteScope]