Django下基于Python的登录验证码生成

验证码

在用户登录时,为了防止暴力请求,我们可以加入验证码功能,如果验证码错误,则不需要继续处理,可以减轻一些服务器的压力
使用验证码也是一种有效的防止crsf的方法
验证码效果如下图:
这里写图片描述
接下来就是代码实现了

验证码视图

实现思路:
新建viewsUtil.py,定义函数verifycode
此段代码用到了PIL中的Image、ImageDraw、ImageFont模块,需要先安装Pillow(3.4.1)包,详细文档参考http://pillow.readthedocs.io/en/3.4.x/
Image表示画布对象
ImageDraw表示画笔对象
ImageFont表示字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”

# PIL是python2版本的图像处理库,不过现在用Pillow比PIL强大,是python3的处理库
from PIL import Image, ImageDraw, ImageFont
from django.http import HttpResponse
#导入随机数模块
import random
from io import BytesIO

def verify_code(request):
        # 1,定义变量,用于画面的背景色、宽、高
        # random.randrange(20, 100)意思是在20到100之间随机找一个数
        bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 159)
        width = 100
        height = 30
        # 2,创建画面对象
        im = Image.new('RGB', (width, height), bgcolor)
        # 3,创建画笔对象
        draw = ImageDraw.Draw(im)
        # 4,调用画笔的point()函数绘制噪点,防止攻击
        for i in range(0, 100):
            # 噪点绘制的范围
            xy = (random.randrange(0, width), random.randrange(0, height))
            # 噪点的随机颜色
            fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
            # 绘制出噪点
            draw.point(xy, fill=fill)
        # 5,定义验证码的备选值
        str1 = 'ABCD123EFGHJK456LMNPQRS789TUVWXYZ0'
        # 6,随机选取4个值作为验证码
        rand_str = ''
        for i in range(0, 4):
            rand_str += str1[random.randrange(0, len(str1))]
        # 7,构造字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
        #arial.ttf window下的字体
        font = ImageFont.truetype('arial.ttf', 23)
        # 8,构造字体颜色
        fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
        # 9,绘制4个字
        draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
        draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
        draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
        draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
        # 9,用完画笔,释放画笔
        del draw
        # 10,存入session,用于做进一步验证
        request.session['verifycode'] = rand_str.lower()
        # 11,内存文件操作
        buf = BytesIO()
        # 12,将图片保存在内存中,文件类型为png
        im.save(buf, 'png')
        # 13,将内存中的图片数据返回给客户端,MIME类型为图片png
        return HttpResponse(buf.getvalue(), 'image/png')

urls.py里面的代码

# 生产验证码图片url
    url(r'^verify_code/$', views.verify_code),

模板页面代码

<!--直接调用生产图片验证码的视图函数,生产验证码-->
<!--每点击一次,后面就一个1,比如11111就是点击了四次-->
    <img src="/verify_code/?1" id="imgvcode"/>
        <div id="change">看不清?</div>
脚本代码:
 $('#change').css('cursor', 'pointer').click(function () {
    $('#imgvcode').attr('src', $('#imgvcode').attr('src') + 1)
       });

猜你喜欢

转载自blog.csdn.net/tyt_xiaotao/article/details/80291310