【问题标题】:Django REST Framework - How to quickly checks user permissions?Django REST Framework - 如何快速检查用户权限?
【发布时间】:2018-03-22 23:05:02
【问题描述】:

我通常使用 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,这很好,但由于它根据定义的视图的查询集工作,有时我需要检查不是为视图的查询集定义的权限。

有没有办法仅通过提供 perms 的字符串列表来快速检查权限?

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      您可以通过使用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 只能由经过身份验证的用户访问。

      【讨论】:

      • 您的解决方案完全等同于定义字段permission_classes = [IsAuthenticated],有没有办法在不创建新权限类的情况下定义允许的模型权限列表(例如'my_app.view_mymodel')?跨度>
      • @wencakisa 我可以在@permission_classes 中授予多个权限吗?他们会遵循andor 规则吗?
      • @harman786 当然,您可以在@permission_classes 中传递一个集合,它们将遵循and 规则。例如:@permission_classes((IsAuthenticated, IsPerson)) -> 这将只允许在您自己的权限中属于“人”的经过身份验证的用户访问视图。
      • @wencakisa:刚刚发现 DRF 文档中提到的这个包,似乎是合法的 and/orgithub.com/caxap/rest_condition
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 2018-05-20
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      相关资源
      最近更新 更多