Python生成驗證碼實例
更新時間:2014年08月21日 11:53:46 投稿:shichen2014
這篇文章主要介紹了Python生成驗證碼的方法,具有很好的實用價值,代碼結(jié)構(gòu)清晰易懂,需要的朋友可以參考下
本文實例展示了Python生成驗證碼的方法,具有很好的實用價值。分享給大家供大家參考。具體實現(xiàn)方法如下:
前臺頁面代碼如下:
<div> <img id="authcode_img" alt="驗證碼" src="/registration/makeimage/{{time}}"/> <!-- time 任意隨機數(shù)(時間戳),防止頁面緩存 導致驗證碼不能更新--> <a href="javascript:refreshCode();" rel="external nofollow" style="color:blue;">看不清換一張</a> </div> <script> function refreshCode() { $('authcode_img').src = "/registration/makeimage/" + Math.random(); } </script>
后臺程序如下:
import StringIO import Image, ImageDraw, ImageFont, random #相應的模塊需要安裝 from xxx.settings import authcode_font #請確保改字體存在 def make_image(request): mp = hashlib.md5() mp.update(str(datetime.datetime.now())+str(random.random())) mp_src = mp.hexdigest() rand_str = mp_src[0:6] font = ImageFont.truetype(authcode_font, 25) width = 75 height = 30 im = Image.new('RGB',(width,height),'#%s'%mp_src[-7:-1]) draw = ImageDraw.Draw(im) draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height))) draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height))) draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height))) draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height))) draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height))) draw.text((5,2), rand_str, font=font) del draw buffer = StringIO.StringIO() im.save(buffer,'jpeg') httpResponse = HttpResponse(content=buffer.getvalue(),mimetype="image/jpeg") request.session['auth_code'] = rand_str return httpResponse
程序效果如下:
相關文章
使用python解析MDX詞典數(shù)據(jù)并保存為Excel文件
MDX(Mobile Dictionary eXchange)是一種常見的詞典文件格式,通常用于在移動設備和電腦之間共享辭典數(shù)據(jù),本文深入探討了從MDX詞典數(shù)據(jù)提取、處理到最終保存為Excel文件的全過程,需要的朋友可以參考下2023-12-12Python將腳本程序轉(zhuǎn)變?yōu)榭蓤?zhí)行程序的實現(xiàn)
本文主要介紹了Python將腳本程序轉(zhuǎn)變?yōu)榭蓤?zhí)行程序的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02Python數(shù)據(jù)結(jié)構(gòu)與算法之完全樹與最小堆實例
這篇文章主要介紹了Python數(shù)據(jù)結(jié)構(gòu)與算法之完全樹與最小堆,結(jié)合實例形式分析了Python完全樹定義及堆排序功能實現(xiàn)相關操作技巧,需要的朋友可以參考下2017-12-12Python中列表遍歷使用range和enumerate的區(qū)別講解
這篇文章主要介紹了Python中列表遍歷使用range和enumerate的區(qū)別,在Python編程語言中,遍歷list有range和enumerate方法,本文結(jié)合示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12