Django REST框架 - 如何快速检查用户权限?

时间:2018-03-22 23:05:02

标签: django django-rest-framework django-permissions

我通常使用permission_required装饰器来快速拒绝用户访问视图。

from django.contrib.auth.decorators import permission_required

@permission_required('my_app.view_mymodel',login_url='/sign_in/')
def my_view(request):
    ...

现在,我正在使用DRF,而我正试图找到一种检查用户权限的正确方法。现在,我使用DjangoModelPermissions这很好,但由于它根据定义的视图的查询集工作,有时我需要检查不是为视图定义的权限&# 39; s queryset。

有没有办法快速检查权限只需提供一个权限列表'字符串?

注意:我知道我可以扩展BasePermission并定义我自己的逻辑,但会产生很多类。

2 个答案:

答案 0 :(得分:1)

像这样对我有用:

在您的意见范围内:

from rest_framework.decorators import api_view
from .permissions import permission_required

@api_view(['GET'])
@permission_required('permission')
def do_something(request):
    pass

在权限内:

from rest_framework.permissions import BasePermission
from rest_framework.decorators import permission_classes

def permission_required(perm):
    def has_permission(self, request, view):
        return request.user.has_perm(perm)
    Can = type(
        'WrappedAPIView',
        (BasePermission,),
        {'message': 'You can not do ' + perm,
        'has_permission': has_permission}
    )
    def decorator(func):
        func.permission_classes = [Can]
        return func
    return decorator

答案 1 :(得分:0)

您可以使用DRF's decorators@api_view@permission_classes)来实现这一目标:

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

@api_view(['GET'])
# At first, you should define your view as an API view
# by using the @api_view decorator

@permission_classes((IsAuthenticated, ))
# With the @permission_classes decorator you can provide a tuple
# with the desired permissions for this view

def example_view(request, format=None):
    content = {
        'status': 'request was permitted'
    }
    return Response(content)

现在只有经过身份验证的用户才能访问您的example_view