September 25, 2022

How to Add backend ReCaptcha to a flask server (Coqui TTS)

Hello. This is part 3 of our application and in that episode, we will integrate Recaptcha to a flask app on the backend. The frontend integration is done, but I will explain a bit also.

Frontend

On the front end, we just need to follow the steps from the google website. So what we can do is first import the script:

 <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
        async defer>
</script>

And the onloadCallback from the script we implement here :

var onloadCallback = function() {
    captha = grecaptcha.render('html_element', {
       'sitekey' : 'Website Key'
    });
};

html_element is the id of the Recaptcha element on the frontend like:

<div id="html_element"></div>

That element must be added to your form so it is submitted automatically with the content. And we can check if the Recaptcha is filled on the front by calling:

if( !grecaptcha.getResponse(captha) ){
    alert("Fill the recaptcha please !")
}

Backend

On the backend it is quick and simple:

We must just call the route https://www.google.com/recaptcha/api/siteverify

And we pass 2 parameters to the request:

{
  "secret" : "RECAPTCHA_SITE_SECRET",
  "response": request.form["g-recaptcha-response"] // from frontend
}

And as a complete code it gives:

response = requests.post("https://www.google.com/recaptcha/api/siteverify", data ={
        "secret" : os.environ.get("RECAPTCHA_SITE_SECRET"),
        "response": request.form["g-recaptcha-response"]
    })

    if(response.status_code == 200):
        data = response.json()
        if(data["success"]):
          pass // do something
    //do another thing is everthing is bad
          

The complete code can also be found here:

Thanks, and see you in the last part, where we will wrap the whole TTS app into a docker container and deploy it online.

Let start your transition to AI

Automate your business processes, handle customer support, Sales SEO and build your website with AI.

Transform Your Business

Tailor and enhance your website by understanding and optimizing for each visitor's unique needs.

Boost Your Revenue

Our innovative, data-driven strategies deliver measurable results in days, not months.

Stay Ahead of the Competition

Outplay your competitors with AI solutions that deliver measurable results.

On a mission to transform every business with AI.

Request a free implementation plan.

You already have a plan? Let make it real.

Hire the best to drive your AI transformation.