3 API_SSL_SERVER="https://api-secure.recaptcha.net"
4 API_SERVER="http://api.recaptcha.net"
5 VERIFY_SERVER="api-verify.recaptcha.net"
7 class RecaptchaResponse(object):
8 def __init__(self, is_valid, error_code=None):
9 self.is_valid = is_valid
10 self.error_code = error_code
12 def displayhtml (public_key,
15 """Gets the HTML to display for reCAPTCHA
17 public_key -- The public api key
18 use_ssl -- Should the request be sent over ssl?
19 error -- An error message to display (from RecaptchaResponse.error_code)"""
23 error_param = '&error=%s' % error
26 server = API_SSL_SERVER
30 return """<script type="text/javascript" src="%(ApiServer)s/challenge?k=%(PublicKey)s%(ErrorParam)s"></script>
33 <iframe src="%(ApiServer)s/noscript?k=%(PublicKey)s%(ErrorParam)s" height="300" width="500" frameborder="0"></iframe><br />
34 <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
35 <input type='hidden' name='recaptcha_response_field' value='manual_challenge' />
39 'PublicKey' : public_key,
40 'ErrorParam' : error_param,
44 def submit (recaptcha_challenge_field,
45 recaptcha_response_field,
49 Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
52 recaptcha_challenge_field -- The value of recaptcha_challenge_field from the form
53 recaptcha_response_field -- The value of recaptcha_response_field from the form
54 private_key -- your reCAPTCHA private key
55 remoteip -- the user's ip address
58 if not (recaptcha_response_field and recaptcha_challenge_field and
59 len (recaptcha_response_field) and len (recaptcha_challenge_field)):
60 return RecaptchaResponse (is_valid = False, error_code = 'incorrect-captcha-sol')
63 def encode_if_necessary(s):
64 if isinstance(s, unicode):
65 return s.encode('utf-8')
68 params = urllib.urlencode ({
69 'privatekey': encode_if_necessary(private_key),
70 'remoteip' : encode_if_necessary(remoteip),
71 'challenge': encode_if_necessary(recaptcha_challenge_field),
72 'response' : encode_if_necessary(recaptcha_response_field),
75 request = urllib2.Request (
76 url = "http://%s/verify" % VERIFY_SERVER,
79 "Content-type": "application/x-www-form-urlencoded",
80 "User-agent": "reCAPTCHA Python"
84 httpresp = urllib2.urlopen (request)
86 return_values = httpresp.read ().splitlines ();
89 return_code = return_values [0]
91 if (return_code == "true"):
92 return RecaptchaResponse (is_valid=True)
94 return RecaptchaResponse (is_valid=False, error_code = return_values [1])