We're hiring
Products

Channels

Beams

Chatkit

DocsTutorialsSupportCareersPusher Blog
Sign InSign Up
Products

Channels

Build scalable, realtime features into your apps

Features Pricing

Beams

Send push notifications programmatically at scale

Pricing

Chatkit

Build chat into your app in hours, not days

Pricing
Developers

Docs

Read the docs to learn how to use our products

Channels Beams Chatkit

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Status

Check on the status of any of our products

Products

Channels

Build scalable, realtime features into your apps

Features Pricing

Beams

Send push notifications programmatically at scale

Pricing

Chatkit

Build chat into your app in hours, not days

Pricing
Developers

Docs

Read the docs to learn how to use our products

Channels Beams Chatkit

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Status

Check on the status of any of our products

Sign InSign Up

Integrate Google reCAPTCHA in Flask

  • Michael Aboagye
February 15th, 2019
You will need Python 3.7 installed on your machine.

In this tutorial, we will look at how to add Google reCAPTCHA v2 to a registration form in Flask.

We will build a Flask app which simply allows users to register, ticking within the reCAPTCHA box to ensure it's not a robot requesting to register.

Google reCAPTCHA is a service that protects websites from spam and abuse.

Prerequisites

  • Python 3.7
  • pip (Python package installer)
  • virtualenv

This tutorial assumes you have basic knowledge in Flask, Python and you know how to navigate your operating system's command line and configure your development environment.

Register for Google reCAPTCHA

In order to integrate Google reCAPTCHA in a Flask-based app, we need to register a site and get an API key pair .

Google provides four types of reCAPTCHA.

  • reCAPTCHA v3
  • reCAPTCHA v2
  • Invisible reCAPTCHA
  • reCAPTCHA Android

reCAPTCHA v3 validates requests with a score whilst v2 validates request with the "I am not a robot" checkbox.

The Invisible reCAPTCHA does not need the user to click on a check box instead it is called upon when a user clicks on a button on a site.

In this tutorial let's make use of reCAPTCHA v2 to validate request in a Flask app.

Browse to Google and sign up or login with your Google account.

Click on the My reCAPTCHA blue button to register a site to use reCAPTCHA.

  • In the Label section, choose and enter a label to make it easy to identify the site in the future, for example: register
  • Choose the type of reCAPTCHA you want to use. Choose the reCAPTCHA v2 purposely for this tutorial.
  • In the Domains box, enter the name of the site you are registering, for example: 127.0.0.1 or localhost
  • Click on the Register button to save settings for your site. Google will generate two keys (site key and secret key) after registering a site

Create your virtual environment using Virtualenv

We need to install virtualenv via pip before we can go ahead to create a virtualized environment for this project.

Use the following command to install virtualenv:

pip install virtualenv

Next create a directory to hold the virtualized environment with the mkdir command.

mkdir Google

Afterwards change to the Google directory you created few seconds ago using the command below:

cd Google

Create a virtualized environment with the tool virtualenv

virtualenv reCaptcha

Next change to the directory reCaptcha and activate your virtual environment using the following commands:

cd reCaptcha
source bin/activate

For Windows users, refer to virtualenv user guide to find out how you can activate your virtual environment using Powershell

Still inside your virtual environment, install the following packages with pip:

    pip install Flask
    pip install Flask-WTF

The second package we have installed with pip is an integration of Flask and WTForms including CSRF, file upload and reCAPTCHA.

Inside our virtualized environment, create two files as app.py and form.py using the touch command as shown below

    touch app.py form.py 

Inside the form.py file, import the following packages

    from flask_wtf import Form, RecaptchaField
    from wtforms import TextField, PasswordField, TextAreaField, StringField, validators

On the first line, we imported Form and RecaptchaField from flask_wtf.

Next we imported TextField , PasswordField, TextAreaField, StringField , and validatorsfrom wtforms .

Beneath the import statement in form.py file, insert the following code

    class RegisterForm(Form):   
      name = StringField('name', [validators.DataRequired(), validators.Length(max=255)])
      password = PasswordField('new password', [validators.DataRequired(),validators.Length(min=8)])
      email = StringField('emailaddress', [validators.DataRequired(), validators.Length(min=6, max=35)])
      recaptcha = RecaptchaField()

Under the Class RegisterForm, we have form fields such as StringField, and PasswordField.

Each field represents a specific data type and contain a number of properties such as a label and description.

Inside the app. py file , import Flask, render_template and request from flask .

render_template will make it possible for us to display the registration form to those who navigate to the register section.

In addition, import the RegisterForm class via the form file.

Afterwards create view method for our registration form.

    // ../reCaptcha/app.py

    from flask import Flask, render_template, request, 

    from form import RegisterForm

    app = Flask(__name__)

    app.config['SECRET_KEY'] = 'lablam.2017'
    app.config['RECAPTCHA_USE_SSL']= False
    app.config['RECAPTCHA_PUBLIC_KEY']='enter_your_public_key'
    app.config['RECAPTCHA_PRIVATE_KEY']='enter_your_private_key'
    app.config['RECAPTCHA_OPTIONS']= {'theme':'black'}

    @app.route('/register', methods=['GET', 'POST']) 
    def register(): 
      form = RegisterForm()

      if form.validate_on_submit():
              return "the form has been submitted. Success!"

      return render_template("register.html", form=form)

    if __name__ == '__main__':
       app.run(port=5000, debug=True)  

In the app.py file, add your Google reCAPTCHA keys.

You need to place reCAPTCHA configuration settings below app = Flask(__name__).

    app.config['RECAPTCHA_USE_SSL']= False
    app.config['RECAPTCHA_PUBLIC_KEY']= 'enter_your_public_key'
    app.config['RECAPTCHA_PRIVATE_KEY']='enter_your_private_key'
    app.config['RECAPTCHA_OPTIONS'] = {'theme':'white'}

In the project directory, create a sub-directory using the mkdir command and name it templates.

We will place the registration HTML file inside the templates directory.

You can create HTML files in the templates by using the touch command.

    touch register.html 

The register.html file will be used to displayed registration form integrated with Google reCAPTCHA by the render_template method .

We will make use of Jinja templates to do so.

Inside the register.html file, place the following code:

    // ../reCaptcha/templates/register.html

    <html>
    <head> 
    <title>Register</title>
    </head>
    <body>
    <h1>Register form</h1>
    <form method="POST" action="{{ url_for('register') }}"> 
        {{ form.csrf_token }}
        {{ form.name.label }}
        {{ form.name }}
        <ul> 
        {% for error in form.name.error %}
           <li style="coloured:red;">{{ error }}</li>
        {% endfor %}
        </ul>
         {{ form.password.label }} 
         {{ form.password }}
         {% for error in form.password.error %} 
         <ul> 
            <li style="coloured:red;">{{ error }}</li>
         {% endfor %}
         </ul>
         {{ form.email.label }}
         {{ form.email }}
         <ul> 
         {% for error in form.email.error %}
            <li style="coloured:red;">{{ error }}</li> 
         {% endfor %}
         </ul>
         {{ form.recaptcha }}
         <input type="submit" value="submit">
    </form>
    </body>
    </html>     

Afterwards, type the following command on your console:

python app.py

Open your web browser and type the following:

localhost:5000/register

or

127.0.0.1:5000/register

This page below will be displayed to users who navigate to the register section.

Conclusion

In this tutorial, we leverage on flask_wtf to integrate Google reCAPTCHA in Flask.

Because the primary purpose of the tutorial is to show users how to integrate Google reCAPTCHA in Flask, we did not place much emphasis on the user interface.

Google reCAPTCHA can be used to prevent spam abuse

The code is available in GitHub. You can clone it to see how it works.

Clone the project repository
  • Python
  • Flask
  • no pusher tech

Products

  • Channels
  • Beams
  • Chatkit

© 2019 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.