Django中實現隨機驗證碼

# 生成驗證碼
from PIL import Image,ImageDraw,ImageFont from io import BytesIO
from .myutil import get_random_color

def
get_confirm_code(req):

  # 實例化畫布 img_size = (150,70) #畫布大小 img_color = get_random_color() #畫布顏色 img = Image.new('RGB',img_size,img_color) #新建畫布傳入畫布模式,大小,顏色 # 實例化畫筆 draw = ImageDraw.Draw(img) #確認畫筆在哪塊畫布上畫# 實例化一個字體 font_path = os.path.join(settings.STATICFILES_DIRS[0],'fonts/ADOBEARABIC-BOLD.OTF') #確認字體路徑 font_size = 30 #確認字體大小 font = ImageFont.truetype(font_path,font_size) #將字體傳入到畫布上

   # 在畫布上生成四個隨機字母 source = 'qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM' res = '' for i in range(4): code_color = get_random_color() index = random.randint(0,len(source)) my_str = source[index] res += my_str draw.text((20+30*i,20),my_str,fill=code_color,font=font) # 將字母畫在畫布上
  # 在畫布上隨機生成200個顏色位置不肯定的點
for i in range(200): x = random.randint(0,149) y = random.randint(0,69) draw.point((x,y),fill=get_random_color())
  # 將生成的畫布以二進制數據保存到內存中,並指定格式 buf
= BytesIO() img.save(buf,'png') del draw #刪除保存後的畫布 # 保存到session,爲了下一步能夠取出做比較 req.session['verify_code'] = res return HttpResponse(buf.getvalue(),content_type='image/png') #以圖片形式返回保存在內存中的值
get_confirm_code用到的工具類函數以下:
import randomdef get_random_color():
    r = random.randint(0,256)
    g = random.randint(0,256)
    b = random.randint(0,256)
    return (r,g,b)

包含驗證碼的驗證頁面html

def login(req):
    if req.method == 'GET':
        return render(req,'login.html')
    else:
        code = req.POST.get('code')
        server_code = req.session.get('verify_code')
        if code and len(code)>0 and code.lower() == server_code.lower():
            return HttpResponse('ok')
        else:
            return HttpResponse('no ok')

  前端頁面前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(function () {
            $('#myimg').click(function () {
                $(this).attr('src',"/app/get_confirm_code/"+Math.random())
            })
        })
    </script>
</head>
<body>
<form action="/app/login/" method="post">
    <img src="/app/get_confirm_code/" alt="" id="myimg"><br>
    <input type="text" name="code" placeholder="請輸入驗證碼"><br>
    <input type="submit" value="驗證">
</form>

</body>
</html>
相關文章
相關標籤/搜索