flask實現驗證碼並驗證

 

效果圖:

點擊圖片、刷新頁面、輸入錯誤點擊登錄時都刷新驗證碼

 

 

 

 

實現步驟:

 

第一步:先定義獲取驗證碼的接口

verificationCode.py

1 #驗證碼
2 @api.route('/imgCode')
3 def imgCode():
4     return imageCode().getImgCode()

此處的@api是在app下注冊的藍圖,專門用來做後臺接口,所以註冊了api藍圖

 

 

 

第二步:實現接口邏輯

 

1)首先實現驗證碼肯定要隨機生成,所以我們需要用到random庫,本次需要隨機生成字母和數字,

所以我們還需要用到string。string的ascii_letters是生成所有字母 digits是生成所有數字0-9。具體代碼如下

1 def geneText():
2     '''生成4位驗證碼'''
3     return ''.join(random.sample(string.ascii_letters + string.digits, 4)) #ascii_letters是生成所有字母 digits是生成所有數字0-9

  2)爲了美觀,我們需要給每個隨機字符設置不同的顏色。我們這裏用一個隨機數來給字符設置顏色

1 def rndColor():
2     '''隨機顏色'''
3     return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

  3)此時我們已經可以生產圖片驗證碼了,利用上面的隨機數字和隨機顏色生成一個驗證碼圖片。

  這裏我們需要用到PIL庫,此時注意,python3安裝這個庫的時候不是pip install PIL 而是pip install pillow。

 1 def getVerifyCode():
 2     '''生成驗證碼圖形'''
 3     code = geneText()
 4     # 圖片大小120×50
 5     width, height = 120, 50
 6     # 新圖片對象
 7     im = Image.new('RGB', (width, height), 'white')
 8     # 字體
 9     font = ImageFont.truetype('app/static/arial.ttf', 40)
10     # draw對象
11     draw = ImageDraw.Draw(im)
12     # 繪製字符串
13     for item in range(4):
14         draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
15                   text=code[item], fill=rndColor(), font=font)
16     return im, code

  4)此時,驗證碼圖片已經生成。然後需要做的就是把圖片發送到前端去展示。

 1 def getImgCode():
 2     image, code = getVerifyCode()
 3     # 圖片以二進制形式寫入
 4     buf = BytesIO()
 5     image.save(buf, 'jpeg')
 6     buf_str = buf.getvalue()
 7     # 把buf_str作爲response返回前端,並設置首部字段
 8     response = make_response(buf_str)
 9     response.headers['Content-Type'] = 'image/gif'
10     # 將驗證碼字符串儲存在session中
11     session['imageCode'] = code
12     return response

  這裏我們採用講圖片轉換成二進制的形式,講圖片傳送到前端,並且在這個返回值的頭部,需要標明這是一個圖片。

  將驗證碼字符串儲存在session中,是爲了一會在登錄的時候,進行驗證碼驗證。

  5)OK,此時我們的接口邏輯已經基本完成。然後我們還可以給圖片增加以下干擾元素,比如增加一點橫線。

1 def drawLines(draw, num, width, height):
2     '''劃線'''
3     for num in range(num):
4         x1 = random.randint(0, width / 2)
5         y1 = random.randint(0, height / 2)
6         x2 = random.randint(0, width)
7         y2 = random.randint(height / 2, height)
8         draw.line(((x1, y1), (x2, y2)), fill='black', width=1)

  然後getVerifyCode函數需要新增一步

 1 def getVerifyCode():
 2     '''生成驗證碼圖形'''
 3     code = geneText()
 4     # 圖片大小120×50
 5     width, height = 120, 50
 6     # 新圖片對象
 7     im = Image.new('RGB', (width, height), 'white')
 8     # 字體
 9     font = ImageFont.truetype('app/static/arial.ttf', 40)
10     # draw對象
11     draw = ImageDraw.Draw(im)
12     # 繪製字符串
13     for item in range(4):
14         draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
15                   text=code[item], fill=rndColor(), font=font)
16     # 劃線
17     drawLines(draw, 2, width, height)
18     return im, code

  最終接口邏輯完成。整體接口代碼如下

 1 from .. import *
 2 from io import BytesIO
 3 import random
 4 import string
 5 from PIL import Image, ImageFont, ImageDraw, ImageFilter
 6 
 7 #驗證碼
 8 @api.route('/imgCode')
 9 def imgCode():
10     return imageCode().getImgCode()
11 
12 
13 class imageCode():
14     '''
15     驗證碼處理
16     '''
17     def rndColor(self):
18         '''隨機顏色'''
19         return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
20 
21     def geneText(self):
22         '''生成4位驗證碼'''
23         return ''.join(random.sample(string.ascii_letters + string.digits, 4)) #ascii_letters是生成所有字母 digits是生成所有數字0-9
24 
25     def drawLines(self, draw, num, width, height):
26         '''劃線'''
27         for num in range(num):
28             x1 = random.randint(0, width / 2)
29             y1 = random.randint(0, height / 2)
30             x2 = random.randint(0, width)
31             y2 = random.randint(height / 2, height)
32             draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
33 
34     def getVerifyCode(self):
35         '''生成驗證碼圖形'''
36         code = self.geneText()
37         # 圖片大小120×50
38         width, height = 120, 50
39         # 新圖片對象
40         im = Image.new('RGB', (width, height), 'white')
41         # 字體
42         font = ImageFont.truetype('app/static/arial.ttf', 40)
43         # draw對象
44         draw = ImageDraw.Draw(im)
45         # 繪製字符串
46         for item in range(4):
47             draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
48                       text=code[item], fill=self.rndColor(), font=font)
49         # 劃線
50         self.drawLines(draw, 2, width, height)
51         return im, code
52 
53     def getImgCode(self):
54         image, code = self.getVerifyCode()
55         # 圖片以二進制形式寫入
56         buf = BytesIO()
57         image.save(buf, 'jpeg')
58         buf_str = buf.getvalue()
59         # 把buf_str作爲response返回前端,並設置首部字段
60         response = make_response(buf_str)
61         response.headers['Content-Type'] = 'image/gif'
62         # 將驗證碼字符串儲存在session中
63         session['imageCode'] = code
64         return response

 

第三步:前端展示。

這裏前端我使用的是layui框架。其他框架類似。

1 <div class="layui-form-item">
2     <label class="layui-icon layui-icon-vercode" for="captcha"></label>
3     <input type="text" name="captcha" lay-verify="required|captcha" placeholder="圖形驗證碼" autocomplete="off"
4            class="layui-input verification captcha" value="">
5     <div class="captcha-img">
6         <img id="verify_code" class="verify_code" src="/api/imgCode" onclick="this.src='/api/imgCode?'+ Math.random()">
7     </div>
8 </div>

js:主要是針對驗證失敗以後,刷新圖片驗證碼

 1             // 進行登錄操作
 2             form.on('submit(login)', function (data) {
 3                 console.log(data.elem);
 4                 var form_data = data.field;
 5                 //加密成md5
 6                 form_data.password=$.md5(form_data.password);
 7                 $.ajax({
 8                     url: "{{ url_for('api.api_login') }}",
 9                     data: form_data,
10                     dataType: 'json',
11                     type: 'post',
12                     success: function (data) {
13                         if (data['code'] == 0) {
14                             location.href = "{{ url_for('home.homes') }}";
15                         } else {
16                             //登錄失敗則刷新圖片驗證碼
17                             var tagImg = document.getElementById('verify_code');
18                             tagImg.src='/api/imgCode?'+ Math.random();
19                             console.log(data['msg']);
20                             layer.msg(data['msg']);
21                         }
22                     }
23                 });
24                 return false;
25             });

 

 

第四步:驗證碼驗證

驗證碼驗證需要在點擊登錄按鈕以後,在對驗證碼進行效驗

1)首先我們獲取到前端傳過來的驗證碼。.lower()是爲了忽略大小寫

這裏的具體寫法爲什麼這樣寫可以獲取到前端傳過來的參數,可以自行了解flask框架

1 if request.method == 'POST':
2     username = request.form.get('username')
3     password = request.form.get('password')
4     captcha = request.form.get('captcha').lower()

  2)對驗證碼進行驗證.因爲我們在生成驗證碼的時候,就已經把驗證碼保存到session中,這裏直接取當時生成的驗證碼,然後跟前端傳過來的值對比即可。

1 if captcha==session['imageCode'].lower():
2     pass
3 else4     return jsonify({'code':-1,'msg':'圖片驗證碼錯誤'})

 

到此,已完成了獲取驗證碼、顯示驗證碼、驗證驗證碼的所有流程。驗證驗證碼中沒有把整體代碼寫出來。可以根據自己情況自己寫。

 

注:轉載請註明出處。謝謝合作~

 

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