其他分享
首页 > 其他分享> > 1 随机生成验证码-组件

1 随机生成验证码-组件

作者:互联网

1组件代码展示:

from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import random


def get_random_color():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))


def get_valid_code_img(request):
    img = Image.new("RGB", (260, 32), color=get_random_color())  # 图片句柄

    draw = ImageDraw.Draw(img)  # 生成画笔
    font_obj = ImageFont.truetype('static/blog/font/aigei_com.ttf', size=20)  # 字体样式的路径

    valid_code_str = ''
    for i in range(1):  # 获取1个字符的验证码
        random_num = str(random.randint(0, 9))  # 生成随机数字
        random_low_alpha = chr(random.randint(95, 122))  # 生成随机小写字母
        random_upper_alpha = chr(random.randint(65, 90))  # 生成随机大写字母
        random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])

        draw.text((i * 50+20, 5), random_char, get_random_color(), font=font_obj)  # 写文件
        # 保存验证码字符串
        valid_code_str += random_char

    # width, height = 260, 40  # 设置图片的宽高
    # for i in range(10):  # 造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(10):  # 造10个点
    #     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())

    request.session["valid_code_str"] = valid_code_str  # 将验证码存入用户session中
    '''
    session过程:
    1.生成一个随机的字符串 "asdfasdfsfsd"
    2.COOKIE  {'session_id': asdfasdfsfsd}
    3.在django-session表中生成
        session-key    session-data
        asdfasdfsfsd   {"valid_code_str": "xxxx"}
    '''

    f = BytesIO()  # 内存句柄(使用完就会清除掉)
    img.save(f, 'png')
    data = f.getvalue()

    return data

2 组件代码调用:

from django.shortcuts import HttpResponse
from utils.validCode import get_valid_code_img

def get_validCode_img(request):
    data = get_valid_code_img(request)
    return HttpResponse(data)

3 组件效果展示:

image

标签:session,code,get,random,验证码,valid,randint,组件,随机
来源: https://www.cnblogs.com/it-lkp/p/16580623.html