我有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错误。
答案 0 :(得分:2)
DRF问题跟踪器上的每this issue,最好的方法似乎是创建自定义权限类。视图对象具有action
属性,可用于改变您为响应ViewSet的每个子操作而执行的操作。
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
中更详细的内容
(此处复制的代码符合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