用户登录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