django登入驗證碼操作
阿新 • • 發佈:2018-11-06
import random from PIL import Image, ImageDraw, ImageFont def v_code(request): def random_color(): return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) # 建立一個隨機顏色的圖片物件 img_obj =Image.new('RGB',(250,30),random_color()) # 例項化一個畫筆物件 pen_obj =ImageDraw.Draw(img_obj) # 載入字型物件 font_obj =ImageFont.truetype('static/font/kumo.ttf',28) tmp = [] for i in range(5): l = chr(random.randint(97, 122)) # 生成隨機的小寫字母 u = chr(random.randint(65, 90)) # 生成隨機的大寫字母 n = str(random.randint(0, 9)) # 生成一個隨機的數字 # 從上面三個隨機選一個 r = random.choice([l, u, n]) pen_obj.text((40*i+30,0),r,fill=random_color(),font=font_obj) tmp.append(r) # # 加干擾線 # width = 250 # 圖片寬度(防止越界) # height = 35 # for i in range(5): # x1 = random.randint(0, width) # x2 = random.randint(0, width) # y1 = random.randint(0, height) # y2 = random.randint(0, height) # pen_obj.line((x1, y1, x2, y2), fill=random_color()) # # # 加干擾點 # for i in range(40): # draw_obj.point([random.randint(0, width), random.randint(0, height)], fill=random_color()) # x = random.randint(0, width) # y = random.randint(0, height) # pen_obj.arc((x, y, x+4, y+4), 0, 90, fill=random_color()) v_code=''.join(tmp).upper() request.session['v_code']= v_code # with open("static/imgs/vcode.png", "wb") as f1: # img_obj.save(f1, format="PNG") # # with open("static/images/vcode.png", "rb") as f: # img_data = f.read() # 直接在記憶體中儲存圖片替代io操作 from io import BytesIO f1 =BytesIO() img_obj.save(f1, format="PNG") img_data = f1.getvalue() return HttpResponse(img_data, content_type="image/png")
在檢視函式中定義此方法,在路由中新增次檢視函式的呼叫
url(r'^v_code/', views.v_code,name='v_code'),
在模板中新增登入控制元件
<div class="login-center clearfix"> <div class="login-center-img"><img src="{% static 'imgs/password.png' %}"></div> <div class="login-center-input"> <input type="text" name="v_code" value="" placeholder="請輸入驗證碼" onfocus="this.placeholder=''" onblur="this.placeholder='請輸入您的驗證碼'"> <div class="login-center-input-text">驗證碼</div> </div> </div>
新增驗證碼的更換
<script> img = document.getElementById('v_code'); img.onclick = function () { img.src += '?' } </script>
最重要的一點:此路由不能通過中介軟體的檢驗,因此,將此路由新增至白名單
最後完成django的登入驗證碼功能的新增