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


用戶登錄的時候,登錄頁面附帶驗證碼圖片,用戶需要輸入正確的驗證碼才可以登錄,驗證碼實現局部刷新操作。

效果如圖:

代碼如下:

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

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.py

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地址

<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){ // } }); };

#登錄視圖函數

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里面的比較,用戶輸入正確才能登錄成功。

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM