Share the verification code Image Code in Python web,

Source: Internet
Author: User

Share the verification code Image Code in Python web,

System Version: CentOS 7.4
Python version: Python 3.6.1

In the current WEB, image Verification Code is one of the most common and simple solutions to prevent crawling programs from submitting forms.

1. Verification Code Image Generation

In python, the image verification code is generally implemented using the PIL or Pillow library. The following code generates the image verification code using Pillow:

#! /Usr/bin/env python3 #-*-coding: utf-8-*-# @ Author: Yang # @ Time: 2017/11/06 1: 04 import randomfrom PILimport Image, imageDraw, ImageFont, ImageFilter_letter_cases = "inherit" # lowercase letters, removing possible interference with I, l, o, z_upper_cases = _ letter_cases.upper () # uppercase letter _ numbers = ''. join (map (str, range (10) # Number init_chars = ''. join (_ letter_cases, _ upper_cases, _ numbers) def create_validate_code (size = (120, 30), chars = init_chars, img_type = "GIF", mode = "RGB ", bg_color = (230,230,230), fg_color = (18, 18, 18), font_size = 20, font_type = '/usr/share/fonts/dejavu/DejaVuSans-Bold. ttf', length = 4, draw_lines = True, n_line = (1, 2), draw_points = True, point_chance = 1): ''' @ todo: generate Verification Code image @ param size: size of the image, format (width, height), default value: (120, 30) @ param chars: allowed character set combination, Format String @ param img_type: the default format for saving images is GIF. The options are GIF, JPEG, TIFF, and PNG @ param mode. The default format is RGB @ param bg_color, the default value is white @ param fg_color: foreground color and Verification Code character color. The default value is blue # 0000FF @ param font_size: Verification Code font size @ param font_type: Detailed path of the Verification Code font, the default value is AE _AlArabiya.ttf @ param length: number of characters in the verification code @ param draw_lines: whether to draw interference lines @ param n_lines: The number range of interference lines. Format tuples. The default value is (1, 2 ), valid only when draw_lines is True @ param draw_points: whether to draw interference points @ param point_chance: the probability of occurrence of interference points. The value range is [0,100] @ return: [0]: PIL Image instance @ return: [1]: String '''width, height = size # width, height img = Image in the verification code Image. new (mode, size, bg_color) # create a graphic draw = ImageDraw. draw (img) # create a brush def get_chars (): ''' to generate a string of the given length, and return the List format ''' return random. sample (chars, length) def create_lines (): ''' draw interference line''' line _ num = random. randint (* n_line) # Number of interfering lines for I in range (line_num): # Starting Point begin = (random. randint (0, size [0]), random. randint (0, size [1]) # end Point end = (random. randint (0, size [0]), random. randint (0, size [1]) draw. line ([begin, end], fill = (0, 0, 0) def create_points (): '''plot interference point' ''chance = min (100, max (0, int (point_chance) # The size limit is [0,100] 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 (): ''' draw Verification Code character ''' c _ chars = get_chars () strs = '% s' % ''. join (c_chars) # separate each character with spaces. font = ImageFont. truetype (font_type, 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 () # graphic distortion parameter 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, 2)/500] img = img. transform (size, Image. PERSPECTIVE, params) # create distortion img = img. filter (ImageFilter. EDGE_ENHANCE_MORE) # filter, boundary enhancement (greater threshold) return img, strsif _ name _ = '_ main _': img, str = create_validate_code () img. save ('. /test.gif ', 'gif ')

The final result of   will return a tuples. The first return value is an Image instance, and the second return value is a string in the verification code Image, which can be used to check whether the verification code is correct.

Verification Code image:

The preceding Code depends on the system font. If font_type is set incorrectly, an OSError exception is thrown.

For CenOS systems, the font files are generally under/usr/share/fonts/dejavu/, such as CentOS 7.4:

Select one of them at will. In windows, you only need to set font_type to the correct font path, as shown in figure

font_type=r"C:\Windows\Fonts\Arial.ttf"

2. How to display the verification code on the webpage

In the preceding code, the verification codes are all saved as files. If you want to use the verification code on the web, it is impossible to create a verification code image every time. Save the image to the disk and then return it to the front-end web. This will increase the disk overhead, and frequently generated verification codes will also occupy a large amount of disk space. In this case, you can use the BytesIO module to directly read and write Verification Code images in the memory and return them to the front-end. At the same time, the correct verification code string is stored in the session. When the user submits a form, it can be compared with the correct string in the session.

Zookeeper uses Flask as an example. The following is a complete Demo of using the verification code in Flask:

#! /Usr/bin/env python3 #-*-coding: UTF-8-*-# @ Author: Yang # @ Time: import randomfrom PIL import Image, ImageDraw, ImageFont, imageFilterfrom io import BytesIOfrom flask import Flask, session, request_letter_cases = "bytes" # lowercase letters, remove potentially interfering I, l, o, z_upper_cases = _ letter_cases.upper () # capital letter _ numbers = ''. join (map (str, range (10) # Number init_chars = ''. join (_ letter_cas Es, _ upper_cases, _ numbers) def create_validate_code (size = (120, 30), chars = init_chars, img_type = "GIF", mode = "RGB ", bg_color = (230,230,230), fg_color = (18, 18, 18), font_size = 20, font_type = '/usr/share/fonts/dejavu/DejaVuSans-Bold.ttf', length = 4, draw_lines = True, n_line = (1, 2), draw_points = True, point_chance = 1): ''' @ todo: generate a verification code image @ param size: The image size, format (width, height), default: (120, 30) @ param chars: allowed character set combination, Format String @ Param img_type: Format of image storage. The default format is GIF. The options are GIF, JPEG, TIFF, and PNG @ param mode. The default format is RGB @ param bg_color, the default value is white @ param fg_color: foreground color and Verification Code character color. The default value is blue # 0000FF @ param font_size: Verification Code font size @ param font_type: Detailed path of the Verification Code font, the default value is AE _AlArabiya.ttf @ param length: number of characters in the verification code @ param draw_lines: whether to draw interference lines @ param n_lines: The number range of interference lines. Format tuples. The default value is (1, 2 ), valid only when draw_lines is True @ param draw_points: whether to draw interference points @ param point_chance: the probability of occurrence of interference points. The value range is [0, 1 00] @ return: [0]: PIL Image instance @ return: [1]: String '''width, height = size # width, height img = Image in the verification code Image. new (mode, size, bg_color) # create a graphic draw = ImageDraw. draw (img) # create a brush def get_chars (): ''' to generate a string of the given length, and return the List format ''' return random. sample (chars, length) def create_lines (): ''' draw interference line''' line_num = random. randint (* n_line) # Number of interfering lines for I in range (line_num): # Starting Point begin = (random. randint (0, size [0]), random. randin T (0, size [1]) # end Point end = (random. randint (0, size [0]), random. randint (0, size [1]) draw. line ([begin, end], fill = (0, 0, 0) def create_points (): '''plot interference point' ''chance = min (100, max (0, int (point_chance) # The size limit is [0,100] 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 (): ''' draw Verification Code character ''' c_chars = get_c Hars () strs = '% s' % ''. join (c_chars) # separate each character with spaces. font = ImageFont. truetype (font_type, 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 () # graphic distortion parameter 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, 2)/500] img = img. transform (size, Image. PERSPECTIVE, params) # create distortion img = img. filter (ImageFilter. EDGE_ENHANCE_MORE) # filter, boundary enhancement (greater threshold) return img, strsapp = Flask (_ name _) app. config. update (DEBUG = True, SECRET_KEY = '... ') @ app. route ('/') def index (): return 'test' @ app. route (' /Code') def get_code (): # send strs to the front end, or use session to save code_img, strs = create_validate_code () buf = BytesIO () code_img.save (buf, 'jpeg ') buf_str = buf. getvalue () response = app. make_response (buf_str) response. headers ['content-type'] = 'image/gif 'session ['img'] = strs. upper () return response@app.route ("/login", methods = ["POST", "GET"]) def login (): if request. method = 'post': if session. get ('img ') = = Request. form. get ('img '). upper (): return 'OK' return 'error' return "<form action =" "method =" post "> <p> Name: <input type = text name = username> <p> Password: <input type = text name = password> <p> CAPTCHA: <input type = text name = img>  # onclick event is used to obtain a new verification code each time you click <p> <input type = submit value = Login> </form>" "if _ name _ = = "_ main __": app. run (host = "0.0.0.0", port = 18888, debug = True)

Final effect:

Summary

The above is all about the implementation of verification code Image Code sharing in Python web. I hope it will be helpful to you. If you are interested, you can continue to refer to this site: python implements facial recognition code, Python crawler instances crawl funny jokes on the website, and Python getting started with trigonometric function full solution [favorites], etc, if you have any questions, you can leave a message at any time. The editor will reply to you in a timely manner. Thank you for your support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.