Flask 驗證碼自動生成的實現(xiàn)示例
想必驗證碼大家都有所了解,但是可以自己定義圖片驗證碼,包含數(shù)字,英文以及數(shù)字計算,自動生成驗證碼。
生成圖片以及結(jié)果
from captcha.image import ImageCaptcha from PIL import Image from random import choices def gen_captcha(content='2345689abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ'): """ 生成驗證碼,可自定義,這里是生成驗證碼結(jié)果,以及驗證碼文件 """ image = ImageCaptcha() # 獲取字符串 captcha_text = "".join(choices(content, k=4)).lower() # 生成圖像 captcha_image = Image.open(image.generate(captcha_text)) return captcha_text, captcha_image
得到生成的驗證碼,進行處理,響應到頁面
處理驗證碼
from io import BytesIO from flask import make_response,session # 生成驗證碼 def get_captcha(): code, image = gen_captcha() #得到驗證碼內(nèi)容 out = BytesIO() # 操作二進制數(shù)據(jù),實例化 image.save(out, 'png') # 保存驗證碼圖片 out.seek(0) resp = make_response(out.read()) #將驗證碼圖片的bytes制作成頁面響應結(jié)果, 具體可查看make_response這個方法 resp.content_type = 'image/png' # 告訴頁面這個響應的類型 return resp, code
制作響應路由,使用藍圖
藍圖
from flask import Blueprint, session, redirect, url_for, render_template, request passport_bp = Blueprint('passport', __name__, url_prefix='/passport') # 生成藍圖passport_bp # 獲取驗證碼 @passport_bp.get('/getCaptcha') def get_captcha(): resp, code = index_curd.get_captcha() #獲取圖片 session["code"] = code # 驗證碼結(jié)果保存到session或者數(shù)據(jù)庫中,這里保存在session return resp # 返回圖片結(jié)果
html頁面展示
html展示
""" <img src="{{ url_for('passport.get_captcha') }}" class="codeImage" id="captchaImage"/> """ <script> # 使用的layui框架 layui.use(['form', 'jquery', 'layer', 'button', 'popup'], function () { let form = layui.form; let $ = layui.jquery; let layer = layui.layer; let button = layui.button; let popup = layui.popup; let captchaPath = "{{ url_for('passport.get_captcha') }}"; $("#captchaImage").click(function () { # 點擊切換 document.getElementById("captchaImage").src = captchaPath + "?" + Math.random(); }); setInterval(function () { # 30秒自動切換 document.getElementById("captchaImage").src = captchaPath + "?" + Math.random(); }, 30 * 1000); }) </script>
到此這篇關(guān)于Flask 驗證碼自動生成的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)Flask 驗證碼自動生成內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決遇到PermissionError:[Errno 13] Permission den
遇到"PermissionError:[Errno 13] Permission denied"通常是權(quán)限不足導致,解決此問題的方法包括檢查并更改文件權(quán)限,使用管理員權(quán)限運行命令,或接觸文件所有者,這些步驟有助于確保用戶具有執(zhí)行操作所需的權(quán)限,有時,文件或目錄可能被鎖定2024-09-09python opencv將圖片轉(zhuǎn)為灰度圖的方法示例
這篇文章主要介紹了python opencv將圖片轉(zhuǎn)為灰度圖的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07Tensorflow tensor 數(shù)學運算和邏輯運算方式
這篇文章主要介紹了Tensorflow tensor 數(shù)學運算和邏輯運算方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python3使用requests模塊實現(xiàn)顯示下載進度的方法詳解
這篇文章主要介紹了Python3使用requests模塊實現(xiàn)顯示下載進度的方法,結(jié)合實例形式分析了Python3中requests模塊的配置、使用及顯示進度條類的相關(guān)定義方法,需要的朋友可以參考下2019-02-02Python文件簡單操作及openpyxl操作excel文件詳解
這篇文章主要為大家詳細介紹了python對文件的簡單使用及openpyxl操作excel文件的方法,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2022-10-10python opencv實現(xiàn)圖片旋轉(zhuǎn)矩形分割
這篇文章主要為大家詳細介紹了python opencv實現(xiàn)圖片旋轉(zhuǎn)矩形分割,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07