本篇文章给大家整理的是关于python web框架Flask实现图形验证码的相关知识点,有需要的朋友们参考下。下列代码都是以自己的项目实例讲述的,相关的文本内容很少,主要说明全在代码注释中:
自制图形验证码
这里所说的图形验证码都是自制的图形,通过画布、画笔、画笔字体的颜色绘制而成的。将验证码封装成一个类比较好管理,代码里有绝对详细的注释,当然大家可以直接复制。
里面涉及的字体都是从系统电脑上自带的,大家直接复制当前目录下就可以了。
主目录/utils/captcha/__init__.py import randomimport string # Image:一个画布# ImageDraw:一个画笔# ImageFont:画笔的字体from PIL import Image, ImageDraw, ImageFont # Captcha验证码class Captcha(object): # 生成4位数的验证码 numbers = 4 # 验证码图片的宽度和高度 size = (100, 30) # 验证码字体大小 fontsize = 25 # 加入干扰线的条数 line_number = 2 # 构建一个验证码源文本 SOURCE = list(string.ascii_letters) for index in range(0, 10): SOURCE.append(str(index)) # 用来绘制干扰线 @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) # 用来绘制干扰点 @classmethod def __gene_points(cls, draw, point_chance, width, height): # 大小限在【0, 100】中 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()) # 生成随机颜色 @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)) # 随机选择一个字体 @classmethod def __gene_random_font(cls): fonts = [ "PAPYRUS.TTF