【问题标题】:How to set a method in Django rest framework's ViewSet to not require authentication如何在 Django 休息框架 ViewSet 中设置方法不需要身份验证
【发布时间】:2018-04-17 18:16:50
【问题描述】:

我有viewset,如下所示:

from rest_framework import viewsets
from paas.serializers import UserSerializer
import logging


logger=  logging.getLogger(__name__)

class UserViewSet(viewsets.ViewSet):
    def list(self,request):
        pass

    def create(self,request):
        logger.info(request.data)
        current_user = UserSerializer.create()

另外,我在我的代码中使用基于 DRF 令牌的身份验证。我怎么能简单地说这个create 方法不需要身份验证? 如您所知,在使用令牌实现身份验证后,所有请求的标头中都应包含Token,任何没有的请求都会出现 403 错误。

【问题讨论】:

    标签: django django-rest-framework django-rest-viewsets


    【解决方案1】:

    根据 DRF 问题跟踪器上的 this issue,最好的方法似乎是创建自定义权限类。视图对象有一个action 属性,可用于改变您为响应视图集的每个子操作而执行的操作。

    class IsCreationOrIsAuthenticated(permissions.BasePermission):
    
        def has_permission(self, request, view):
            if not request.user.is_authenticated():
                if view.action == 'create':
                    return True
                else:
                    return False
            else:
                return True
    

    或更详细的来自AssembledAdam

    (此处复制的代码符合 SO 政策,不只是链接出去,以防链接被破坏或更改。)

    class AnonCreateAndUpdateOwnerOnly(permissions.BasePermission):
        """
        Custom permission:
            - allow anonymous POST
            - allow authenticated GET and PUT on *own* record
            - allow all actions for staff
        """
    
        def has_permission(self, request, view):
            return view.action == 'create' or request.user and request.user.is_authenticated
    
        def has_object_permission(self, request, view, obj):
            return view.action in ['retrieve', 'update', 'partial_update'] and obj.id == request.user.id or request.user.is_staff
    
    class ListAdminOnly(permissions.BasePermission):
        """
        Custom permission to only allow access to lists for admins
        """
    
        def has_permission(self, request, view):
            return view.action != 'list' or request.user and request.user.is_staff
    

    【讨论】:

      猜你喜欢
      • 2017-01-06
      • 1970-01-01
      • 2021-06-07
      • 2013-06-29
      • 2017-09-26
      • 2017-11-02
      • 1970-01-01
      • 2021-11-30
      • 2022-10-16
      相关资源
      最近更新 更多