Python Captcha Library: Secure Web Forms with CAPTCHA Integration

Python Captcha Library is a powerful tool that allows developers to create and integrate CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) into their web forms. CAPTCHAs are widely used to prevent automated bots from spamming or abusing web applications and ensure the security of user data.

This documentation article provides a step-by-step guide on installing the library, creating and generating CAPTCHA text, and integrating it into a sample Python web project.

Installation

To get started with Python Captcha Library, follow these simple steps to install it using pip:

pip install captcha

Generating Captcha Text

The core functionality of the Python Captcha Library revolves around generating CAPTCHA text. Let's explore how to use the library to create CAPTCHA text using the captcha.image.ImageCaptcha class.

# Import the necessary class
from captcha.image import ImageCaptcha

# Create an instance of ImageCaptcha with custom dimensions
cap = ImageCaptcha(width=280, height=90)

# Define the CAPTCHA text
c_text = "samcodehub"

# Generate the CAPTCHA data and save it as an image file
data = cap.generate(c_text)
cap.write(c_text, "cap.png")

The code above will create a CAPTCHA image with the text "samcodehub" and save it as "cap.png" in the current working directory.

You can watch the video below:

Integration with a Web Project

Now, let's see how you can integrate the Python Captcha Library into a Python web project. For this example, we'll use the Flask framework (learn more about Flask framework.) to create a simple web application that includes a CAPTCHA-protected form.

Prerequisites

Before proceeding, make sure you have installed Flask. If not, install it using pip:

pip install flask

Creating the Flask Web Application

Create a new Python file named app.py, and include the following code to set up the Flask web application and serve a web page with the CAPTCHA-protected form:

# Import necessary modules
from flask import Flask, render_template, request, redirect, url_for
from captcha.image import ImageCaptcha

# Create the Flask app
app = Flask(__name__)

# Define CAPTCHA dimensions
captcha_width = 280
captcha_height = 90

# Create an instance of ImageCaptcha
cap = ImageCaptcha(width=captcha_width, height=captcha_height)

# Route to display the CAPTCHA form
@app.route('/', methods=['GET', 'POST'])
def captcha_form():
    if request.method == 'POST':
        # Validate the CAPTCHA input
        captcha_input = request.form['captcha_input']
        captcha_text = request.form['captcha_text']
        if captcha_input.lower() == captcha_text.lower():
            return "Success! CAPTCHA is verified."
        else:
            return "Error! CAPTCHA verification failed."
    else:
        # Generate a random CAPTCHA text
        captcha_text = "samplecaptcha"
        captcha_data = cap.generate(captcha_text)

        # Render the CAPTCHA form template
        return render_template('captcha_form.html', captcha_data=captcha_data)

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

Creating the CAPTCHA Form Template

Create a new folder named templates, and inside that folder, create a file named captcha_form.html. This file will be used to display the CAPTCHA form to the user:

<!DOCTYPE html>
<html>
<head>
    <title>Python Captcha Library Example</title>
</head>
<body>
    <h1>Sample CAPTCHA Form</h1>
    <form method="post" action="/">
        <img src="{{ captcha_data }}" alt="Captcha Image">
        <br>
        <label for="captcha_input">Enter the CAPTCHA text:</label>
        <input type="text" id="captcha_input" name="captcha_input" required>
        <input type="hidden" name="captcha_text" value="samplecaptcha">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Running the Web Application

Save both app.py and captcha_form.html files in their respective locations. Open a terminal or command prompt, navigate to the project directory, and run the Flask app:

python app.py

Visit http://127.0.0.1:5000/ in your web browser, and you'll see the CAPTCHA-protected form. Enter the displayed CAPTCHA text accurately to verify it. If the text matches, you'll see a success message; otherwise, you'll see an error message.

Conclusion

Python Captcha Library provides an easy-to-use solution for generating CAPTCHA text, making it simple to enhance the security of your web forms. In this guide, you learned how to install the library, generate CAPTCHA text, and integrate it into a sample Python web project using Flask.

By implementing CAPTCHA, you can prevent automated bots from abusing your web application, ensuring a safer and more secure user experience.

Comments...

banner