I. Write in front

Now, large or small websites will basically use the verification code. When they are logged in, they should be verified. When they are downloaded, they must be verified, and the verification code will also evolve from those simple character verification codes to the verification code that needs to be recognized by pictures and text, the slide verification code that needs to drag the slider, and even the mobile phone verification code. When you deal with it, have you considered the principles behind it? Of course, for those complicated verification codes, it is still very difficult for us to get a clear picture, but we can pick a soft persimmon -- the character graphic verification code. In this way, I decided to make a simple verification code system with Python + Flask.



II. Basic Ideas

A simple validation code system aims at refreshing the validation code and verifying the user's input. If the validation is successful, follow-up operations will be carried out. If the validation fails, prompt information will be given and re-input will be required.

But what if there aren't a lot of validation code pictures? The so-called "do it yourself" is a rich third party library, which makes it very simple to produce a lot of authentication code pictures. The main module used here is pillow. Python

With the authentication code picture, all we need to do is to display it on the front page and update the authentication code, which can be easily implemented by Flask. Then I input the validation code and validate the input content. Here I use JS to implement the validation.


III. Specific steps

1. Generating Verification Code Pictures

As mentioned earlier, the main module used in this step is pillow, which can be installed using pip install pillow if it is not installed.

PIL: Python Image Library is the standard library for Python to process pictures, but PIL only supports Python 2.7, on which a compatible version was created, called pillow.

Create a new Flask project: CaptchaTest, and then create a generate.py. To generate a captcha picture, you need to create a picture first, which can be implemented with Image.new() in the pilot module. Then we need to generate the validation code text and write it to the previous generated pictures. In addition, we can add some interference elements to increase the difficulty of recognition. Below are some generated validation code pictures:


The final code to generate the verification code picture is as follows:

 1 from random import randint
 2 from PIL import Image, ImageDraw, ImageFont
 5 def get_random_color():
 6     # Random colors RGB
 7     return randint(120, 200), randint(120, 200), randint(120, 200)
10 def get_random_code():
11     # Random character
12     codes = [[chr(i) for i in range(48, 58)], [chr(i) for i in range(65, 91)], [chr(i) for i in range(97, 123)]]
13     codes = codes[randint(0, 2)]
14     return codes[randint(0, len(codes)-1)]
17 def generate_captcha(width=140, height=60, length=4):
18     # Generating Verification Code
19     img = Image.new("RGB", (width, height), (250, 250, 250))
20     draw = ImageDraw.Draw(img)
21     font = ImageFont.truetype("static/font/font.ttf", size=36)
22     # Verification Code Text
23     text = ""
24     for i in range(length):
25         c = get_random_code()
26         text += c
28         rand_len = randint(-5, 5)
29         draw.text((width * 0.2 * (i+1) + rand_len, height * 0.2 + rand_len), c, font=font, fill=get_random_color())
30     # Add jamming line
31     for i in range(3):
32         x1 = randint(0, width)
33         y1 = randint(0, height)
34         x2 = randint(0, width)
35         y2 = randint(0, height)
36         draw.line((x1, y1, x2, y2), fill=get_random_color())
37     # Adding interference points
38     for i in range(16):
39         draw.point((randint(0, width), randint(0, height)), fill=get_random_color())
40     # Save pictures
41     img.save("static/captcha/" + text + ".jpg")
42     return text + ".jpg"
45 if __name__ == "__main__":
46     for i in range(1000):
47         generate_captcha()

2. Display Verification Code Pictures

After the last step, we have got 1000 validation code pictures, which are stored in the captcha folder under static. Now the problem is how to display the validation code picture on the page. To solve this problem, first of all, we need to define a routing for randomly selecting the validation code picture and returning the path.

In Flask, the route() decorator binds a function to the URL, which can not only configure static URL, but also dynamic URL, but also static URL. The code defining the route is as follows:

1 @app.route('/get_captcha', methods=['GET'])
2 def get_captcha():
3     img_list = os.listdir("static/captcha")
4     img = img_list[random.randint(0, 1000)]
5     return os.path.join("static/captcha", img)

Where os.listdir() is used to list the contents under the folder and os.path.join() is used to return the image path.

3. Refresh Verification Code Pictures

The function of refreshing validation code pictures can be realized by using Ajax. The main process is to send a request to the back end first. After the request is successful, a validation code picture path will be obtained, and then the src attribute of the picture will be set to refresh the validation code. The URLs in Ajax can write static URLs directly, and can also use url_for to retrieve the corresponding URLs by reverse parsing.

 1 <script>
 2     function Change() {
 3         $.ajax({
 4             url: '{{ url_for('get_captcha') }}',
 5             async: true,
 6             type: "GET",
 7             success: function (data) {
 8                 document.getElementById("captcha").src = data;
 9             }
10         })
11     }
12 </script>

4. Verification of Verification Code Content

After entering the content of validation code, the input content needs to be validated. Because in the previous generation of validation code pictures, we can use JavaScript to get the name of the picture, and then get the content in the input box, compare the two, this step can also do a case-ignoring, as for the specific code will not be put.


IV. Operational screenshots

First, a screenshot of the running page. Click "Can't see clearly, change one" to refresh the verification code, and click "Confirm" to verify that the input is correct:


When the input is correct, give a hint of successful verification:


Up to now, a simple verification code system has been developed. Of course, there are many things that can be improved, such as using more complex verification codes, limiting the number of validations, and so on.


Complete code has been uploaded to GitHub!