Build a Flask application to validate CAPTCHA
Last Updated :
26 May, 2022
In this article, we are going a build a web application that can have a CAPTCHA. CAPTCHA is a tool you can use to differentiate between real users and automated users. CAPTCHAs are usually found on the login pages or on payment pages.
What is CAPTCHA?
Captcha is strategy used to ensure sites against spam. Objective is to prevent intuitive sites from being spammed by sifting through naturally created input. Abbreviation CAPTCHA means ‘Totally Automated Public Turing test to distinguish Computers and Humans’. Captchas are generally utilized when web applications require client input. Envision you are running online store and need to offer your clients chance to compose item surveys in remarks segment. For this situation, you need to guarantee that passages are really from your clients or if nothing else from human site guests. You will regularly go over naturally produced spam remarks – in most pessimistic scenario connecting to your opposition.
Note: For more information refer to What is CAPTCHA code?
Requirements
- Flask framework: Flask is an API of Python that allows us to build up web-applications. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application.
- Flask-session-captcha library: A captcha implementation for flask using flask-sessionstore and captcha packages. Each captcha challenge answer is saved in the server-side session of the challenged client.
- MongoDB: MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data.
Note: The database depends on your application. Flask-session-captcha library supports multiple databases so if you are using any other database be sure to check out their documentation.
Build the application
You can install all the required dependencies using the following command
pip install -U Flask flask-session-captcha Flask-Sessionstore pymongo
It is recommended that you install all the dependencies in the virtual environment.
Stepwise Implementation
Step 1: Create the UI
Create a folder called templates and inside it create an HTML file. You can save the HTML file as form.html.
HTML
<form method="post">
<!-- The following line creates the captcha -->
{{ captcha() }}
<input type="text" name="captcha">
<input type="submit" name="submit">
</form>
Step 2: Create app.py
Let's create a simple app that shows the above form without captcha.
Example: Initialize Flask Application
Python3
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('form.html')
if __name__ == "__main__":
app.run(debug=True)
Run the server using the following command to make sure that the application is running successfully and the form.html page is displayed.
python app.py
Output:

Step 3: Initialize PyMongoClient
To use Python in MongoDB, we are going to import PyMongo. From that, MongoClient can be imported which is used to create a client to the database.
Python3
from flask import Flask, render_template
from pymongo import MongoClient
app = Flask(__name__)
# Database Config
# If your mongodb runs on a different port
# change 27017 to that port number
mongoClient = MongoClient('localhost', 27017)
@app.route('/')
def index():
return render_template('form.html')
if __name__ == "__main__":
app.run(debug=True)
Step 4: Configure Captcha
There are various configurations required to use the captcha in the application. Here we will be using flask_session_captcha module which implements captcha using flask-sessionstore and captcha packages.
Python3
import uuid
from flask import Flask, render_template
from flask_sessionstore import Session
from flask_session_captcha import FlaskSessionCaptcha
from pymongo import MongoClient
app = Flask(__name__)
# Database Config
# If your mongodb runs on a different port
# change 27017 to that port number
mongoClient = MongoClient('localhost', 27017)
# Captcha Configuration
app.config["SECRET_KEY"] = uuid.uuid4()
app.config['CAPTCHA_ENABLE'] = True
# Set 5 as character length in captcha
app.config['CAPTCHA_LENGTH'] = 5
# Set the captcha height and width
app.config['CAPTCHA_WIDTH'] = 160
app.config['CAPTCHA_HEIGHT'] = 60
app.config['SESSION_MONGODB'] = mongoClient
app.config['SESSION_TYPE'] = 'mongodb'
# Enables server session
Session(app)
# Initialize FlaskSessionCaptcha
captcha = FlaskSessionCaptcha(app)
@app.route('/')
def index():
return render_template('form.html')
if __name__ == "__main__":
app.run(debug=True)
Step 5: Configure Logging
Logging is a means of tracking events that happen when some software runs. Here we have used the logging.getLogger() method which returns a logger with a specified name otherwise returns the root logger,
Python3
import uuid
import logging
from flask import Flask, render_template
from flask_sessionstore import Session
from flask_session_captcha import FlaskSessionCaptcha
from pymongo import MongoClient
app = Flask(__name__)
# Database Config
# If your mongodb runs on a different port
# change 27017 to that port number
mongoClient = MongoClient('localhost', 27017)
# Captcha Configuration
app.config["SECRET_KEY"] = uuid.uuid4()
app.config['CAPTCHA_ENABLE'] = True
# Set 5 as character length in captcha
app.config['CAPTCHA_LENGTH'] = 5
# Set the captcha height and width
app.config['CAPTCHA_WIDTH'] = 160
app.config['CAPTCHA_HEIGHT'] = 60
app.config['SESSION_MONGODB'] = mongoClient
app.config['SESSION_TYPE'] = 'mongodb'
# Enables server session
Session(app)
# Initialize FlaskSessionCaptcha
captcha = FlaskSessionCaptcha(app)
@app.route('/')
def index():
return render_template('form.html')
if __name__ == "__main__":
app.debug = True
logging.getLogger().setLevel("DEBUG")
app.run()
Step 6: Code the index route
Here we have used the POST method which returns checks the input against the captcha. If the captcha matches success method is displayed otherwise fail method is displayed.
Python3
import uuid
import logging
from flask import Flask, request, render_template
from flask_sessionstore import Session
from flask_session_captcha import FlaskSessionCaptcha
from pymongo import MongoClient
app = Flask(__name__)
# Database Config
# If your mongodb runs on a different port
# change 27017 to that port number
mongoClient = MongoClient('localhost', 27017)
# Captcha Configuration
app.config["SECRET_KEY"] = uuid.uuid4()
app.config['CAPTCHA_ENABLE'] = True
# Set 5 as character length in captcha
app.config['CAPTCHA_LENGTH'] = 5
# Set the captcha height and width
app.config['CAPTCHA_WIDTH'] = 160
app.config['CAPTCHA_HEIGHT'] = 60
app.config['SESSION_MONGODB'] = mongoClient
app.config['SESSION_TYPE'] = 'mongodb'
# Enables server session
Session(app)
# Initialize FlaskSessionCaptcha
captcha = FlaskSessionCaptcha(app)
@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == "POST":
if captcha.validate():
return "success"
else:
return "fail"
return render_template("form.html")
if __name__ == "__main__":
app.debug = True
logging.getLogger().setLevel("DEBUG")
app.run()
Run the app
Start server with:
python app.py
Then visit:
http://localhost:5000/
Output:

Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read