Python——验证码

utils/verify.py

#!/usr/bin/env python3
# coding=utf-8
# Version:python3.6.1
# Project:mysite
# File:verify.py
# Data:2020/12/24 11:58
# Author:LGSP_Harold
import os
import random
from io import BytesIO

from PIL import Image, ImageDraw, ImageFont
from django.http import HttpResponse

from mysite import settings


class VerifyCode:
    def __init__(self, dj_request):
        self.dj_request = dj_request
        # 设置验证码长度
        self.code_len = 6
        # 设置验证码图片尺寸
        self.img_width = 250
        self.img_height = 50

        # django中session的名称
        self.session_key = 'verify_code'

    def get_vcode(self):
        """ 生成验证码 """
        # 1、设定生成的字符范围
        random_str = 'QWERTYUPASDFGHJKLCVBNMqwertyuipasdfghjkcvbnm3456789'
        # 2、使用随机数生成验证码字符串
        code_list = random.sample(list(random_str), self.code_len)
        code = ''.join(code_list)
        return code

    def gen_code(self):
        # 1、获取随机生成的验证码
        code = self.get_vcode()
        # 2、把验证码存在session
        self.dj_request.session[self.session_key] = code
        # 3、准备随机元素(字体路径、验证码文字的颜色、背景颜色、干扰线)
        # 字体路径
        font_path = os.path.join(settings.STATICFILES_DIRS[0], 'fonts', 'timesbi.ttf')
        # 验证码文字的颜色
        font_color = ['black', 'brown', 'darkblue', 'darkred', 'green', 'darkmagenta', 'cyan', 'darkcyan']
        # RGB随机背景色
        bg_color = (
            random.randint(230, 255),
            random.randint(230, 255),
            random.randint(230, 255)
        )

        # 创建图片
        image = Image.new('RGB', (self.img_width, self.img_height), bg_color)
        draw = ImageDraw.Draw(image)

        # 验证码
        for index, char in enumerate(code):
            # 验证码颜色
            code_color = random.choice(font_color)
            # 验证码大小及字体
            code_size = random.randint(25, 30)
            code_font = ImageFont.truetype(font_path, code_size)
            # 验证码位置
            code_point = (index * int(self.img_width / self.code_len), random.randint(0, int(self.img_height / 3)))
            # 绘制验证码
            draw.text(code_point, char, code_color, code_font)

        # 干扰线
        for i in range(random.randint(2, 3)):
            line_color = random.choice(font_color)
            line_weight = random.randint(2, 3)
            line_point = (
                random.uniform(0, self.img_width * 0.2),
                random.randint(0, self.img_height),
                random.uniform(self.img_width - self.img_width * 0.2, self.img_width),
                random.randint(0, self.img_height)
            )
            draw.line(line_point, line_color, line_weight)

        # 干扰点
        for i in range(self.code_len * 20):
            dot_color = random.choice(font_color)
            dot_point = (
                random.randint(1, self.img_width),
                random.randint(1, self.img_height)
            )
            draw.point(dot_point, dot_color)

        buf = BytesIO()
        image.save(buf, 'gif')
        return HttpResponse(buf.getvalue(), 'image/gif')

    def validate_code(self, code):
        """ 验证验证码是否正确 """
        # 1、转变大小写
        code = str(code).lower()
        vcode = self.dj_request.session.get(self.session_key, '')

        return vcode.lower() == code

 

views.py

from utils.verify import VerifyCode


def verify_code(request):
    client = VerifyCode(request)
    return client.gen_code()

 

posted @ 2020-12-24 22:17  嘆世殘者——華帥  阅读(149)  评论(0编辑  收藏  举报