1.在用户注册、登陆页面,为了防止暴力请求,可以加入验证码功能,如果验证码错误,则不需要继续处理,这样可以减轻服务器的压力
2.使用验证码也是一种有效防止csrf攻击的方法
视图函数views.py
from django.shortcuts import render, redirect from django.http import HttpResponse from django.urls import reverse from . import models # 创建验证码 def verifycode(request): # 引入绘画模板 from PIL import Image, ImageDraw, ImageFont # 引入随机函数模块 import random # 定义变量,用于画面的背景色,宽,高 bg_color = (random.randrange(20, 100), random.randrange(20, 100), 255) bg_width = 100 bg_height = 25 # 创建画面对象 im = Image.new('RGB', (bg_width, bg_height), bg_color) # 创建笔画对象 draw = ImageDraw.Draw(im) # 调用笔画的point()函数绘画噪点 for i in range(0, 100): draw_xy = (random.randrange(0, bg_width), random.randrange(0, bg_height)) draw_fill = (random.randrange(0, 255), 255, random.randrange(0, 255)) draw.point(draw_xy, fill=draw_fill) # 定义验证码的备选值 candidate_str = 'ASDFGHJKLQWERTYUIO1234567890ZXCVBNM0987654321poiuytrewqlkjhgfdsamnbvcxz' # 随机选取四个字符作为验证码 rand_str = '' for i in range(0, 4): rand_str += candidate_str[random.randrange(0, len(candidate_str))] # 构造字体对象 font_obj = ImageFont.truetype("C:\WINDOWS\Fonts\SIMLI.TTF", 23) # 构造字体颜色 fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255)) # 绘制出随机选取的四个字符 draw.text((5, 0), rand_str[0], font=font_obj, fill=fontcolor) draw.text((25, 0), rand_str[1], font=font_obj, fill=fontcolor) draw.text((50, 0), rand_str[2], font=font_obj, fill=fontcolor) draw.text((75, 0), rand_str[3], font=font_obj, fill=fontcolor) # 释放画笔 del draw # 存入session, 用于做进一步验证 request.session['verifycode'] = rand_str # 内存文件操作 import io buf = io.BytesIO() # 将图片保存在内存中,文件类型为png im.save(buf, 'png') # 将内存中的图片数据返回给客户端,MIME类型为图片png return HttpResponse(buf.getvalue(), content_type='image/png') # 将验证码应用的登陆页面 def login(request): return render(request, 'login.html') # 验证用户输入的验证码 def verifycodeValid(request): verify_code = request.POST.get('verifycode') if verify_code.upper() == request.session['verifycode']: return HttpResponse('验证码通过') else: return HttpResponse('验证码错误')
登陆页面login.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>验证码</title> </head> <body> <form action="{% url 'valid' %}" method="POST"> {% csrf_token %} 用户名:<input type="text" name="uname" /> <br/> 验证码:<input type="text" name="verifycode" /> <img id='img' src="{% url 'yzm' %}" alt="验证码" /> <br/> <button>提交</button> </form> <script type="text/javascript"> var Img = document.getElementById('img'); Img.onclick=function(){ Img.src=Img.src+'?imgid='+Math.random(); } </script> </body> </html>
子路由
from django.urls import path, re_path from . import views urlpatterns = [ path('yzm/', views.verifycode, name='yzm'), path('login/', views.login, name='login'), path('valid/', views.verifycodeValid, name='valid') ]
# 注意:PIL模块导入:pip install pillow 而且要在服务器端导入,仅在pycharm导入开启服务器时是不生效的