booktest26-驗證碼

1.增加視圖函數

def verify_code(request):
    import random
    bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)
    width = 100
    height = 25
    # 創建畫布
    im = Image.new('RGB', (width, height), bgcolor)
    # 創建畫筆
    draw = ImageDraw.Draw(im)
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill)
    str1 = 'ABCD234EFGHIJK456LMNOPQRS789TUVWXYZ0'
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    font = ImageFont.truetype('c:\\Windows\\Fonts\\SIMYOU.TTF',size=23)
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)

    del draw
    request.session['verifycode'] = rand_str
    buf = BytesIO()
    im.save(buf, 'png')
    return HttpResponse(buf.getvalue(), 'image/png')

2.修改login.html,添加驗證碼圖片和輸入框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陸頁面</title>
</head>
<body>
<form method="post" action="/login_check">
    {% csrf_token %}
    用戶名:<input type="text" name="username" value="{{username}}"/><br/>
    密碼:<input type="password" name="password"/><br/>
    <input type="checkbox" name="remember"/>記住用戶名<br/>
    <img src="/verify_code"><input type="text" name="vcode"><br/>
    <input type="submit" value="登陸">
</form>
</body>
</html>

3.修改login_check視圖函數,判斷驗證碼是否輸入正確

def login_check(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    remember = request.POST.get('remember')
    print(remember)
    #用戶輸入的驗證碼
    vcode1 = request.POST.get('vcode')
    #session裏面存的驗證碼
    vcode2 = request.session.get('verifycode')
    if vcode1 != vcode2:
        return redirect('/login')


    # print(username + ":" + password)
    if username == 'admin' and password == '111':
        response = redirect('/change_pwd')
        if remember == 'on':
            response.set_cookie('username', username, max_age=7 * 24 * 3600)
        # 只要有islogin,表示用戶已經登陸,值無所謂
        request.session['islogin'] = True
        request.session['username'] = username
        return response
    else:
        return redirect('/login')

4.測試效果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章