运维开发网

django项目登录中使用图片验证码

运维开发网 https://www.qedev.com 2020-06-17 18:31 出处:网络 作者:运维开发网整理
应用下创建untils文件夹放置封装图片验证码的函数 创建validCode.py文件定义验证码规则

应用下创建untils文件夹放置封装图片验证码的函数

创建validCode.py文件定义验证码规则

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):
    # 方式:

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

    img = Image.new("RGB", (270, 40), color=get_random_color())#生成一个宽270*高40的画布,背景颜色随机

    draw = ImageDraw.Draw(img)#进行绘画
    kumo_font = ImageFont.truetype("static/font/kumo.ttf", size=32)#字体  字体大小

    valid_code_str = ""

    for i in range(5):
        random_num = str(random.randint(0, 9))#0-9的随机数  9
        random_low_alpha = chr(random.randint(97, 122))#a 到 z 随机的一个小写字母  b
        random_upper_alpha = chr(random.randint(65, 90))#A 到 Z 随机的一个大写字母  Q
        random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])        #2
        draw.text((i * 50 + 20, 5), random_char, get_random_color(), font=kumo_font) #往长方形上写字


        # 保存验证码字符串
        valid_code_str += random_char #85656
    width=270
    height=40
    for i in range(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


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


    return data

建路由

# 登录
path(‘login/‘, login.login,name=‘login‘),
# 图片验证码
re_path(‘get_valid_code_img/‘, login.get_valid_code_img, name=‘get_valid_code_img‘),

写后台方法

from blog.utils import validCode  # 引入自定义的验证码
#页面返回方法
from django.shortcuts import render, HttpResponse, redirect
#哈希加密
from django.contrib.auth.hashers import make_password, check_password
#数据库
from blog.models import Article, Comment, Member, Praise, Web, Image
# 登陆
def login(request):
    res = {‘status‘: None, ‘info‘: None}

    if request.method == ‘POST‘:
        valid_code = request.POST.get("valid_code")
        valid_code_str = request.session.get("valid_code_str")
        print(valid_code, valid_code_str)
        if valid_code.upper() == valid_code_str.upper():
            # 查询用户和密码是否正确
            username = request.POST.get(‘username‘)
            pwd = request.POST.get(‘pwd‘)
            username_obj = Member.objects.filter(member_name=username).first()
            if not username_obj:
                res[‘status‘] = 3
                res[‘info‘] = ‘用户名不存在‘
                return HttpResponse(json.dumps(res))
            if check_password(pwd, username_obj.member_pwd):
                res[‘status‘] = 1
                res[‘info‘] = ‘登录成功‘
                request.session[‘member_name‘] = username
                request.session[‘member_id‘] = Member.objects.filter(member_name=username).first().member_id
                response_new = HttpResponse(json.dumps(res))  # 把这个结果告诉给前台,ajax
                return response_new
            else:
                res[‘status‘] = 0
                res[‘info‘] = ‘帐号/密码错误‘
                return HttpResponse(json.dumps(res))
        else:
            res[‘status‘] = 2
            res[‘info‘] = ‘验证码错误‘
            return HttpResponse(json.dumps(res))
    return render(request, ‘blog/login.html‘, locals())
    
    # 生成图片验证码
def get_valid_code_img(request):
    img_data = validCode.get_valid_code_img(request)
    return HttpResponse(img_data)

前端登录的表单

{#登陆的表单#}

<form action="{% url ‘blog:login‘ %}" method="post" id="login">
    <input type="text" class="name" name="username" Placeholder="Username" required=""/>
    <input type="password" class="password" name="pwd" Placeholder="Password" required=""/>
    {% csrf_token %}
    <input type="text" name="valid_code" placeholder="验证码">
    <img width="270" height="36" id="valid_code_img" src="/blog/get_valid_code_img/" alt=""
         onclick="this.src=‘/blog/get_valid_code_img/?‘+Math.random()">
    <div class="login-agileits-bottom">
        <h6><a href="javascript:;" type="button" id="onsubmit">登陆</a></h6>
    </div>
</form>

{#登陆的表单结束#}

前端提交登录表单的jquery

{#  登陆的jquery  #}
$(document).ready(function () {
    $(‘#onsubmit‘).click(function () {
        $.post(‘/blog/login/‘, $(‘#login‘).serialize(), function (data) {
            if (data[‘status‘] == 1) {
                layer.msg(data.info);
                location.href = "{% url ‘index‘ %}";
            } else {
                layer.msg(data[‘info‘])
            }
        }, ‘json‘)
    })
})
{#  登陆的jquery结束  #}

页面效果

django项目登录中使用图片验证码

done。

0

精彩评论

暂无评论...
验证码 换一张
取 消