在3次错误尝试后显示recaptcha并在Django中处理它?

时间:2013-03-28 09:44:22

标签: django recaptcha

我正在使用Django Class-based view:我想在3次之后才显示验证码,并且仅在显示后才处理验证码。直到现在,我只能在一次错误尝试后显示验证码:

def post(self, request):
        response = captcha.submit(  
            request.POST.get('recaptcha_challenge_field'),  
            request.POST.get('recaptcha_response_field'),  
            '[[ MY PRIVATE KEY ]]',  
            request.META['REMOTE_ADDR'],)  

        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(username=username, password=password)
        state = "The username or password is incorrect."
        if user is not None:
            login(request, user)
            return HttpResponseRedirect('/index/')
        else:
            #captcha = CaptchaField()
            public_key = settings.RECAPTCHA_PUBLIC_KEY
            script = displayhtml(public_key=public_key)
            return render_to_response('index.html', {'state':state, 'captcha':'captcha', 'script':script}, context_instance=RequestContext(request))

我想在三次后显示验证码并使用response.is_valid处理它。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

最简单的解决方案可能是存储cookie中的尝试次数,并在每次失败尝试时递增它。显然这可以被篡改,这使我有了签名的cookie:

如果值已被篡改,基本上签名的cookie将引发异常。

你也可以在会话中存储计数器,但是当cookie发挥作用时,我没有看到过早创建会话对象的任何意义。