django 實現驗證碼功能
阿新 • • 發佈:2018-12-10
這是我做的驗證碼的效果圖,可能
在這裡我是通過django框架實現的
下面是主要功能塊,思路是建立畫布和畫筆,然後通過隨機數生成隨機字元,隨機顏色,隨機點,然後組合成為的一張圖片
def getVerificationCode(request): #建立畫布 #mode 模式,"RGB" #size 畫布的尺寸 image=Image.new("RGB",(200,70),createcolor()) imageDraw=ImageDraw.Draw(image,"RGB") imageFont=ImageFont.truetype("/home/yc/Desktop/hz1805project/week01/static/fonts/ADOBEARABIC-ITALIC.OTF",size=50) # imageDraw.text((5,10),"i love you!",fill=createcolor(),font=imageFont) import io charsource="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890" sum = "" for i in range(4): ch=random.choice(charsource) imageDraw.text((15+i*50,10),ch,fill=createcolor(),font=imageFont) sum+=ch #通過session記錄這個驗證碼並且設定過期時間為60秒 request.session["verCode"]=sum request.session.set_expiry(60) #畫麻子 for i in range(2000): x=random.randint(0,200) y = random.randint(0, 70) imageDraw.point((x,y),fill=createcolor()) #建立一個位元組流 byteIO=io.BytesIO() #把圖片放在位元組流裡面去 image.save(byteIO,"png") return HttpResponse(byteIO.getvalue(),"image/png") #隨機顏色的生成 def createcolor(): red=random.randint(0,255) green=random.randint(0,255) blue=random.randint(0,255) return (red,green,blue) #登陸頁面 def login(request): return render(request,"logincode.html") #登陸之後進行的後臺比對操作 def dologin(request): value=request.GET.get("codevalue") value2=request.session.get("verCode") if value==value2: return HttpResponse("success!!") else: return HttpResponse("error!!")
這個是表單的程式碼
<form action="{% url 'day7:dologin' %}" method="GET"> 驗證碼<input type="text" name="codevalue"><br> <br><img src="{% url 'day7:getVerificationCode' %}" id="code" onclick="change()" alt="驗證碼"> <input type="submit" value="submit"> </form>
js的程式碼
function change(){
(document.getElementById("code")).setAttribute("src","/day7/getVerificationCode"+Math.random())
}