In this article we shall see how to generate image CAPTCHA using python. This can be achieved with a few lines of code with a help of a python library called captcha. Let us get started with the installation of this package. This will be extremely helpful if you are using python as backend for your site where your login system uses CAPTCHAs for confirmation.
This package can be installed easily using pip as
pip install captcha
We can also clone the repo from here, change the directory to the downloaded one and then run the following command on the terminal.
python setup.py install
Make sure you are in the same directory as the setup.py file. Once we have installed this we are good to go.
Generate an image CAPTCHA
First of all we have to generate a random string consisting of both alphabets and numbers. This will be used to generate the CAPTCHA.
You can also specify the number of characters we want in our string by specifying the value inside the range function.
The output of the above code is,
Let us look at the complete code example to generate the image CAPTCHA.
This will generate an image like this.
How it works?
- First we import the ImageCaptcha class from the captcha library.
- Then we generate a random text using string and random modules.
- Then we initialise the ImageCaptcha class.
- After that we call the generate method by providing the text as input to the generate method.
- Finally we call the write method by providing the text and name of the output file as input to the write method.
That is it. We have generated captchas using python in just 4 lines of code. Hope this article is helpful. Bookmark us to get new articles everyday.