原创

Django登录验证码

一、验证码函数

def check_code(width=130, height=46, char_length=4, font_file='A1/login/FZQingCTJ.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:
"""
ranNum = str(random.randint(0, 9))
ranLower = chr(random.randint(65, 90))
ranUpper = chr(random.randint(97, 120))
return random.choice([ranNum, ranLower, ranUpper])

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 = (height - font_size) / 2
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)

二、验证码视图

class Verify_codes(View):

def get(self, request):
img, code = check_code() f = BytesIO()
img.save(f, "png")
data = f.getvalue() # 验证码写入session request.session['yzm_str'] = code.lower()
return HttpResponse(data)

三、验证码请求URL

path("verify_code/", Verify_codes.as_view(), name="yzm")

四、验证码前端页面

此代码url为二级

<div class="form-group has-feedback row">
<div class="col-7">
<span class="mdi mdi-check-all form-control-feedback" aria-hidden="true"></span>
<input type="text" name="yam" id="yzm" class="form-control" placeholder="验证码">
</div>
<div class="col-5 text-right">
<img src="/login/verify_code/" class="pull-right" id="captcha" style="cursor: pointer;"
onclick="this.src=this.src+'?d='+Math.random();" title="点击刷新" alt="captcha">
</div>
</div>

五、登录提交视图

class Login(View):
def post(self, request):
userdata = request.POST
yzm = request.POST.get("yzm", None)
if yzm:
if request.session.get("yzm_str") == yzm.lower():
"""验证码正确之后验证用户信息"""
else:
res = {"status": False, "msg": "验证码不正确!", "url": ""}
else:
res = {"status": False, "msg": "验证码不能为空!", "url": ""}

return HttpResponse(json.dumps(res))



“”“”“”

哪里有问题欢迎评论,积极改进

“”“”“”



正文到此结束
评论

登录后才能发表评论 登录/注册

0评论
  • 还没有评论,快来抢沙发吧!