2018-04-18

Django---验证码

效果图

030.png

1.Pillow的安装

pip install Pillow
pip的升级命令windows
python -m pip install -U pip
pip的升级命令linux
pip install -U pip

2.新建 viewsUtil.py,定义函数 verify

  • Image 表示画布对象
  • ImageDraw 表示画笔对象
  • ImageFont 表示字体对象, ubuntu 的字体路径为
    “/usr/share/fonts/truetype/freefont”
  • 代码如下
from django.http import HttpResponse
from PIL import Image,ImageDraw,ImageFont
import random
import io


def verify(request):
    #定义变量,用于画面的背景色,宽,高
    bg_color = (random.randrange(20,100), random.randrange(20,100), random.randrange(20,100))
    width = 120
    height = 25
    #创建画面对象
    im = Image.new('RGB',(width,height),bg_color)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(100):
        #x,y 的坐标轴,在这里是一个元组
        xy = (random.randrange(0,width),random.randrange(0,height))
        fill = (random.randrange(0,255),255,random.randrange(0,225))
        draw.point(xy,fill)
        
    #定义验证码的被选值
    str1 = 'abcdefghijklmnuvwxyz123456789ABCDEFGHIJKLMONUVWXYZ'
    
    #从中随机选取6个值作为验证码
    rand_str = ""
    for i in range(6):
        rand_str = rand_str + str1[random.randrange(0,len(str1)-1)]
    print(rand_str)
    
    #构造字体对象
    font = ImageFont.truetype('simkai.ttf',23)
    
    #构造字体颜色
    fontcolor = (225,random.randrange(0,225),random.randrange(0,225))
    
    #绘制验证码的6个字
    draw.text((5,2),rand_str[0],font = font,fill = fontcolor)
    draw.text((25,2),rand_str[1],font = font,fill = fontcolor)
    draw.text((45,2),rand_str[2],font = font,fill = fontcolor)
    draw.text((65,2),rand_str[3],font = font,fill = fontcolor)
    draw.text((85,2),rand_str[4],font = font,fill = fontcolor)
    draw.text((105,2),rand_str[5],font = font,fill = fontcolor)
    
    #释放画笔
    del draw
    
    #存入seeeion,用于进一步验证
    # request.session['Verification'] = rand_str
    # print(request.session.get('Verification'))
    request.session['Verification'] = rand_str
    print(rand_str)
    
    #将照片保存在内存中,文件后缀名为 .png
    f = io.BytesIO()
    im.save(f,'png')
    
    #将内存中的图片数据返回客户端,MIME类型为图片png
    return HttpResponse(f.getvalue(),'image/png')

3.配置项目的url

url(r'^Verification/',include('Verification.urls')),

4.配置应用的url

    url(r'^$',viewsUtil.verify),
    url(r'verify/$', views.verify),
    url(r'^verifycodeValid/$', views.verifycodeValid),
    url(r'^verify_page/$', views.verify_page),

5.js添加

在主文件夹中添加static文件夹,将 jquery文件放到static文件夹中
然后配置项目settings.py 添加代码

STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]

6.显示验证码





Title


Hello world
CheckCode

启动服务器,即可查看

7.扩展和验证(可以在页面里实现更换验证码)

配置应用的views

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .viewsUtil import verify
from django.views.decorators.csrf import csrf_exempt
# Create your views here.

@csrf_exempt
def verify_page(request):
    verify(request)
    template = loader.get_template('Verification/Verification.html')
    return HttpResponse(template.render())


@csrf_exempt
def verifycodeValid(request):
    vc = request.POST['vc']
    print(vc)
    if vc != request.session['Verification']:
        return HttpResponse('no')
    else:
        return HttpResponse('ok')

应用的url同上所配置的

8.完整的html模块代码




    
    Title




验证码: CheckCode 看不清,换一个

效果图


031.png

你可能感兴趣的:(2018-04-18)