用戶登陸ajax局部刷新驗證碼

用戶登陸的時候,登陸頁面附帶驗證碼圖片,用戶須要輸入正確的驗證碼才能夠登陸,驗證碼實現局部刷新操做。javascript

效果如圖:html

代碼以下:前端

#生成驗證碼及圖片的函數  newcode.pyjava

import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter

_letter_cases = "abcdefghjkmnpqrstuvwxy" # 小寫字母,去除可能干擾的i,l,o,z
_upper_cases = _letter_cases.upper() # 大寫字母
_numbers = ''.join(map(str, range(3, 10))) # 數字
init_chars = ''.join((_letter_cases, _upper_cases, _numbers))


def create_validate_code(size=(110, 40),
             chars=init_chars,
             img_type="GIF",
             mode="RGB",
             bg_color=(255, 255, 255),
             fg_color=(0, 0, 255),
             font_size=18,
             font_type="Monaco.ttf",
             length=4,
             draw_lines=True,
             n_line=(1, 2),
             draw_points=True,
             point_chance=2):


  width, height = size # 寬高
  # 建立圖形
  img = Image.new(mode, size, bg_color)
  draw = ImageDraw.Draw(img) # 建立畫筆

  def get_chars():
    """生成給定長度的字符串,返回列表格式"""
    return random.sample(chars, length)

  def create_lines():
    """繪製干擾線"""
    line_num = random.randint(*n_line) # 干擾線條數

    for i in range(line_num):
      # 起始點
      begin = (random.randint(0, size[0]), random.randint(0, size[1]))
      # 結束點
      end = (random.randint(0, size[0]), random.randint(0, size[1]))
      draw.line([begin, end], fill=(0, 0, 0))

  def create_points():
    """繪製干擾點"""
    chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]

    for w in range(width):
      for h in range(height):
        tmp = random.randint(0, 100)
        if tmp > 100 - chance:
          draw.point((w, h), fill=(0, 0, 0))

  def create_strs():
    """繪製驗證碼字符"""
    c_chars = get_chars()
    strs = ' %s ' % ' '.join(c_chars) # 每一個字符先後以空格隔開

    #定義font字體
    font = ImageFont.truetype(font_type, font_size)
    font_width, font_height = font.getsize(strs)

    draw.text(((width - font_width) / 3, (height - font_height) / 3),
         strs, font=font, fill=fg_color)

    return ''.join(c_chars)

  if draw_lines:
    create_lines()
  if draw_points:
    create_points()
  strs = create_strs()

  # 圖形扭曲參數
  params = [1 - float(random.randint(1, 2)) / 100,
       0,
       0,
       0,
       1 - float(random.randint(1, 10)) / 100,
       float(random.randint(1, 2)) / 500,
       0.001,
       float(random.randint(1, 2)) / 500
       ]
  img = img.transform(size, Image.PERSPECTIVE, params) # 建立扭曲

  img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 濾鏡,邊界增強(閾值更大)

  return img, strs

# 後臺構造前端ajax請求的url url.pyajax

url(r'^createCodeImg/$', create_code_img,name='createCodeImg'),

#生成驗證碼圖片views.py數據庫

from newcode.py import create_validate_code
@csrf_exempt
def create_code_img(request):

    f = BytesIO()  # 直接在內存開闢一點空間存放臨時生成的圖片
    # 調用check_code生成照片和驗證碼
    img, code = create_validate_code()
    # 將驗證碼存在服務器的session中,用於校驗
    request.session['check_code'] = code  
    img.save(f, 'PNG') 
    # 將內存的數據讀取出來,並以HttpResponse返回
    return HttpResponse(f.getvalue())  

#前端頁面 驗證碼圖片src地址django

<img id="codepic" src={% url 'common:createCodeImg' %} onclick="refreshcode(this);"/>點擊刷新

#也能夠寫成<img id="codepic" src='/common:createCodeImg/' onclick="refreshcode(this);"/>點擊刷新

#javascript+ajax刷新驗證碼服務器

function refreshcode(ths)
    {
        // alert('點擊了圖片');
        var url = "/createCodeImg/";
        $.ajax({
                url: url,
                type: "POST",
                data: {},
                dataType: 'text',
                success: function(data, statusText, xmlHttpRequest){
                    console.log(data);
                    // $("#codepic").attr("src",data+"?flag="+Math.random());
                    ths.src += '?';
            //此處刷新圖片src }, error:
function(xmlHttpRequest, statusText, errorThrown){ // } }); };

#登陸視圖函數session

def log_in(request):
    try:
        if request.method == 'POST':
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                # 取會話中驗證碼
                session_check_code = request.session['check_code']
                post_check_code = login_form.cleaned_data['check_code']
                username = login_form.cleaned_data["username"]
                password = login_form.cleaned_data["password"]
                # django自帶驗證
                # user = authenticate(username=username, password=password)
                # 數據庫查詢驗證
                user = UserProfile.objects.get(username=username, password=password)
                print user
                if user is not None:
                    if user.is_active:
                        if session_check_code == post_check_code:
                            user.backend = 'django.contrib.auth.backends.ModelBackend'                                                login(request, user)
                            msg=(u"login successful !登陸成功!")
                            # return render(request, 'common/success.html', {'reason': msg})
                        else:
                            msg = (u"check code is wrong!驗證碼錯誤!請返回從新輸入")
                            return render(request, 'common/failure.html', {'reason': msg})
                    else:
                        msg=(u"disabled account please active your account!帳戶未激活!")
                        return render(request, 'common/failure.html', {'reason': msg})
                else:
                    msg=(u"invalid account please register!無效的帳戶!請從新註冊!")
                    return render(request, u'common/failure.html', {'reason': msg})
        else:
            login_form = LoginForm()
    except Exception as e:
        print '錯誤',e
        # logger.error(e)
     
    return render(request, 'common/first.html', locals())

作到這裏,圖片就能夠實現局部刷新了!登陸的時候將頁面獲取到的驗證碼和保存在session裏面的比較,用戶輸入正確才能登陸成功。dom

這裏生產驗證碼圖片的方法涉及圖形庫相關知識,大概瞭解就好了!

參考:http://www.jb51.net/article/111525.htm

相關文章
相關標籤/搜索