Validating Google's reCAPTCHA on App Engine with Python
Sun, 20 November 2016
Google have seriously revamped their reCAPTCHA recently. And it's awesome. Running this on App Engine for comments on blog posts or whatever else you need it for is quite simple.
I wrote this small Python class to help verifying the results:
import urllib2
import urllib
import json
class ReCaptchaService(object):
@staticmethod
def validate_recaptcha_form(secret_key, g_recaptcha_response, remote_ip):
url = "https://www.google.com/recaptcha/api/siteverify"
import logging
request = urllib2.Request(
url,
data=urllib.urlencode(
{
"secret": secret_key,
"response": g_recaptcha_response,
"remoteip": remote_ip
}
)
)
try:
data = urllib2.urlopen(request).read()
# {
# "success": true,
# "challenge_ts": "2016-11-13T15:35:29Z",
# "hostname": "89.123.123.123"
# }
decoded = json.loads(data)
if decoded["success"] is True:
return True
logging.info(data)
except Exception, e:
logging.exception("Failed validating recaptcha.")
return False
You'll need to provide the class with a couple properties:
def validate_recaptcha_form(secret_key, g_recaptcha_response, remote_ip):
The secret_key variable is the key obtained from the reCAPTCHA interface: https://www.google.com/recaptcha/admin
g_recaptcha_response is the POST variable, obtained from the g-recaptcha-response parameter.
remote_ip is optional (although I use it every time) and it's the IP of the user.
It's quite easy to use, and a really handy script to have.