This article is about the knowledge of implementing graphic verification code in the python web framework, Flask, for your reference. The following codes are described with their own project examples, with few related text content, mainly in the code Notes:
Self made graphic verification code
The graphic verification codes mentioned here are all self-made graphics drawn by the colors of canvas, brush and brush font. It's better to encapsulate the verification code into a class. There are absolutely detailed comments in the code. Of course, you can copy them directly.
The fonts involved are all brought by the system computer. You can copy the current directory directly.
home directory/utils/captcha/__init__.py import random import string # Image: a canvas # ImageDraw: a brush # ImageFont: the font of the brush from PIL import Image, ImageDraw, ImageFont # Captcha verification code class Captcha(object): # Generate 4-digit verification code numbers = 4 # Width and height of captcha image size = (100, 30) # Verification code font size fontsize = 25 # Number of interference lines added line_number = 2 # Build a verification code source text SOURCE = list(string.ascii_letters) for index in range(0, 10): SOURCE.append(str(index)) # Used to draw interference lines @classmethod def __gene_line(cls, draw, width, height): begin = (random.randint(0, width), random.randint(0, height)) end = (random.randint(0, width), random.randint(0, height)) draw.line([begin, end], fill=cls.__gene_random_color(), width=2) # Used to draw interference points @classmethod def __gene_points(cls, draw, point_chance, width, height): # The size limit is in [0100] 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=cls.__gene_random_color()) # Generate random colors @classmethod def __gene_random_color(cls, start=0, end=255): random.seed() return (random.randint(start, end), random.randint(start, end), random.randint(start, end)) # Randomly select a font @classmethod def __gene_random_font(cls): fonts = [ "PAPYRUS.TTF", "CENTAUR.TTF", "Inkfree.ttf", "verdana.ttf", ] font = random.choice(fonts) return "utils/captcha/"+font # Used to randomly generate a string (including English and numbers) @classmethod def gene_text(cls, numbers): # numbers is the number of digits to generate the verification code return " ".join(random.sample(cls.SOURCE, numbers)) # Generate verification code @classmethod def gene_graph_captcha(cls): # Width and height of captcha image width, height = cls.size # create picture image = Image.new("RGBA", (width, height), cls.__gene_random_color(0, 100)) # Verification code font font = ImageFont.truetype(cls.__gene_random_font(), cls.fontsize) # Create brush draw = ImageDraw.Draw(image) # Generate string text = cls.gene_text(cls.numbers) # Get font size font_width, font_height = font.getsize(text) # Fill string draw.text(((width-font_width)/2, (height-font_height)/2), text, font=font, fill=cls.__gene_random_color(150, 255)) # Draw interference line for x in range(0, cls.line_number): cls.__gene_line(draw, width, height) # Draw interference points cls.__gene_points(draw, 10, width, height) with open("captcha.png", "wb") as fp: image.save(fp) return text, image
Generally, the graphic verification code is in the form, so the data and suggestions in a short time are saved in the redis cache (the user clicks to refresh the graphic verification code dynamically). First, we draw the graphic verification code and save it to the project directory (the entry file is the main directory (project directory) app.py file, and the pictures are also saved to the main directory). Then we access the self-made graphic verification code (here I only add the main code) through the url address to display the graphic verification code.
home directory/common/views.py @bp.route("/captcha") def graph_captcha(): """ //Use the defined graphic verification code class to make the verification code //Take the verification code as the key and the verification code as the value (ignore the case for the user's experience) and store them in the redis cache. //Save and access pictures by BytesIO byte stream :return: Picture response """ # Get verification code text, image = Captcha.gene_graph_captcha() cpcache.set(text.lower(), text.lower()) # BytesIO: byte stream out = BytesIO() # Save pictures image.save(out, "png") # After storing the picture, point the file pointer to the file header, so that the next saved picture can overwrite the previously saved picture, saving space out.seek(0) # Access the image and return it to the foreground as a response resp = make_response(out.read()) resp.content_type = "image/png" return resp
The code of the front page is as follows:
<div class="form-group"> <div class="input-group"> <input type="text" class="form-control" name="graph_captcha" placeholder="Graphic verification code"> <span class="input-group-addon captcha-addon"> <img id="captcha-img" class="captcha-img" src="{{ url_for("common.graph_captcha") }}" alt=""> </span> </div> </div>
It's just to regenerate it into a graphic verification code, which can be accessed through url again, but it's very troublesome. It's hard for me to explain here (it's very difficult!!!) You can copy the code directly. This code is to click the image to generate a new url to access the image dynamic refresh verification code.
This file can be placed in a public directory var cpparam = { setParam: function(href, key, value){ //Reload entire page var isReplaced = false; var urlArray = href.split("?"); if(urlArray.length > 1){ var queryArray = urlArray[1].split("&"); for(var i=0; i < queryArray.length; i++){ var paramArray = queryArray[i].split("="); if(paramArray[0] == key){ paramArray[1] = value; queryArray[i] = paramArray.join("="); isReplaced = true; break; } } if(!isReplaced){ var params = {}; params[key] = value; if(urlArray.length > 1){ href = href + "$" + $.param(params); }else{ href = href + "?" + $.param(params); } }else{ var params = queryArray.join("&"); urlArray[1] = params; href = urlArray.join("?"); } }else{ var param = {}; param[key] = value; if(urlArray.length > 1){ href = href + "$" + $.param(param); }else{ href = href + "?" + $.param(param); } } return href; } };
The js file corresponding to html needs to implement the element (picture) Click to refresh the picture, call the above variable cpparam to generate a chapter of picture and access it.
$(function(){ $("#captcha-img").on("click", function(){ var self = $(this); var src = self.attr("src"); var newsrc = cpparam.setParam(src, "xx", Math.random()); self.attr("src", newsrc); }); });
The above is all the knowledge about the implementation of graphic verification code in the python web framework Flask. If you think the article is good, you can like it. If you have any suggestions or opinions, please share them in the comment area!