Build a Flask application to validate CAPTCHA - GeeksforGeeks

14 Sep, 2021
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.
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?
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.
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.
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>
Let’s create a simple app that shows the above form without captcha.
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:
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_templatefrom pymongo import MongoClient  app = Flask(__name__)  # Database Config# If your mongodb runs on a different port# change 27017 to that port numbermongoClient = MongoClient('localhost', 27017)  @app.route('/')def index():    return render_template('form.html')  if __name__ == "__main__":    app.run(debug=True)
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 flak-sessionstore and captcha packages. 
Python3
import uuidfrom flask import Flask, render_templatefrom flask_sessionstore import Sessionfrom flask_session_captcha import FlaskSessionCaptchafrom pymongo import MongoClient  app = Flask(__name__)  # Database Config# If your mongodb runs on a different port# change 27017 to that port numbermongoClient = MongoClient('localhost', 27017)  # Captcha Configurationapp.config["SECRET_KEY"] = uuid.uuid4()app.config['CAPTCHA_ENABLE'] = True  # Set 5 as character length in captchaapp.config['CAPTCHA_LENGTH'] = 5  # Set the captcha height and widthapp.config['CAPTCHA_WIDTH'] = 160app.config['CAPTCHA_HEIGHT'] = 60app.config['SESSION_MONGODB'] = mongoClientapp.config['SESSION_TYPE'] = 'mongodb'  # Enables server sessionSession(app)  # Initialize FlaskSessionCaptchacaptcha = FlaskSessionCaptcha(app)  @app.route('/')def index():    return render_template('form.html')  if __name__ == "__main__":    app.run(debug=True)
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 uuidimport loggingfrom flask import Flask, render_templatefrom flask_sessionstore import Sessionfrom flask_session_captcha import FlaskSessionCaptchafrom pymongo import MongoClient  app = Flask(__name__)  # Database Config# If your mongodb runs on a different port# change 27017 to that port numbermongoClient = MongoClient('localhost', 27017)  # Captcha Configurationapp.config["SECRET_KEY"] = uuid.uuid4()app.config['CAPTCHA_ENABLE'] = True  # Set 5 as character length in captchaapp.config['CAPTCHA_LENGTH'] = 5  # Set the captcha height and widthapp.config['CAPTCHA_WIDTH'] = 160app.config['CAPTCHA_HEIGHT'] = 60app.config['SESSION_MONGODB'] = mongoClientapp.config['SESSION_TYPE'] = 'mongodb'  # Enables server sessionSession(app)  # Initialize FlaskSessionCaptchacaptcha = FlaskSessionCaptcha(app)  @app.route('/')def index():    return render_template('form.html')    if __name__ == "__main__":    app.debug = True    logging.getLogger().setLevel("DEBUG")    app.run()
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 uuidimport loggingfrom flask import Flask, request, render_templatefrom flask_sessionstore import Sessionfrom flask_session_captcha import FlaskSessionCaptchafrom pymongo import MongoClient  app = Flask(__name__)  # Database Config# If your mongodb runs on a different port# change 27017 to that port numbermongoClient = MongoClient('localhost', 27017)  # Captcha Configurationapp.config["SECRET_KEY"] = uuid.uuid4()app.config['CAPTCHA_ENABLE'] = True  # Set 5 as character length in captchaapp.config['CAPTCHA_LENGTH'] = 5  # Set the captcha height and widthapp.config['CAPTCHA_WIDTH'] = 160app.config['CAPTCHA_HEIGHT'] = 60app.config['SESSION_MONGODB'] = mongoClientapp.config['SESSION_TYPE'] = 'mongodb'  # Enables server sessionSession(app)  # Initialize FlaskSessionCaptchacaptcha = 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()
Start server with:
python app.py
Then visit:
http://localhost:5000/
Output:
Python Flask
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python