How to validate a ReCaptcha response server side with Python?

柔情痞子 提交于 2019-12-06 10:16:10
dbrrt

It was actually quite straightforward, and no library is required to perform this verification, following Google's documentation : https://developers.google.com/recaptcha/docs/verify

I just had to encode my parameters in the address and send a request to Google servers, here's my code, note that I'm using Flask, but the principle remains the same for any Python back-end :

from urllib.parse import urlencode
from urllib.request import urlopen
import json


        URIReCaptcha = 'https://www.google.com/recaptcha/api/siteverify'
        recaptchaResponse = body.get('recaptchaResponse', None)
        private_recaptcha = '6LdXXXXXXXXXXXXXXXXXXXXXXXX'
        remote_ip = request.remote_addr
        params = urlencode({
            'secret': private_recaptcha,
            'response': recaptchaResponse,
            'remote_ip': remote_ip,
        })

        # print params
        data = urlopen(URIReCaptcha, params.encode('utf-8')).read()
        result = json.loads(data)
        success = result.get('success', None)

        if success == True:
            print 'reCaptcha passed'
        else:
            print 'recaptcha failed'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!