2016-12-12 62 views
0

我明白,我们可以建立认证类基于类viewsets这样的:动态地改变身份验证类Django的REST框架

class ExampleViewSet(ModelViewSet): 
    authentication_classes = (SessionAuthentication, BasicAuthentication) 

然而,有没有办法来动态改变基于请求认证类方法?我想在我的ExampleViewSet重写此功能:

def get_authenticators(self): # Found in 
    if self.request.method == "POST": 
     authentication_classes.append(authentication.MyCustomAuthentication) 
    return authentication_classes 

然而,Django的休息没有request对象设置在这一点上:

'ExampleViewSet' object has no attribute 'request' 

注:不是真正的变量名 - 只是举例的目的。

回答

0

您可以使用detail_route装饰从rest_framework像这样来的请求, detail_route可以用来定义职位以及获得,期权或因此删除选项 ,更新的代码应该是这样的:

from rest_framework.decorators import detail_route 

class ExampleViewSet(ModelViewSet): 
    authentication_classes = (SessionAuthentication, BasicAuthentication) 

    @detail_route(methods=['post','get']) 
    def get_authenticators(self, request, **kwargs): # Found in 
     if request.method == "POST": 
      authentication_classes.append(authentication.MyCustomAuthentication) 
     return authentication_classes 

对于进一步阅读,Read from here.

+0

这不起作用,但给出了一种新的错误类型。 – lbrindze

+0

@lbrindze那是什么错误? –

+0

使用django 1.11与python3它说get_authentictors期待2个参数,但只收到一个(这是有道理的,因为这个重写指定自我和请求作为位置参数)。 我认为我的用例https://stackoverflow.com/questions/19773869/django-rest-framework-separate-permissions-per-methods似乎让我想要什么。 – lbrindze

0

基于以前的答案,它适用于Django的1.10

@detail_route(methods=['post', 'get']) 
def get_authenticators(self): 
    if self.request.method == "GET": 
     self.authentication_classes = [CustomAuthenticationClass] 
    return [auth() for auth in self.authentication_classes]