Implement captcha in Django projects

PIL/ Pillow and Random generate an image and a string of random numbers in the background and store them in memory (or directly in your Django project).

#! /usr/bin/env python # -*- coding:utf-8 -*- import random from PIL import Image, ImageDraw, ImageFont, ImageFilter _letter_cases = "abcdefGHjkmnpQrSTUvwxy" # lowercase letters, remove possible interference I, L, O, Upper_cases = _letter_cases. Upper () # upper_numbers = ". Join (map(STR, range(3,)) Join ((_letter_cases, _upper_cases, _numbers)) def create_validate_code(size=(120, 30), chars=init_chars, img_type="GIF", mode="RGB", bg_color=(255, 255, 255), fg_color=(0, 0, 255), font_size=18, font_type="Monaco.ttf", length=4, draw_lines=True, n_line=(1, 2), draw_points=True, point_chance=2): """ @todo: @param size: specifies the size and format (width, height) of the image. The default value is (120, 30). @param chars: Specifies the set of allowed characters. GIF, JPEG, TIFF, PNG @param mode: image mode, default: RGB @param bg_color: background color, default: white @param fg_color: #0000FF @param font_size: captcha font size @param font_type: Captcha font size: ae_alarabiya. ttf@param length: Number of verification code characters @param draw_lines: indicates whether to draw interference lines. @param n_lines: indicates the number of interference lines. The format is a tuple. PIL Image instance @return: [1]: PIL Image instance @return: [1]: Img = image.new (mode, size, size) Draw = ImageDraw.Draw(img) # def get_chars(): """ return random. Sample (chars, length) def create_lines(): "" line_num = random. Randint (*n_line) # for I in range(line_num): Begin = (random.randint(0, size[0]), random.randint(0, size[1])) end = (random.randint(0, size[0]), random.randint(0, size[1])) draw.line([begin, end], fill=(0, 0, 0)) def create_points(): "" chance = min(100, Max (0, int(point_chance)) # for w in range(width): for h in range(height) tmp = random.randint(0, 100) if tmp > 100 - chance: draw.point((w, h), fill=(0, 0, 0)) def create_strs(): "" c_chars = get_chars() STRS = '%s' % '. Join (c_chars) # Separate each character with a space  font_size) font_width, font_height = font.getsize(strs) draw.text(((width - font_width) / 3, (height - font_height) / 3), strs, font=font, fill=fg_color) return ''.join(c_chars) if draw_lines: create_lines() if draw_points: Create_points () STRS = create_strs() # params = [1-float (random.randint(1, 2)) / 100, 0, 0, 0, params = [1-float (random.randint(1, 2))) / 100, 0, 0, 0, 1 - float(random.randint(1, 10)) / 100, float(random.randint(1, 2)) / 500, 0.001, float(random.randint(1, 10)) / 500, 0.001, float(random.randint(1, 10)) 2)) / 500 ] img = img.transform(size, Image.PERSPECTIVE, Img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # return img, STRSCopy the code

You can also write it directly in views.py, as shown in the figure below

def verifycode(request): Print (path_to_static) # from PIL import Image, ImageDraw, ImageFont Bgcolor = (random.randrange(20, 100), random.randrange(20, 100), random.randrange(20, 100) Im = image.new ('RGB', (width, height), Draw = imagedRaw.draw (im) # Call the point() function of the brush to draw noise for I in range(0, 100): xy = (random.randrange(0, width), random.randrange(0, height)) fill = (random.randrange(0, 255), 255, random.randrange(0, 255)) draw.point(xy, The fill = the fill) # define captcha values of alternative STR = '123456789 qwertyupasdfghjklzxcvbnmqwertyupasdfghjklzxcvbnm # randomly selected from four values as a captcha rand_str =' for i in range(0, 4): rand_str += str[random.randrange(0, Len (STR))] # store session case insensitive request.session['check_code'] = rand_str.lower() # construct font object font = Fontcolor1 = (255, random. Randrange (0, 255), random. Randrange (0, 0) 255)) fontcolor2 = (255, random.randrange(0, 255), random.randrange(0, 255)) fontcolor3 = (255, random.randrange(0, 255), random.randrange(0, 255)) fontcolor4 = (255, random.randrange(0, 255), random.randrange(0, Draw. Text ((5, 2), rand_str[0], font=font, fill=fontcolor1) draw. Text ((25, 2), rand_str[1], font=font, fill=fontcolor2) draw.text((50, 2), rand_str[2], font=font, fill=fontcolor3) draw.text((75, 2), rand_str[3], font=font, Fill =fontcolor4) # Request.session ['verifycode'] = rand_str.lower() # import IO buf = io.bytesio () # save images in memory Save (buf, 'PNG ') PNG check_code = rand_str return HttpResponse(buf.getValue (), 'image/ PNG ')Copy the code

It will be used as an interface to interact with the front page, and will also configure a file about fonts simkai. TTF, link: pan.baidu.com/s/1_SwGqhD7… Extract code: BME9 can extract the method that finally invokes the verification code in the login interface.

The login page

You can also add some judgment information in the front page to determine whether the verification code is successful. routing