【问题标题】:How to add permissions in Django Rest Framework for specific requests如何在 Django Rest Framework 中为特定请求添加权限
【发布时间】:2013-06-16 13:31:48
【问题描述】:

我正在为文档应用程序创建一个基于类的 api,但我想在我的 APIView 中为帖子和补丁定义添加特定权限。例如,

class DocumentList(APIView):

    def get(self,request,format=None):
         ... blah

    def post(self,request,format=None):
        only allow administrators to create new documents 
        ... blah

【问题讨论】:

    标签: django permissions django-rest-framework


    【解决方案1】:

    这就是我所做的。参考来自documentation

    为项目创建权限类

    项目/permissions.py

    from rest_framework import permissions
    
    class IsAuthenticatedOrReadOnly(permissions.BasePermission):
    
        def has_object_permission(self, request, view, obj):
            # Read permission - always allow for GET request
            if request.method in permissions.SAFE_METHODS:
                return True
    
            # Write permissions - only if authenticated
            return request.user and request.user.is_authenticated()
    

    现在在视图中使用这个 PermissionClass

    @permission_classes((IsAuthenticatedOrReadOnly, ))
    class ShopViewSet(viewsets.ModelViewSet):
         queryset = Shop.objects.all()
         serializer_class = ShopSerializer
    

    【讨论】:

    • 我们也可以在 ShopViewSet 中设置 permission_classes 属性
    【解决方案2】:

    By default permissions are unrestricted。在您的settings.py 中,您可以指定一组不同的默认值,以使用户必须经过身份验证并拥有正确的 Django 模型权限。您需要在视图类中指定model 属性,DjangoModelPermissions 才能生效。

    # settings.py
    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
            'rest_framework.permissions.DjangoModelPermissions'
        )
    }
    
    # views.py
    class DocumentList(APIView):
        model = Document
        ...
    

    DjangoModelPermissions 权限映射can be found in the source

    • GET、OPTIONS 和 HEAD 不需要权限,但由于我们指定了 IsAuthenticated,我们仍然需要该权限
    • POST 地图添加
    • 要更改的 PUT 和 PATCH 映射
    • DELETE 要删除的地图

    【讨论】:

      猜你喜欢
      • 2018-03-01
      • 1970-01-01
      • 2021-06-19
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 2015-01-11
      相关资源
      最近更新 更多