-
-
Save nurupo/c12bcb2faeb021a0575dd9e31ba4041a to your computer and use it in GitHub Desktop.
Python reCAPTCHA v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Modified version of https://pypi.python.org/pypi/recaptcha-client | |
# made to work with recaptcha api v2, since v1 is phasing out soon | |
# Authors: Ben Maurer <support@recaptcha.net> | |
# Maxim Biro <nurupo.contributions@gmail.com> | |
# License: MIT/X11 | |
import urllib2, urllib, json | |
class RecaptchaResponse(object): | |
def __init__(self, is_valid, error_codes=None): | |
self.is_valid = is_valid | |
self.error_codes = error_codes | |
def displayhtml (site_key): | |
"""Gets the HTML to display for reCAPTCHA | |
site_key -- The site api key""" | |
return """ | |
<script src='https://www.google.com/recaptcha/api.js'></script> | |
<div class="g-recaptcha" data-sitekey="%(SiteKey)s"></div> | |
""" % { | |
'SiteKey' : site_key | |
} | |
def submit (recaptcha_response_field, | |
secret_key, | |
remoteip): | |
""" | |
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse | |
for the request | |
recaptcha_response_field -- The value of g-recaptcha-response from the form | |
secret_key -- your reCAPTCHA secret key | |
remoteip -- the user's ip address | |
""" | |
if not (recaptcha_response_field and len (recaptcha_response_field)): | |
return RecaptchaResponse (is_valid = False, error_codes = ['incorrect-captcha-sol']) | |
def encode_if_necessary(s): | |
if isinstance(s, unicode): | |
return s.encode('utf-8') | |
return s | |
params = urllib.urlencode ({ | |
'secret': encode_if_necessary(secret_key), | |
'remoteip': encode_if_necessary(remoteip), | |
'response': encode_if_necessary(recaptcha_response_field) | |
}) | |
request = urllib2.Request ( | |
url = "https://www.google.com/recaptcha/api/siteverify", | |
data = params, | |
headers = { | |
"Content-type": "application/x-www-form-urlencoded", | |
"User-agent": "reCAPTCHA Python" | |
} | |
) | |
httpresp = urllib2.urlopen (request) | |
data = json.load(httpresp) | |
httpresp.close(); | |
if (data['success']): | |
return RecaptchaResponse (is_valid=True) | |
else: | |
return RecaptchaResponse (is_valid=False, error_codes = data['error-codes']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment