驗證碼 --- 總結

驗證碼

使用工具: html

  pillow前端

前端數據庫

  前端模板json

<div class="col-sm-6">
    <img id="avlid_img" src="{% url "get_imge" %}">
</div>
//url 路徑
url(r'^get_imge/', views.get_imge, name="get_imge"),

 //點擊圖片當即刷新?須要在圖片的路徑後面加上一個「?」問好便可。以下實例後端

{#    刷新驗證碼#}
    $("#avlid_img").on("click",function () {
        $(this)[0].src +="?";

    })

前端看到的驗證碼就是以上這麼多,如今到了後端的view層cookie

 
 
import random
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont

def get_rgb_func(): """ 獲取三原色 :return: 三個元組 """ return (random.randint(1,255),random.randint(1,255),random.randint(1,255)) def get_imge(request): image = Image.new(mode="RGB", size=(130, 50), color=get_rgb_func()) draw = ImageDraw.Draw(image) font = ImageFont.truetype("static/fonts/kumo.ttf",size=36) f = BytesIO() temp = [] for i in range(5): // 生成五個隨機字符 random_char = random.choice([str(random.randint(0,9)),chr(random.randint(65,90)),chr(random.randint(97,122))]) draw.text((i*27,10),random_char,get_rgb_func(),font=font) temp.append(random_char)
  //生成點、線 # width = 120 # height = 80 # # for i in range(80): # draw.point((random.randint(0,width),random.randint(0,height)),fill=get_rgb_func()) # # for i in range(10): # x1=random.randint(0,width) # x2=random.randint(0,width) # y1=random.randint(0,height) # y2=random.randint(0,height) # draw.line((x1,y1,x2,y2),fill=get_rgb_func()) # for i in range(40): # draw.point([random.randint(0, width), random.randint(0, height)], fill=get_rgb_func()) # x = random.randint(0, width) # y = random.randint(0, height) # draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_rgb_func()) image.save(f, "png") data = f.getvalue() request.session["random_char"] = ''.join(temp) //注意這裏把生成的字符串,寫入到seesion 中,目的是在用戶登陸時,利用cookie、session原理,取出以前存入的字符串,和數據庫中保存的session做對比 return HttpResponse(data)

登陸時作校驗session

 def post(self, request):
        login_response = {"user": None, "error_msg": ""}
        name = request.POST.get("name", None)
        user_pwd = request.POST.get("pwd", None)
        valid_code = request.POST.get("codeValid", None)
        session_cord = request.session.get("random_char")
        if valid_code.upper() == session_cord.upper():
            user = auth.authenticate(username=name, password=user_pwd)
            if user:
                login_response["user"] = user.username
                auth.login(request, user)
                return HttpResponse(json.dumps(login_response))
            else:
                login_response["error_msg"] = "有戶名或者密碼錯誤"
                return HttpResponse(json.dumps(login_response))
        login_response["error_msg"] = "驗證碼錯誤"
        return HttpResponse(json.dumps(login_response))
View Code

 其餘版本app

相關文章
相關標籤/搜索