利用python生成图形验证码
validCode.py
import random
from io import BytesIO from PIL import Image, ImageDraw, ImageFont def get_random_color():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) def get_valid_code_img(request):
img = Image.new('RGB', (260, 34), color=get_random_color())
draw = ImageDraw.Draw(img)
kumo_font = ImageFont.truetype('static/font/kumo.ttf', size=28) valid_code_str = ''
for i in range(5):
random_num = str(random.randint(0, 9))
random_low_alpha = chr(random.randint(97, 122))
random_high_alpha = chr(random.randint(65, 90))
random_char = random.choice([random_num, random_low_alpha, random_high_alpha])
draw.text((i * 50 + 20, 5), random_char, get_random_color(), font=kumo_font) # 保存验证码字符串
valid_code_str += random_char # 噪点噪线
width = 260
height = 34
for i in range(5):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
draw.line((x1, y1, x2, y2), fill=get_random_color()) for i in range(5):
draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
x = random.randint(0, width)
y = random.randint(0, height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color()) # 保存验证码字符串到该用户的session
request.session['valid_code_str'] = valid_code_str f = BytesIO() # 用完之后,BytesIO会自动清掉
img.save(f, 'png')
data = f.getvalue() return data
views.py
from django.contrib import auth
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse from blog.utils.validCode import get_valid_code_img def get_validCode_img(request):
"""
基于PIL模块动态生成响应状态码图片
:param request:
:return:
"""
data = get_valid_code_img(request)
return HttpResponse(data) def login(request):
if request.method == 'POST':
response = {'user': None, 'msg': None}
user = request.POST.get('user')
pwd = request.POST.get('pwd')
valid_code = request.POST.get('valid_code') valid_code_str = request.session.get('valid_code_str')
if valid_code.lower() == valid_code_str.lower():
user = auth.authenticate(username=user, password=pwd)
if user:
auth.login(request, user) # request.user == 当前登录对象
response['user'] = user.username
else:
response['msg'] = '用户名或密码错误'
else:
response['msg'] = '验证码错误'
return JsonResponse(response)
return render(request, 'login.html')
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆页面</title>
<link rel="stylesheet" href="/static/blog/bs/css/bootstrap.css">
</head>
<body> <h3>登陆页面</h3>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form id="fm">
{% csrf_token %}
<div class="form-group">
<label for="id_user">用户名</label>
<input type="text" name="user" id="id_user" class="form-control">
</div> <div class="form-group">
<label for="id_pwd">密码</label>
<input type="text" name="pwd" id="id_pwd" class="form-control">
</div> <div class="form-group">
<label for="id_valid_code">验证码</label>
<div class="row">
<div class="col-md-6">
<input type="text" name="valid_code" id="id_valid_code" class="form-control">
</div>
<div class="col-md-6">
<img width="260" height="34" src="/get_validCode_img/" id="valid_code_img">
</div>
</div>
</div> <input type="button" value="提交" id="login_btn" class="btn btn-default ">
<span id="error"></span>
</form>
</div>
</div>
</div> <script src="/static/blog/js/jquery-3.3.1.js"></script>
<script>
// 验证码图片刷新
$('#valid_code_img').click(function () {
$(this)[0].src += '?'; // 问号的唯一意义是:图片链接发生了变化,图片需要刷新
}); // 登陆验证
$('#login_btn').click(function () {
$.ajax({
url: '',
type: 'post',
data: $('#fm').serialize(),
success: function (data) {
if (data.user) {
location.href = '/index/'
} else {
$('#error').text(data.msg).css({'color': 'red', 'margin-left': '10px'});
setTimeout(function () {
$('#error').text('') // 3秒后清空error信息
}, 3000)
}
}
})
})
</script>
</body>
</html>
利用python生成图形验证码的更多相关文章
- python 生成图形验证码
文章链接:https://mp.weixin.qq.com/s/LYUBRNallHcjnhJb1R3ZBg 日常在网站使用过程中经常遇到图形验证,今天准备自己做个图形验证码,这算是个简单的功能,也适 ...
- PHP5 GD库生成图形验证码(汉字)
PHP5 GD库生成图形验证码且带有汉字的实例分享. 1,利用GD库函数生成图片,并在图片上写指定字符imagecreatetruecolor 新建一个真彩色图像imagecolorallocate ...
- PHP5生成图形验证码(有汉字)
利用PHP5中GD库生成图形验证码 类似于下面这样 1.利用GD库函数生成图片,并在图片上写指定字符 imagecreatetruecolor 新建一个真彩色图像 imagecolora ...
- C#生成图形验证码
先看效果: 再上代码 public class CaptchaHelper { private static Random rand = new Random(); private static in ...
- Python 生成随机验证码
Python生成随机验证码 Python生成随机验证码,需要使用PIL模块. 安装: 1 pip3 install pillow 基本使用 1. 创建图片 1 2 3 4 5 6 7 8 9 fro ...
- Python生成随机验证码
Python生成随机验证码,需要使用PIL模块. 安装: pip3 install pillow 基本使用 1.创建图片 from PIL import Image img = Image.new(m ...
- 利用Python生成随机密码
#coding:utf-8 #利用python生成一个随机10位的字符串 import string import random import re list = list(string.lowerc ...
- java生成图形验证码
效果图 import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.Buf ...
- Python利用PIL生成随机验证码图片
安装pillow: pip install pillow PIL中的Image等模块提供了创建图片,制作图片的功能,大致的步骤就是我们利用random生成6个随机字符串,然后利用PIL将字符串绘制城图 ...
随机推荐
- Linux利用iptables实现真-全局代理
对于经常要浏览油管等被墙网站的人而言,利用代理来实现fq是非常有必要的.现在fq的方法中,最为主流的应该要数ssr了,因此本教程都是基于ssr的socks5代理而言的. 在windows中,ssr客户 ...
- C# 发Domino邮件 报错误 Password or other security violation for database 的解决方案
错误提示: Password or other security violation for database ******* 问题产生的描述: 之前C#发邮件是好的 加上了附件部分代码之后,出现了这 ...
- cout格式化输出 详解
//在使用setf等库函数时使用 //在使用流操纵算子时使用 //using namespace std; //以下所有的setf()都有对应的unsetf()用于取消设置 //所有的setiosfl ...
- 事件(Application Event)
Spring的事件(Appllcation Event)为Bean与Bean之间的消息通信提供了支持.当一个Bean处理完一个任务后,希望另一个Bean知道并能做相应的处理,这种情况可以让另一个Bea ...
- php-7.1.11编译选项配置
./configure \ --prefix=/usr/local/php-7.1.11 \ --with-config-file-path=/usr/local/php7.1.11/etc \ -- ...
- ubuntu14.04server下安装scala+sbt工具
安装sbt参考https://www.cnblogs.com/wrencai/p/3867898.html 在安装scala时 首先得安装jdk环境,最好安装最新版本以免后续安装出现不必要的麻烦 一. ...
- 部署JavaWeb时出现 If a file is locked,you can wait until
在部署JavaWeb程序时出现了if a file is locked ,you can wait until the lock stop的问题,这个主要是classpath目录出错或者jar包未导入 ...
- [转贴] ASP.NET -- Web Service (.asmx) & JSON
[转贴] ASP.NET -- Web Service (.asmx) & JSON 以前没做过,但临时被要求 ASP.NET Web Service 要传回 JSON格式 找到网络上两篇好文 ...
- GridView的 PreRender事件与 RowCreated、RowDataBound事件大乱斗
GridView的 PreRender事件与 RowCreated.RowDataBound事件大乱斗 之前写了几个范例,做了GridView的 PreRender事件与 RowCreated.Row ...
- 从.net到java,从基础架构到解决方案。
这一年,职业生涯中的最大变化,是从.net到java的直接跨越,是从平台架构到解决方案的不断完善. 砥砺前行 初出茅庐,天下无敌.再学三年,寸步难行.很多时候不是别人太强,真的是自己太弱,却不自知. ...