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
我相信,它不可能从这里返回一个响应。
我希望有人找到解决办法。
预先感谢您!