【Django】Python 實現登入驗證碼
阿新 • • 發佈:2018-12-22
1 安裝 pillow 包,用於生成驗證碼圖片
程式碼檔案
verification.py
#!/usr/bin/python # -*- coding: utf-8 -*- import random from PIL import Image, ImageDraw, ImageFont, ImageFilter class VerificationCode: # 生成幾位數的驗證碼 number = 4 # 生成驗證碼圖片的寬高 size = (102, 34) # 背景顏色,預設為白色 bg_color = (255, 255, 255) # 字型顏色,預設為藍色 font_color = (0, 0, 255) # 干擾線顏色。預設為紅色 line_color = (255, 0, 0) # 干擾點顏色。預設為藍色 point_color = (0, 0, 255) # 加入干擾線條數 line_number = 3 # 干擾點的個數 point_number = 30 # 用來隨機生成一個字串 def gene_text(self): letters = "23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" # 元字元 return ''.join(random.sample(list(letters), self.number)) # 生成位數為number的驗證碼 # 用來繪製干擾線 def gene_line(self, draw, width, height): for i in range(self.line_number): begin = (random.randint(0, width), random.randint(0, height)) end = (random.randint(0, width), random.randint(0, height)) draw.line([begin, end], fill=self.line_color) # 增加干擾點 def gene_point(self, draw, width, height): point_list = [] for i in range(self.point_number): point = (random.randint(0, width), random.randint(0, height)) point_list.append(point) draw.point(point_list, fill=self.point_color) # 生成驗證碼 def gene_code(self): width, height = self.size # 圖片寬高 image = Image.new('RGBA', self.size, self.bg_color) # 建立圖片 font = ImageFont.truetype('arial', 25) # 驗證碼的字型 draw = ImageDraw.Draw(image) # 建立畫筆 text = self.gene_text() # 生成字串 font_width, font_height = font.getsize(text) # 驗證碼佔寬高 draw.text(((width - font_width) / self.number + 5, (height - font_height) / self.number), text, font=font, fill=self.font_color) # 填充字串 self.gene_line(draw, width, height) # 增加干擾線 self.gene_point(draw, width, height) # 增加干擾點 image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) # 濾鏡,邊界加強 # image.save('idencode.png') # 儲存驗證碼圖片 return text, image # 呼叫一下試試 # VerificationCode().gene_code()
html
<img class="value" src="/index/verification_code/" onclick="ChangeCode(this);"/>
js
function ChangeCode(ths) {
var src_re = $(ths).attr('src');
$(ths).attr('src', src_re + '?');
}
urls 中配置
urlpatterns = [ path('admin/', admin.site.urls), # ... url(r'^index/verification_code/$', views.verification_code), ]
views 中的使用
def verification_code(request): text, img = verification.VerificationCode().gene_code() # 存session 參考:http://www.cnblogs.com/liuye1990/p/9663474.html request.session['verification_code'] = text # img.show() # 顯示一下效果 stream = io.BytesIO() # 建立一個io物件 img.save(stream, "png") # 將圖片物件im儲存到stream物件裡 # stream.getvalue() 圖片二級制內容,再通過HttpResponse封裝,返回給前端頁面 return HttpResponse(stream.getvalue())