1、配置文件setting
AUTH_USER_MODEL = 'app01.UserInfo' import os STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
2、views
验证码传输
"""pip install Pillow""" from PIL import Image, ImageDraw, ImageFont import random from io import BytesIO def get_img(request): """随机生成颜色""" def get_color(): return random.randint(0, 255), random.randint(0, 255), random.randint(0,255) img = Image.new('RGB', (270, 40), color=get_color()) #生成背景色 """在背景色中添加文字""" draw = ImageDraw.Draw(img) word_font = ImageFont.truetype('static/font/msyhbd.ttf', size=25) """生成6位字符的随机验证码""" code_str = '' for i in range(5): random_num = str(random.randint(0, 9)) random_low = chr(random.randint(95, 122)) random_upper = chr(random.randint(65, 90)) random_char = random.choice([random_num,random_low,random_upper]) draw.text((i*50+30,5), random_char, get_color(), font=word_font) # !!!!保存验证码 code_str += random_char request.session['code_str'] = code_str"""噪点""" width=270 height=40 for i in range(10): x1 = random.randint(0, width) y1 = random.randint(0, height) x2 = random.randint(0, width) y2 = random.randint(0, height) draw.line((x1,y1,x2,y2),fill=get_color()) """生成图片存储在内存中""" f = BytesIO() img.save(f,'png') data = f.getvalue() return HttpResponse(data)
用户验证
from django.contrib import auth from django.http import JsonResponse from django.shortcuts import render, HttpResponse def login(request): user_info={'user':None,'msg':None} if request.method == 'POST': user = request.POST.get('user') pwd = request.POST.get('pwd') captcha = request.POST.get('captcha') if captcha.upper() == request.session['code_str'].upper(): user_boj = auth.authenticate(username=user,password=pwd) if user_boj: auth.login(request,user_boj) user_info['user'] = user_boj.username else: user_info['msg'] = '账号、密码错误' else: user_info['msg'] = '验证码错误' return JsonResponse(user_info) #无需反序列化 return render(request, 'login.html')
3、前端
<div class='container'> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h2 class="text-center">用户登陆</h2> <form > {% csrf_token %} <div class="form-group"> <label for="user">用户名</label> <input type="text" id="user" class="form-control"> </div> <div class="form-group"> <label for="pwd">密码</label> <input type="password" id="pwd" class="form-control"> </div> <div class="row"> <div class="col-md-6"> <label for="captcha">验证码</label> <input type="text" id="captcha" class="form-control"> </div> <div class="col-md-6"> <img src="/get_img/" alt="" id="img" > </div> </div> <input type="button" class="btn pull-left" value="提交" id="btn"><span class="error"></span> <input type="button" class="btn btn-info pull-right" value="注册" id="btn"> </form> </div> </div> </div>
4、jquery
$(function () { $('#btn').click(function () { $.ajax({ url:'/login/', type:'POST', data:{ user:$('#user').val(), pwd:$('#pwd').val(), captcha:$('#captcha').val(), {#ajax自己组件{% csrf_token %}#} csrfmiddlewaretoken:$('[name=csrfmiddlewaretoken]').val(), }, success:function (data) { console.log(data); if(data['user']){ location.href = '/index/' } else{ $('.error').text(data['msg']).css({'color':'red','text-align':'right'}) } } }) }); {#验证码刷新#} $('#img').click(function () { $(this)[0].src += '?' }) })
重点
1、前端img标签,显示后端图片(一次请求伴随多次静态请求)
2、PIL模块的应用(生成背景色,生成验证码,生成噪点),IO应用将数据存放入内存中
3、验证码的校验,将数据存储在session中
request.session['name'] = value
obj = auth.authenticate(...)验证后通过auth.login(request,obj) 将obj存入了requset,下次请求来时,可直接取上次登陆对象
4、JsonResponse用法,无需经过json序列化数据
5、ajax传输数据,需要自建{%csrf_token%}
6、验证码刷新
$('#img').click(function () {
$(this)[0].src += '?'
})