验证码
使用工具:
pillow
前端
前端模板
<div class="col-sm-6"> <img id="avlid_img" src="{% url "get_imge" %}"> </div>
//url 路径
url(r'^get_imge/', views.get_imge, name="get_imge"),
//点击图片立即刷新?需要在图片的路径后面加上一个“?”问好即可。如下实例
{# 刷新验证码#}
$("#avlid_img").on("click",function () {
$(this)[0].src +="?";
})
前端看到的验证码就是以上这么多,现在到了后端的view层
import random
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
def get_rgb_func():
"""
获取三原色
:return: 三个元组
"""
return (random.randint(1,255),random.randint(1,255),random.randint(1,255))
def get_imge(request):
image = Image.new(mode="RGB", size=(130, 50), color=get_rgb_func())
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("static/fonts/kumo.ttf",size=36)
f = BytesIO()
temp = []
for i in range(5): // 生成五个随机字符
random_char = random.choice([str(random.randint(0,9)),chr(random.randint(65,90)),chr(random.randint(97,122))])
draw.text((i*27,10),random_char,get_rgb_func(),font=font)
temp.append(random_char)
//生成点、线
# width = 120
# height = 80
#
# for i in range(80):
# draw.point((random.randint(0,width),random.randint(0,height)),fill=get_rgb_func())
#
# for i in range(10):
# x1=random.randint(0,width)
# x2=random.randint(0,width)
# y1=random.randint(0,height)
# y2=random.randint(0,height)
# draw.line((x1,y1,x2,y2),fill=get_rgb_func())
# for i in range(40):
# draw.point([random.randint(0, width), random.randint(0, height)], fill=get_rgb_func())
# x = random.randint(0, width)
# y = random.randint(0, height)
# draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_rgb_func())
image.save(f, "png")
data = f.getvalue()
request.session["random_char"] = ''.join(temp) //注意这里把生成的字符串,写入到seesion 中,目的是在用户登录时,利用cookie、session原理,取出之前存入的字符串,和数据库中保存的session作对比
return HttpResponse(data)
登录时做校验
def post(self, request):
login_response = {"user": None, "error_msg": ""}
name = request.POST.get("name", None)
user_pwd = request.POST.get("pwd", None)
valid_code = request.POST.get("codeValid", None)
session_cord = request.session.get("random_char")
if valid_code.upper() == session_cord.upper():
user = auth.authenticate(username=name, password=user_pwd)
if user:
login_response["user"] = user.username
auth.login(request, user)
return HttpResponse(json.dumps(login_response))
else:
login_response["error_msg"] = "有户名或者密码错误"
return HttpResponse(json.dumps(login_response))
login_response["error_msg"] = "验证码错误"
return HttpResponse(json.dumps(login_response))