Django框架之驗證碼生成示例
阿新 • • 發佈:2018-10-04
console 函數 with sta fse == urn str ucc
一、生成隨機顏色的圖片
1)前端代碼展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.min.css"> <script src="/static/jquery-3.1.1.js"></script> <title>登錄頁面</title> </head> <body> <div classlogin.html="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>登錄</h1> <form> <div class="form-group"> <label for="">用戶名</label> <input type="text" id="id_name" class="form-control"> </div> <div class="form-group"> <label for="">密碼</label> <input type="password" id="id_pwd" class="form-control"> </div> <div class="form-group"> <label for="">驗證碼</label> <div class="row"> <div class="col-lg-6"> <input type="text" id="code" class="form-control"> </div> <div class="col-lg-6"> <img height="35" width="250" src="/get_code/" alt=""> </div> </div> </div> <input type="button" value="登錄" class="btn btn-danger"> </form> </div> </div> </div> </body> </html>
提交方式,基於ajax提交
2)生成隨機顏色的圖片
def get_random_color(): ‘‘‘生成隨機顏色的圖片‘‘‘ import random return (random.randint(0,255),random.randint(0,255),random.randint(0,255))get_random_color
3)驗證碼函數,寫入圖片,讀取圖片返回給前端
def get_code(request): from PIL import Image img = Image.new(‘RGB‘,(35,250),color=get_random_color()) with open(‘code.png‘,‘wb‘) as f: # 造成隨機顏色的圖片 img.save(f) with open(‘code.png‘,‘rb‘) as f: # 讀取圖片,給前端 data=f.read() return HttpResponse(data)get_code
二、在隨機驗證碼圖片內寫入文字.(重點)
隨機生成的驗證碼圖片,保存於內存。圖片內的文字保存於session(用於登錄驗證)
def get_code(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.ttf 文字樣式,網上下載ttf 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)) # 隨機一個數字 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]) # 從上面的3個選擇一個出來 draw.text((i * 50 + 20, 5), random_char, get_random_color(), font=kumo_font) # (i * 50 + 20, 5) 寫字母的時候便宜 # 保存驗證碼字符串 valid_code_str += random_char print("valid_code_str", valid_code_str) f = BytesIO() # 生成一個對象,保存於內存 img.save(f, "png") # 驗證碼圖片保存於內存 data = f.getvalue() request.session[‘code‘]=valid_code_str # 驗證碼保存於session中 return HttpResponse(data)get_code
三、加入ajax請求登錄
1)url視圖函數
from django.conf.urls import url from django.contrib import admin from mybbs import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^login/‘, views.login), url(r‘^get_code/‘, views.get_code), ]url.py
2)login頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.min.css"> <script src="/static/jquery-3.1.1.js"></script> <title>登錄頁面</title> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>登錄</h1> <form> {% csrf_token %} <div class="form-group"> <label for="">用戶名</label> <input type="text" id="id_name" class="form-control"> </div> <div class="form-group"> <label for="">密碼</label> <input type="password" id="id_pwd" class="form-control"> </div> <div class="form-group"> <label for="">驗證碼</label> <div class="row"> <div class="col-lg-6"> <input type="text" id="code" class="form-control"> </div> <div class="col-lg-6"> <img height="35" width="250" src="/get_code/" alt=""> </div> </div> </div> <input type="button" id="submit" value="登錄" class="btn btn-danger"> </form> </div> </div> </div> <script> $("#submit").click(function () { $.ajax({ url: ‘/login/‘, type: ‘post‘, data: { ‘name‘: $("#id_name").val(), ‘pwd‘: $("#id_pwd").val(), ‘code‘: $("#code").val(), ‘csrfmiddlewaretoken‘: ‘{{csrf_token}}‘ }, success: function (data) { console.log(data) } }) }) </script> </body> </html>login.html
3)驗證碼相關函數
def get_random_color(): ‘‘‘生成隨機顏色的圖片‘‘‘ import random return (random.randint(0,255),random.randint(0,255),random.randint(0,255)) def get_code(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.ttf 文字樣式,網上下載ttf 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)) # 隨機一個數字 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]) # 從上面的3個選擇一個出來 draw.text((i * 50 + 20, 5), random_char, get_random_color(), font=kumo_font) # (i * 50 + 20, 5) 寫字母的時候便宜 # 保存驗證碼字符串 valid_code_str += random_char print("valid_code_str", valid_code_str) f = BytesIO() # 生成一個對象,保存於內存 img.save(f, "png") # 驗證碼圖片保存於內存 data = f.getvalue() request.session[‘code‘]=valid_code_str # 驗證碼保存於session中 return HttpResponse(data)驗證碼相關請求函數
4)login函數請求(判斷ajax)
from django.contrib import auth def login(request): if request.is_ajax(): name=request.POST.get(‘name‘) pwd=request.POST.get(‘pwd‘) code=request.POST.get(‘code‘) if code.upper()== request.session[‘code‘].upper(): user=auth.authenticate(request,username=name,password=pwd) if user: return HttpResponse(‘ok‘) else: return HttpResponse(‘用戶名或密碼錯誤‘) else: return HttpResponse(‘驗證碼錯誤‘) return render(request,‘login.html‘)Views.login
Django框架之驗證碼生成示例