Adding reCAPTCHA to a Flask site

Posted on Sat 20 June 2020 in dev-journal

This post will explain how to add Google reCAPTCHA to a Python Flask application using Flask-WTF.

The first thing you will need to do is get your SITE KEY and your SECRET KEY from Google reCAPTCHA Make sure to create a reCAPTCHA version 2 site. Version 3 takes much more configuration to get running.

Flask-WTF uses config variables name RECAPTCHA_PUBLIC_KEY and RECAPTCHA_PRIVATE_KEY

  • Add the following to your
RECAPTCHA_PUBLIC_KEY = "<Enter Site Key here>"
# make sure to load the private key from environment variables
  • Add RECAPTCHA_PRIVATE_KEY=<secret_key> to a .flaskenv file or in the Environment Variables section of your conveyor site page

Add the RecaptchaField to the Flask-WTF form

from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired

class RegistrationForm(FlaskForm):
    recaptcha = RecaptchaField()
    email = StringField(('Email'), validators=[DataRequired(), Email()])
    password = PasswordField(('Password'), validators=[DataRequired()])
    submit = SubmitField(('Create Account'))

Add the following to the template file that uses the form:

{{ form.recaptcha }}