代码实现验证码功能
现在大部分网址登录时都需要输验证码才允许登录,在这里我用python代码来实现手写一套验证码逻辑
Django后端代码
# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io
# 自定义图片验证码
class MyCode(View):
# 定义RGB随机颜色
def get_random_color(self):
R = random.randrange(255)
G = random.randrange(255)
B = random.randrange(255)
return(R, G, B)
# 定义图片视图
def get(self, request):
# 画布
img_size = (130, 60)
# 定义图片对象
image = Image.new('RGB', img_size, '#FFFFE0')
# 定义画笔
draw = ImageDraw.Draw(image, 'RGB')
# 定义内容
source = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
# 定义字体
my_font = ImageFont.truetype(font="c:\\Windows\\Fonts\\comic.ttf", size=25)
# 接收容器
code_str = ''
# 进入循环绘制
for i in range(4):
# 获取字体颜色
text_color = self.get_random_color()
# 获取随机下标
tmp_num = random.randrange(len(source))
# 随机字符串
random_str = source[tmp_num]
# 装入容器中
code_str += random_str
# 绘制字符串 坐标(x, y) 随机字符串 字体颜色
draw.text((10 + 30 * i, 10), random_str, text_color, font=my_font)
# 获取缓冲区
buf = io.BytesIO()
# 将临时图片保存到缓冲区
image.save(buf, 'png')
# 保存随机码
r.set('code', code_str)
#保存session
request.session['code'] = code_str
print(r.get('code'))
return HttpResponse(buf.getvalue(), 'image/png')
vue前端代码
<template>
<div>
<table>
<tr>
<td>
验证码:
</td>
<td>
<input type="text" v-model="code" placeholder="请输入验证码">
</td>
</tr>
<tr>
<td></td>
<td>
<img class="imgcode" alt="点击刷新" :src="src" @click="changecode">
</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data () {
return {
// 验证码图片地址
src:'http://localhost:8000/code/',
// 验证码
code:'',
}
},
methods: {
// 刷新验证码
changecode:function () {
// 生成随机数
var num = Math.ceil(Math.random()*10);
// 进行传参
this.src = this.src + "?num=" + num;
},
}
}
<style>
/* 标签选择器 */
td {
padding: 5px;
}
.imgcode {
cursor:pointer;
}
</style>
就是这么简单,最后附上项目地址: https://github.com/TianShangXing/mydjango