Beispiel #1
0
def submit(recaptcha_challenge_field,
           recaptcha_response_field,
           private_key,
           remoteip,
           use_ssl=False):
    """
    Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
    for the request

    recaptcha_challenge_field -- The value of recaptcha_challenge_field
    from the form
    recaptcha_response_field -- The value of recaptcha_response_field
    from the form
    private_key -- your reCAPTCHA private key
    remoteip -- the user's ip address
    """

    if not (recaptcha_response_field and recaptcha_challenge_field and
            len(recaptcha_response_field) and len(recaptcha_challenge_field)):
        return RecaptchaResponse(is_valid=False,
                                 error_code='incorrect-captcha-sol')

    params = urlencode({
        'privatekey': want_bytes(private_key),
        'remoteip': want_bytes(remoteip),
        'challenge': want_bytes(recaptcha_challenge_field),
        'response': want_bytes(recaptcha_response_field),
    })

    if not PY2:
        params = params.encode('utf-8')

    if use_ssl:
        verify_url = 'https://%s/recaptcha/api/verify' % VERIFY_SERVER
    else:
        verify_url = 'http://%s/recaptcha/api/verify' % VERIFY_SERVER

    req = Request(url=verify_url,
                  data=params,
                  headers={
                      'Content-type': 'application/x-www-form-urlencoded',
                      'User-agent': 'reCAPTCHA Python'
                  })

    httpresp = urlopen(req)

    return_values = httpresp.read().splitlines()
    httpresp.close()

    return_code = return_values[0]
    if not PY2:
        return_code = return_code.decode('utf-8')

    if (return_code == "true"):
        return RecaptchaResponse(is_valid=True)
    else:
        return RecaptchaResponse(is_valid=False, error_code=return_values[1])
def recaptcha_request(params):
    request_object = Request(
        url="https://%s/recaptcha/api/siteverify" %
        getattr(settings, "RECAPTCHA_DOMAIN", DEFAULT_RECAPTCHA_DOMAIN),
        data=params,
        headers={
            "Content-type": "application/x-www-form-urlencoded",
            "User-agent": "reCAPTCHA Django"
        })

    # Add proxy values to opener if needed.
    opener_args = []
    proxies = getattr(settings, "RECAPTCHA_PROXY", {})
    if proxies:
        opener_args = [ProxyHandler(proxies)]
    opener = build_opener(*opener_args)

    # Get response from POST to Google endpoint.
    return opener.open(request_object,
                       timeout=getattr(settings,
                                       "RECAPTCHA_VERIFY_REQUEST_TIMEOUT", 10))