验证码验证Python Django

时间:2018-11-26 12:43:56

标签: python django captcha

对于以下设置,我收到无效的验证码响应。联系表格工作得非常好,我添加了验证验证码的规则,检查了秘密密钥,即使解决了问题,仍然获得了无效的验证码。下面是我的设置:

views.py

:silent

我的模板:

    def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

def grecaptcha_verify(request):
        response = {}
        data = request.POST
        captcha_rs = data.get('g-recaptcha-response')
        url = "https://www.google.com/recaptcha/api/siteverify"
        params = {
            'secret': settings.RECAPTCHA_SECRET_KEY,
            'response': captcha_rs,
            'remoteip': get_client_ip(request)
        }
        verify_rs = requests.get(url, params=params, verify=True)
        verify_rs = verify_rs.json()
        response["status"] = verify_rs.get("success", False)
        response['message'] = verify_rs.get('error-codes', None) or "Unspecified error."
        return response

def contact(request):
        if request.method == 'POST':
            if grecaptcha_verify(request) == "success":
                subject = request.POST.get('subject')
                message = request.POST.get('message')
                email = request.POST.get('email')     
                if subject and message and email:
                    try:
                        send_mail(subject, message, email, ['myemail@gmail.com'],fail_silently= True)
                    except BadHeaderError:
                        return HttpResponse('{Bad Header}')
                    return greatsuccess(request)        
                else:
                    return HttpResponse('{Invalid Form}')
            else:
                return HttpResponse('Invalid Captcha')    
        return render(request, 'personal/contact.html')

我对Python还是很陌生,如何检查后台发生了什么,以及在什么时候验证失败?

2 个答案:

答案 0 :(得分:1)

您正在向get提出验证请求,但您需要向其提出post请求。这就是验证码验证失败的原因。所以尝试这样:

    url = "https://www.google.com/recaptcha/api/siteverify"
    headers = {'User-Agent': 'DebuguearApi-Browser',}
    params = {'secret': settings.RECAPTCHA_SECRET_KEY, 'response': captcha_rs}
    verify_rs = requests.post(url, data=params, headers=headers)  # <--  Update Here
    ... # rest of your code

请参阅documentation,了解如何验证重新验证。

答案 1 :(得分:0)

好的。 我知道了感谢Ruddra的所有帮助。

我首先删除了</div>,因为我发现这是不必要的。这允许将g-recaptcha-response包含在POST数据中。显然,重要的是要确保您的表单正确无误,并且Google会喜欢它。

第二,我根据收到的建议对主要views.py进行了一些修改,并进行了一些改进。

def greatsuccess(request):
    messages.success(request, "Email sent!")
    return render(request, 'personal/contact.html')

def greatfail(request):
    messages.error(request, "Invalid Captcha!")
    return render(request, 'personal/contact.html')

def grecaptcha_verify(request):
        data = request.POST
        captcha_rs = data.get('g-recaptcha-response')
        url = "https://www.google.com/recaptcha/api/siteverify"
        headers = {'User-Agent': 'DebuguearApi-Browser',}
        params = {'secret': settings.RECAPTCHA_SECRET_KEY, 'response': captcha_rs}
        verify_rs = requests.post(url,params, headers=headers)
        verify_rs = verify_rs.json()
        response = verify_rs.get("success", False)
        return response 

def contact(request):
    if request.method == 'POST':
        response=grecaptcha_verify(request)
        if response == True :
            subject = request.POST.get('subject')
            message = request.POST.get('message')
            email = request.POST.get('email')     
            if subject and message and email:
                try:
                        send_mail('Sent from mywebsite '+subject, message, email, ['email@gmail.com'],fail_silently= True)
                except BadHeaderError:
                    return HttpResponse('{Bad Header}')
                return greatsuccess(request)        
            else:
                    return HttpResponse('{Invalid Form}')
        else:
            greatfail(request)
    return render(request, 'personal/contact.html')

我的模板:

<form method="POST">
                    {% csrf_token %}
                        <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" maxlength="70" required>

                    <br>
                    <div class="form-group">
                        <input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
                    </div>

                    <div class="form-group">
                    <textarea class="form-control" type="textarea" id="message" name="message" placeholder="Message" maxlength="300" rows="7"></textarea>                
                    </div>

                    <div class="g-recaptcha" data-sitekey="key"></div>

                    <button type="submit"  name="submit" class="btn btn-m btn-secondary">Submit</button>

        </form>

    {% for message in messages %}
        {{ message }}
        {% endfor %}