Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Flask Templates
  • Jinja2
  • Flask-REST API
  • Python SQLAlchemy
  • Flask Bcrypt
  • Flask Cookies
  • Json
  • Postman
  • Django
  • Flask Projects
  • Flask Interview Questions
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJs
  • Vue.Js
Open In App
Next Article:
How to Run a Flask Application
Next article icon

Build a Flask application to validate CAPTCHA

Last Updated : 26 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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:



Next Article
How to Run a Flask Application
author
gupta_shrinath
Improve
Article Tags :
  • Python
  • Flask Projects
  • Python Flask
Practice Tags :
  • python

Similar Reads

  • Implement ChatGPT in a Flask Application
    You can build dynamic and interactive chat interfaces by integrating ChatGPT into a Flask application. This article's instructions can help you integrate ChatGPT into your Flask project and give users engaging chat experiences. Improve the user interface, try out new prompts, and look into new optio
    3 min read
  • How to Run a Flask Application
    After successfully creating a Flask app, we can run it on the development server using the Flask CLI or by running the Python script. Simply execute one of the following commands in the terminal: flask --app app_name runpython app_nameFile StructureHere, we are using the following folder and file. D
    4 min read
  • How To Use Web Forms in a Flask Application
    A web framework called Flask provides modules for making straightforward web applications in Python. It was created using the WSGI tools and the Jinja2 template engine. An example of a micro-framework is Flask. Python web application development follows the WSGI standard, also referred to as web ser
    5 min read
  • Flask - (Creating first simple application)
    Building a webpage using python.There are many modules or frameworks which allow building your webpage using python like a bottle, Django, Flask, etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you with the versatility to program wit
    6 min read
  • Login Application and Validating info using Kivy GUI and Pandas in Python
    Prerequisites : Kivy, Pandas Kivy is a multiplatform GUI library, known for being responsive. It provides management of multiple screens in a single application. In this application we will be using multiple screens to log in user's info and validate it. We will save the information in a csv file an
    5 min read
  • Testing FastAPI Application
    The web framework in Python that is used for creating modern and fast APIs is called FastAPI. Once we have created the FastAPI, there is a need to test if the API is working fine or not according to the requirements. In this article, we will discuss the various ways to test the FastAPI application.
    3 min read
  • Python | Build a REST API using Flask
    Prerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
    3 min read
  • Comparison of FastAPI with Django and Flask
    For starters, as you may know, Python is an interpreted programming language that is becoming more and more popular for building web applications. However, there are numerous web frameworks to choose from but they all have different use cases. In this article, we will look at 3 frameworks which are
    4 min read
  • Create a Weather app using Flask | Python
    Prerequisite : Flask installation Flask is a lightweight framework written in Python. It is lightweight because it does not require particular tools or libraries and allow rapid web development. today we will create a weather app using flask as a web framework. this weather web app will provide curr
    2 min read
  • Visiting Card Scanner GUI Application using Python
    Python is an emerging programming language that consists of many in-built modules and libraries. Which provides support to many web and agile applications. Due to its clean and concise syntax behavior, many gigantic and renowned organizations like Instagram, Netflix so-and-so forth are working in Py
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences