首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从Django rest框架的自定义身份验证类返回自定义响应对象

如何从Django rest框架的自定义身份验证类返回自定义响应对象
EN

Stack Overflow用户
提问于 2016-10-19 11:29:55
回答 1查看 923关注 0票数 2

我已经为这事绞尽脑汁了将近3-4天了。

让我解释一下情况。我有一个基于DRF(Django REST Framework)类的视图和一个自定义身份验证类。据我所知,您可以重写DRF的BaseAuthentication类的身份验证方法来实现您的自定义身份验证,而只有在验证失败时才能引发从DRF提供的预定义异常。

我的问题是,我试图找到一种方法来返回自定义响应,即,captcha HTML直接从身份验证类返回到前端,以便在我看来没有实现任何与身份验证相关的代码。

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

代码语言:javascript
复制
class ExampleView(APIView):
    authentication_classes = (ExampleCustomAuth, )

    def get(self, request):
        pass

这是观点,这部分是绝对好的。

代码语言:javascript
复制
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

我相信,我们不可能从这里收回回应。

我希望有人想办法绕过这件事。

提前谢谢你!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-20 11:23:19

我终于想出办法让它起作用了。

根据DRF文档,对于任何身份验证逻辑,都应该重写身份验证方法,并且还必须重写authenticate_header,以便如果在身份验证方法中引发异常,则可以从authenticate_header方法返回一个字符串,该字符串将用作www-身份验证标头的值。

下面是实现的工作方式。

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40130210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档