码迷,mamicode.com
首页 > 其他好文 > 详细

验证码图片生成pillow

时间:2018-11-16 13:26:09      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:port   dump   result   password   span   new   cli   use   log   

前端代码

div验证码框的样式

<div class="form-group">
                    <label for="pwd">验证码</label>
                    <div class="row">
                        <div class="col-md-6">
                            <input type="text" class="form-control" id="valid_code">
                        </div>
                        <div class="col-md-6">
                            <img width="270" height="36" id="valid_code_img" src="/get_validCode_img/" alt="">   //自动加载验证码视图函数
                        </div>
                    </div>
                </div>

验证码点击刷新事件

<script>
    $("#valid_code_img").click(function () {
        {#console.log($(this)[0]);#}

        $(this)[0].src += "?"

    });
</script>

验证码生成函数

def create_img(request):
    img = Image.new(RGB,(270,40),color=color_yeild())  # pillow 库PIL 生成图片 color为函数生成
    draw = ImageDraw.Draw(img)
    kumo_font = ImageFont.truetype(static/font/kumo.ttf,size=32)  # 字体设置
    check_digit = ‘‘
    for i in range(5):
        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,color_yeild(),kumo_font)
        check_digit += random_char
    # print(‘check_digit‘,check_digit)
    request.session["check"] = check_digit   #生成随机5位验证码并存入session中




    f = BytesIO()
    img.save(f, png)
    data = f.getvalue()


    # with open(‘wudi.png‘,‘wb‘) as f:
    #     img.save(f,‘png‘)
    # f = open(‘wudi.png‘,‘rb‘)
    # import json
    # data = json.dumps(img)
    return HttpResponse(data)
def color_yeild():  #生成随机的颜色(255,255,255)
    result = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
    return result

登录的时候校验验证码(d代码只有片段),通过ajax请求传入request的

valid_code = request.POST.get(valid_code, None)
print(valid_code,valid_code)
# print(‘request‘, request)
check_true = request.session.get("check")
print("check_true",check_true)
if valid_code.upper() == check_true.upper():   # 去除大小写
    print(1)
    user = auth.authenticate(username=user,password=pwd)   # 自动去djangouser表中校验
    if user:
       auth.login(request, user)  # 相当于设置session 设置session的值user 设置完成后request.user就是全局的变量了直接可以随意随时随地的使用request.user进行取值
       response[user] = user.username
    else:
        response[msg]=密码输入错误
else:
    response[msg]=验证码错误
return JsonResponse(response)

 

验证码图片生成pillow

标签:port   dump   result   password   span   new   cli   use   log   

原文地址:https://www.cnblogs.com/cjj-zyj/p/9968548.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!