Django框架之验证码生成示例
Posted linu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django框架之验证码生成示例相关的知识,希望对你有一定的参考价值。
一、生成随机颜色的图片
1)前端代码展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.min.css"> <script src="/static/jquery-3.1.1.js"></script> <title>登录页面</title> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>登录</h1> <form> <div class="form-group"> <label for="">用户名</label> <input type="text" id="id_name" class="form-control"> </div> <div class="form-group"> <label for="">密码</label> <input type="password" id="id_pwd" class="form-control"> </div> <div class="form-group"> <label for="">验证码</label> <div class="row"> <div class="col-lg-6"> <input type="text" id="code" class="form-control"> </div> <div class="col-lg-6"> <img height="35" width="250" src="/get_code/" alt=""> </div> </div> </div> <input type="button" value="登录" class="btn btn-danger"> </form> </div> </div> </div> </body> </html>
提交方式,基于ajax提交
2)生成随机颜色的图片
def get_random_color(): ‘‘‘生成随机颜色的图片‘‘‘ import random return (random.randint(0,255),random.randint(0,255),random.randint(0,255))
3)验证码函数,写入图片,读取图片返回给前端
def get_code(request): from PIL import Image img = Image.new(‘RGB‘,(35,250),color=get_random_color()) with open(‘code.png‘,‘wb‘) as f: # 造成随机颜色的图片 img.save(f) with open(‘code.png‘,‘rb‘) as f: # 读取图片,给前端 data=f.read() return HttpResponse(data)
二、在随机验证码图片内写入文字.(重点)
随机生成的验证码图片,保存于内存。图片内的文字保存于session(用于登录验证)
def get_code(request): from PIL import Image, ImageDraw, ImageFont from io import BytesIO # 生成的验证码存放于内存 import random img = Image.new("RGB", (270, 40), color=get_random_color()) # (270, 40) 指定生成的图片的长度,高度 draw = ImageDraw.Draw(img) # kumo.ttf 文字样式,网上下载ttf kumo_font = ImageFont.truetype("static/font/kumo.ttf", size=32) # 引入字体 valid_code_str = "" for i in range(5): random_num = str(random.randint(0, 9)) # 随机一个数字 random_low_alpha = chr(random.randint(95, 122)) # 随机一个小写字母 random_upper_alpha = chr(random.randint(65, 90)) # 随机一个大写字母 random_char = random.choice([random_num, random_low_alpha, random_upper_alpha]) # 从上面的3个选择一个出来 draw.text((i * 50 + 20, 5), random_char, get_random_color(), font=kumo_font) # (i * 50 + 20, 5) 写字母的时候便宜 # 保存验证码字符串 valid_code_str += random_char print("valid_code_str", valid_code_str) f = BytesIO() # 生成一个对象,保存于内存 img.save(f, "png") # 验证码图片保存于内存 data = f.getvalue() request.session[‘code‘]=valid_code_str # 验证码保存于session中 return HttpResponse(data)
三、加入ajax请求登录
1)url视图函数
from django.conf.urls import url from django.contrib import admin from mybbs import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^login/‘, views.login), url(r‘^get_code/‘, views.get_code), ]
2)login页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.min.css"> <script src="/static/jquery-3.1.1.js"></script> <title>登录页面</title> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>登录</h1> <form> {% csrf_token %} <div class="form-group"> <label for="">用户名</label> <input type="text" id="id_name" class="form-control"> </div> <div class="form-group"> <label for="">密码</label> <input type="password" id="id_pwd" class="form-control"> </div> <div class="form-group"> <label for="">验证码</label> <div class="row"> <div class="col-lg-6"> <input type="text" id="code" class="form-control"> </div> <div class="col-lg-6"> <img height="35" width="250" src="/get_code/" alt=""> </div> </div> </div> <input type="button" id="submit" value="登录" class="btn btn-danger"> </form> </div> </div> </div> <script> $("#submit").click(function () { $.ajax({ url: ‘/login/‘, type: ‘post‘, data: { ‘name‘: $("#id_name").val(), ‘pwd‘: $("#id_pwd").val(), ‘code‘: $("#code").val(), ‘csrfmiddlewaretoken‘: ‘{{csrf_token}}‘ }, success: function (data) { console.log(data) } }) }) </script> </body> </html>
3)验证码相关函数
def get_random_color(): ‘‘‘生成随机颜色的图片‘‘‘ import random return (random.randint(0,255),random.randint(0,255),random.randint(0,255)) def get_code(request): from PIL import Image, ImageDraw, ImageFont from io import BytesIO # 生成的验证码存放于内存 import random img = Image.new("RGB", (270, 40), color=get_random_color()) # (270, 40) 指定生成的图片的长度,高度 draw = ImageDraw.Draw(img) # kumo.ttf 文字样式,网上下载ttf kumo_font = ImageFont.truetype("static/font/kumo.ttf", size=32) # 引入字体 valid_code_str = "" for i in range(5): random_num = str(random.randint(0, 9)) # 随机一个数字 random_low_alpha = chr(random.randint(95, 122)) # 随机一个小写字母 random_upper_alpha = chr(random.randint(65, 90)) # 随机一个大写字母 random_char = random.choice([random_num, random_low_alpha, random_upper_alpha]) # 从上面的3个选择一个出来 draw.text((i * 50 + 20, 5), random_char, get_random_color(), font=kumo_font) # (i * 50 + 20, 5) 写字母的时候便宜 # 保存验证码字符串 valid_code_str += random_char print("valid_code_str", valid_code_str) f = BytesIO() # 生成一个对象,保存于内存 img.save(f, "png") # 验证码图片保存于内存 data = f.getvalue() request.session[‘code‘]=valid_code_str # 验证码保存于session中 return HttpResponse(data)
4)login函数请求(判断ajax)
from django.contrib import auth def login(request): if request.is_ajax(): name=request.POST.get(‘name‘) pwd=request.POST.get(‘pwd‘) code=request.POST.get(‘code‘) if code.upper()== request.session[‘code‘].upper(): user=auth.authenticate(request,username=name,password=pwd) if user: return HttpResponse(‘ok‘) else: return HttpResponse(‘用户名或密码错误‘) else: return HttpResponse(‘验证码错误‘) return render(request,‘login.html‘)
以上是关于Django框架之验证码生成示例的主要内容,如果未能解决你的问题,请参考以下文章