当前位置 博文首页 > Django中使用pillow实现登录验证码功能(带刷新验证码功能)

    Django中使用pillow实现登录验证码功能(带刷新验证码功能)

    作者:糖糖說 时间:2021-06-18 17:43

    首先在项目里建立common目录,编写验证码的函数

    verification_code.py

    import random
    
    from PIL import Image, ImageFont, ImageDraw
    
    
    def get_code():
        mode = 'RGB'
        bg_width = 180 #这个是验证码那个框框的宽度
        bg_height = 30 #这个是验证码那个框框的高度
        bg_size = (bg_width, bg_height)
        bg_color = (255, 255, 255)
        ttf_path = 'config/DejaVuSansMono.ttf'#这个是字体,从linux里扒出来饿字体
        # ttf_path = '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf' #这个要换你服务器里有的字体才行
        img = Image.new(mode, bg_size, bg_color)
        draw = ImageDraw.Draw(img, mode)
        font = ImageFont.truetype(ttf_path, 20)#这个俺也没懂
    
        # generate text
        letters = get_letters()
        for index, text in enumerate(letters):
            x = 35 * index + 10 #这个好像是调那个字符间距的
            y = 0
            draw.text((x, y), text, get_rdmcolor(), font)
    
        # blur the background
        for i in range(100): #这个是设置干扰线的,数值越大,干扰的越厉害
            x = random.randint(0, bg_width)
            y = random.randint(0, bg_height)
            fill = get_rdmcolor()
            draw.point((x, y), fill)
        return img, letters
    
    
    def get_letters(): #这个就是从下面这些字母里去随机4个出来
        base = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
        result = []
        for i in range(4): #这个是4位,应该改更多位,那么上面的参数还要调试,不然显示有问题
            result.append(random.choice(base))
        return result
    
    def get_rdmcolor():
        return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

    模板

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form method="POST" action="login/">
        <p>用户名:<input type="text" name="user"></p>
        <p>密码:<input type="text" name="pwd"></p>
        <label for="verification_code">验证码:</label><input type="text"  name="verification_code"
                                                          placeholder="Please type below code">
        <img class="identifyCode" title="点击重新获取" onclick="this.setAttribute('src','verification_code?random='+Math.random())" src="{% url 'verification_code' %}" alt="verification code">
        <br>
        <input type="submit" value="登录">
    </form>
    <script>
    </script>
    </body>
    </html>
    onclick="this.setAttribute('src','verification_code?random='+Math.random())"

    这个 onclick事件 就是实现点击图片刷新验证码功能 ,那为啥要加个随机数呢,这样就不会走浏览器缓存了

    urls.py

    from django.urls import path
    
    from test_login_app import views
    
    urlpatterns = [
        path('',views.index),
        path('verification_code/', views.verification_code, name='verification_code'),
        path('login/',views.login),
        path('index/',views.index2),
    ]

    views.py

    from io import BytesIO
    
    from django.http import HttpResponse
    from django.shortcuts import render, redirect
    
    from common.verification_code import get_code
    
    
    # Create your views here.
    
    def index(request):
        return render(request, 'login.html')
    
    
    def verification_code(request):
        img, letters = get_code()
        request.session['verification_code'] = ''.join(letters)
        fp = BytesIO()
        img.save(fp, 'png')
        return HttpResponse(fp.getvalue(), content_type='image/png')
    
    
    def login(request):#我这个没跟数据库联动,简单模拟的逻辑
        if request.method == 'POST':
            name = request.POST.get('user')
            password = request.POST.get('pwd')
            code = request.POST.get('verification_code')
            if name == 'fuck' and password == 'xxoo' and code == request.session.get('verification_code', ''):
                return redirect('/index/')
        return render(request,'login.html')
    
    
    def index2(request):
        return render(request,'index.html')

    成品如图

    在这里插入图片描述

    js