时间:2021-07-01 10:21:17 帮助过:31人阅读
将验证码保存在session, 用户提交验证码和session的验证码进行比较,完成验证码的验证
- 将验证码保存在session,用来记住用户。以便后面的验证码验证 code = "".join(code_list) request.session["code"] = code - login验证码验证 def login(request): if request.method == ‘GET‘: return render(request, ‘login.html‘) else: input_code = request.POST.get("code") session_code = request.session.get(‘code‘) if input_code.upper() == session_code.upper(): return HttpResponse("code is correct") else: return HttpResponse("code is invalid")View Code
将验证码封装
- 验证码封装 import random from PIL import (Image,ImageDraw,ImageFont,ImageFilter) def check_code(width=120, height=30, char_length=5, font_file=‘kumo.ttf‘, font_size=28): code = [] img = Image.new(mode=‘RGB‘, size=(width, height), color=(255, 255, 255)) draw = ImageDraw.Draw(img, mode=‘RGB‘) def rndChar(): """生成随机字母 :return: """ return chr(random.randint(65, 90)) def rndColor(): """生成随机颜色:return: """ return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255)) # 写文字 font = ImageFont.truetype(font_file, font_size) for i in range(char_length): char = rndChar() code.append(char) h = random.randint(0, 4) draw.text([i * width / char_length, h], char, font=font, fill=rndColor()) # 写干扰点 for i in range(40): draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor()) # 写干扰圆圈 for i in range(40): draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor()) x = random.randint(0, width) y = random.randint(0, height) draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor()) # 画干扰线 for i in range(5): 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=rndColor()) img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) return img, ‘‘.join(code)View Code
获取验证码后台视图
# 封装后的使用 def checkout(request): from io import BytesIO from utils.checkCode import check_code img, code = check_code() stream = BytesIO() img.save(stream, ‘png‘) request.session[‘code‘] = code return HttpResponse(stream.getvalue())View Code
[oldboy-django][2深入django]登录注册页面验证码
标签:login end 添加内容 ima 文字 closed 空间 完成 tle