2016-10-19 26 views
1

我已经将头脑放在了这个位置,差不多3-4天了。如何从Django rest框架的自定义身份验证类中返回自定义响应对象

让我来解释一下情况。我有一个DRF(Django REST框架)基于类的视图与自定义认证类。据我所知,您可以重写DRF的BaseAuthentication类的authenticate方法来实现您的自定义身份验证,而只有在身份验证失败的情况下才能提出DRF提供的预定义的例外。

我的问题是,我试图找到一种方法来返回自定义响应即;将验证码HTML直接从认证类发送到前端,以便在我的视图中实现与认证无关的代码。

为了更好地理解我的情况,我在下面提供了一个伪代码。

class ExampleView(APIView): 
    authentication_classes = (ExampleCustomAuth,) 

    def get(self, request): 
     pass 

这是视图,这部分是绝对好的。

class ExampleCustomAuth(BaseAuthentication): 

    def authenticate(self, request): 
     req = request 
     request = req._request 
     { 
      This part of code decides if its required for a 
      captcha or not 
     } 

     if captcha_required: 
      response = HttpResponse() 
      response.status_code = 401 
      response['WWW-Authenticate'] = 'Captcha" id="%s"'% (id) 
      response.content = loader.render_to_string('captcha.html') 

      return response # This is where it goes wrong 

我相信,它不可能从这里返回一个响应。

我希望有人找到解决办法。

预先感谢您!

回答

0

嗯,我终于想出了一个办法让它工作。

根据DRF docs,应该为任何验证逻辑覆盖验证方法,还必须重写authenticate_header,以便如果在验证方法中引发异常,则可以从authenticate_header方法返回一个字符串,它将用作www-Authenticate头的值。

以下是实现的工作原理。

class ExampleCustomAuth(BaseAuthentication): 

    def authenticate(self, request): 
     req = request 
     request = req._request 
     { 
      This part of code decides if its required for a 
      captcha or not 
     } 

     if captcha_required: 
      raise exceptions.AuthenticationFailed(loader.render_to_string('captcha.html')) 

    def authenticate_header(self, request): 
     return 'Captcha" id="%s"'% (id)