1 # -*- coding: utf-8 -*-
5 API_SSL_SERVER="https://www.google.com/recaptcha/api"
6 API_SERVER="http://www.google.com/recaptcha/api"
7 VERIFY_SERVER="www.google.com"
9 class RecaptchaResponse(object):
10 def __init__(self, is_valid, error_code=None):
11 self.is_valid = is_valid
12 self.error_code = error_code
14 def displayhtml (public_key):
17 <div id="recaptcha_field"></div>
18 <script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
20 <script type="text/javascript">
22 Recaptcha.create("%(PublicKey)s", 'recaptcha_field', {
24 callback: Recaptcha.focus_response_field});
29 'PublicKey' : public_key,
33 def submit (recaptcha_challenge_field,
34 recaptcha_response_field,
38 if not (recaptcha_response_field and recaptcha_challenge_field and
39 len (recaptcha_response_field) and len (recaptcha_challenge_field)):
40 return RecaptchaResponse (is_valid = False, error_code = 'incorrect-captcha-sol')
43 def encode_if_necessary(s):
44 if isinstance(s, unicode):
45 return s.encode('utf-8')
48 params = urllib.urlencode ({
49 'privatekey': encode_if_necessary(private_key),
50 'remoteip' : encode_if_necessary(remoteip),
51 'challenge': encode_if_necessary(recaptcha_challenge_field),
52 'response' : encode_if_necessary(recaptcha_response_field),
55 request = urllib2.Request (
56 url = "http://%s/recaptcha/api/verify" % VERIFY_SERVER,
59 "Content-type": "application/x-www-form-urlencoded",
60 "User-agent": "reCAPTCHA Python"
64 httpresp = urllib2.urlopen(request)
66 return_values = httpresp.read().splitlines()
69 return_code = return_values[0]
71 if return_code == "true":
72 return RecaptchaResponse(is_valid = True)
74 return RecaptchaResponse(is_valid = False, error_code = return_values[1])