我正在尝试在视图集的 ListModelMixin 上设置特定的身份验证和权限类。我尝试了以下方法,但它不起作用:
def list(self, request):
self.authentication_classes = (apiauth.SessionAuthentication, )
self.permission_classes = (permissions.IsAuthenticated, )
return super(TestViewSet, self).list(request)
我做错了什么吗?
@henriquesalvaro的答案对我不起作用。
出于某种原因,action
在get_authenticators(self)
中不是自我的一部分,所以if self.action == 'list'
对我不起作用。
我必须编写以下代码才能获得操作。
def get_authenticators(self):
authentication_classes = [TokenAuthentication]
action_map = {key.lower(): value for key,
value in self.action_map.items()}
action_name = action_map.get(self.request.method.lower())
if action_name =="list":
return [YourPermission]
return authentication_classes
当您的请求到达list
函数时,这意味着它已经通过了身份验证和权限阶段。
如果对ViewSet
上的所有操作使用相同的类进行权限和身份验证,则应在类声明中定义它们:
class MyViewSet(viewsets.ViewSet):
authentication_classes = (apiauth.SessionAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
如果尝试对list
操作使用不同的身份验证/权限类,则可以覆盖get_authenticators
和get_permissions
方法:
class MyViewSet(viewsets.ViewSet):
...
def get_authenticators(self):
if self.action == 'list':
# Set up here
return YourAuthenticators
return super().get_authenticators()
def get_permissions(self):
if self.action == 'list':
# Set up here
return YourPermissions
return super().get_permissions()