验证码的模版

###################图书管理系统验证码逻辑################
from PIL import Image,ImageDraw,ImageFont    #python中自带的验证码生成模块
import random    #为产生随机字母和数字做准备
from io import BytesIO  #为验证码做噪点和噪线
def get_valid_img(request):
    #产生随机的颜色框来放置验证码
    def get_random_color():
        import random
        return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    img = Image.new("RGB", (350, 38), get_random_color())
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("static/font/kumo.ttf", 32)

    keep_str = ""
    for i in range(6):
        random_num = str(random.randint(0, 9))
        random_lowalf = chr(random.randint(97, 122))
        random_upperalf = chr(random.randint(65, 90))
        random_char = random.choice([random_num, random_lowalf, random_upperalf])
        draw.text((i * 30 + 50, 0), random_char, get_random_color(), font=font)
        keep_str += random_char

    #加噪点和躁线防止机器攻击
    width = 350        #参数一定要与前面的随机框保持一致
    height=38
    for i in range(10):          #参数越大越识别
        x1 = random.randint(0, width)
        x2 = random.randint(0, width)
        y1 = random.randint(0, height)
        y2 = random.randint(0, height)
        draw.line((x1, y1, x2, y2), fill=get_random_color())

    for i in range(50):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())

    # 写与读
    f = BytesIO()
    img.save(f, "png")
    data = f.getvalue()

    print('keep_str', keep_str)

    # 将验证码存在各自的session中

    request.session['keep_str'] = keep_str

    return HttpResponse(data)

 

posted @ 2018-11-06 15:27  RootEvils  阅读(97)  评论(0)    收藏  举报