基于Python+Flask實現一個簡易網頁驗證碼登錄系統案例
在當今的互聯網世界中,為了防止惡意訪問,許多網站在登錄和注冊表單中都采用了驗證碼技術。驗證碼可以防止機器人自動提交表單,確保提交行為背后有一個真實的人類用戶。 本文將向您展示如何使用Python的Flask框架來創建一個簡單的驗證碼登錄系統。
1. 開始之前
首先,確保你已經安裝了以下所需的庫:
pip install flask Pillow
- Flask: 一個輕量級的Web服務器和框架。
- Pillow: 處理圖像操作,用于生成驗證碼圖像。
2. 生成驗證碼圖像
我們使用Pillow庫來生成驗證碼圖像。除了顯示數字和字母,為了增加安全性,我們還會在圖像上添加一些干擾線條和噪點。
from PIL import Image, ImageDraw, ImageFont
import random
import string
def generate_captcha_image():
# 定義圖片大小及背景顏色
image = Image.new('RGB', (120, 30), color=(73, 109, 137))
# 使用系統自帶字體,或指定字體文件路徑
font_path = "./arial.ttf"
fnt = ImageFont.truetype(font_path, 15)
d = ImageDraw.Draw(image)
# 生成5位數的驗證碼文本
captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
d.text((10, 10), captcha_text, font=fnt, fill=(255, 255, 0))
# 添加干擾線條和噪點
for _ in range(random.randint(3, 5)):
start = (random.randint(0, image.width), random.randint(0, image.height))
end = (random.randint(0, image.width), random.randint(0, image.height))
d.line([start, end], fill=(random.randint(50, 200), random.randint(50, 200), random.randint(50, 200)))
for _ in range(100):
xy = (random.randrange(0, image.width), random.randrange(0, image.height))
d.point(xy, fill=(random.randint(50, 200), random.randint(50, 200), random.randint(50, 200)))
return image, captcha_text
3. 使用Flask建立Web應用
現在,我們使用Flask來創建一個Web應用,并展示登錄頁面與驗證碼圖像。
from flask import Flask, render_template, jsonify, request, session
import io
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key_here'
@app.route('/')
def index():
# 渲染登錄頁面
return render_template('login.html')
@app.route('/captcha')
def captcha():
# 使用上述函數生成驗證碼圖片
image, captcha_text = generate_captcha_image()
# 將驗證碼文本存儲到session,以便之后進行驗證
session['captcha'] = captcha_text
buf = io.BytesIO()
image.save(buf, format='PNG')
buf.seek(0)
return buf.getvalue(), 200, {
'Content-Type': 'image/png',
'Content-Length': str(len(buf.getvalue()))
}
4. 處理登錄請求
登錄時,我們需要驗證用戶輸入的驗證碼是否與我們生成的匹配。
@app.route('/login', methods=['POST'])
def login():
# 檢查用戶輸入的驗證碼是否與session中的一致
if request.json.get('captcha', '').upper() == session.get('captcha', '').upper():
return jsonify({'status': 'success', 'message': '登錄成功'})
else:
return jsonify({'status': 'error', 'message': '驗證碼錯誤'}), 400
總結
通過上面的代碼,我們創建了一個簡單的網站驗證碼登錄系統。用戶需要輸入與圖片上顯示的驗證碼匹配的文本來驗證自己是人類。這不僅提高了安全性,而且能夠有效地阻止惡意機器人。 盡管此示例只是基礎版本,但您可以在此基礎上添加更多的安全性措施,例如使用更復雜的驗證碼、添加限制登錄嘗試次數的功能或使用其他驗證方法。 希望本文能幫助您了解如何使用Python和Flask來創建驗證碼登錄系統。在實際開發中,為了提供更好的用戶體驗和安全性,建議進一步完善和增強此系統。