登录验证码的实现

验证码的实现:

1.验证码生成

#验证码的实现
from PIL import Image,ImageDraw,ImageFont
import random
from io import BytesIO,StringIO

#获取随机的样式颜色
def get_random():
    return random.randint(0,255),random.randint(0,255),random.randint(0,255)

def get_code(request):
    img_obj = Image.new('RGB', (360, 35), get_random())  #生成图片对象
    img_draw = ImageDraw.Draw(img_obj)  # 生成了一个画笔对象
    img_font = ImageFont.truetype('static/font/111.ttf', 30)  # 字体样式
    #随机码的获取:
    code = ''
    for i in range(5):
        upper_str = chr(random.randint(65, 90))  #ascii码 大写字母
        lower_str = chr(random.randint(97, 122)) #ascii码 小写字母
        random_int = str(random.randint(0, 9))
        tmp = random.choice([upper_str, lower_str, random_int]) #随机取值
        
        img_draw.text((i * 60 + 60, 0), tmp, get_random(), img_font)  # 文字展示到图片上
        code += tmp  #一次结果
    print(code)
    request.session['code'] = code  #存储
    io_obj = BytesIO()   #内存内存储,读取
    img_obj.save(io_obj, 'png')  # 保存,并选定格式
    return HttpResponse(io_obj.getvalue())   #返回图片的二进制的数据

2.页面展示:


#页面展示:login.html
 <div class="form-group">
                <label for="id_code">验证码</label>
                <div class="row">
                    <div class="col-md-6">
                        <input type="text" name="code" id="id_code" class="form-control">
                    </div>
                    <div class="col-md-6">
                        <img src="/get_code/" alt="" width="360" height="35" id="id_img">
                    </div>
                </div>
            </div

<script>
    $('#id_img').click(function () {
        var oldPath = $(this).attr('src');
        $(this).attr('src',oldPath+='?')   //绑定img属性,自动像后端请求数据
    })
    $('#id_submit').click(function () {
        $.ajax({
            url:'',
            type:'post',
            data:{
                'username':$('#id_username').val(),
                'password':$('#id_password').val(),
                'code':$('#id_code').val(),
                'csrfmiddlewaretoken':'{{ csrf_token }}'  //发送ajax请求
            },
            success:function (data) {
                if (data.code== 1000) {
                    window.location.href=data.url
                }else{
                    $('#id_error').text(data.msg)
                    //自动刷新验证码
                    var oldPath = $('#id_img').attr('src');
                    $('#id_img').attr('src',oldPath+='?')
                }

            }
        })

    })
</script>

3.内置模块的参数

io内存管理器模块: 
BytesIO  保存数据 并且在获取的时候 是以二进制的方式给你
StringIO  保存数据 并且在获取的时候 是以字符串的方式给你

from PIL import Image,ImageDraw,ImageFont
Image       生成图片
ImageDraw   在图片上写字
ImageFont   控制字的字体样式

框架下载方式: pip3 install baidu-aip -i https://pypi.douban.com/simple/
原文地址:https://www.cnblogs.com/shaozheng/p/12013706.html