import random,string
# 加密用到的模块
import hashlib,hmac
from PIL import Image,ImageDraw,ImageFont,ImageFilter
from django.conf import settings
# 获取一个随机字符串,4位的
def getRandomChar(count=4):
# 生成随机字符串
# string模块包含各种字符串,以下为小写字母加数字
ran = string.ascii_lowercase + string.ascii_uppercase + string.digits
char = ''
for i in range(count):
char += random.choice(ran)
return char
# 返回一个随机的RGB颜色
def getRandomColor():
return (random.randint(50,150),random.randint(50,150),random.randint(50,150))
def create_code():
# 创建图片,模式,大小,背景色
img = Image.new('RGB', (120,40), (255,255,255))
#创建画布
draw = ImageDraw.Draw(img)
# 设置字体
font = ImageFont.truetype('./font/arial.ttf', 25)
code = getRandomChar()
# 将生成的字符画在画布上
for t in range(4):
draw.text((30*t+5,0),code[t],getRandomColor(),font)
# 生成干扰点
for _ in range(random.randint(0,200)):
# 位置,颜色
draw.point((random.randint(0, 120),random.randint(0, 30)),fill=getRandomColor())
# 使用模糊滤镜使图片模糊
# img = img.filter(ImageFilter.BLUR)
# 保存
# img.save(''.join(code)+'.jpg','jpeg')
return img,code
# md5加密
def encrypt_by_md5(pwd):
md5 = hashlib.md5(pwd.encode("utf-8"))
md5.update(settings.MD5ZHI.encode("utf-8"))
# md5.update("yuzihua".encode("utf-8"))
return md5.hexdigest()
# hmac对称加密
def hmac_by_md5(pwd):
return hmac.new(pwd.encode('utf-8'), settings.MD5ZHI.encode("utf-8"), "MD5").hexdigest()
# return hmac.new(pwd.encode('utf-8'), "123456".encode("utf-8"), "MD5").hexdigest()
if __name__ == '__main__':
print(hmac_by_md5("123456"))
print(encrypt_by_md5("123456"))
2、然后就可以在其他模块调用
# 生成验证码
def code(request):
img, code = utils.create_code()
# 首先需要将code保存到session中
request.session['code'] = code
# 返回图片
file = BytesIO()
img.save(file, 'PNG')
return HttpResponse(file.getvalue(), "image/png")
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6ca8ae0fe2cdc0da5c52c61dcab7f8c1.jpeg)
# 加密
password = utils.encrypt_by_md5(password)
password1 = utils.encrypt_by_md5(password1)
# 接受验证码
code = request.POST["code"]
my_code = request.session["code"]
if code.upper() != my_code.upper():
return render(request, 'blog/register.html', {"msg": "验证码错误,请重新填写!"})
# 删除session中的验证码
del request.session["code"]
3、html页面
<!--验证码-->
<div class="f-rember" style="margin-top: 20px">
<div class="col-md-4">
<input type="text" name="code" placeholder="请输入验证码" autocomplete="off">
</div>
<div class="col-md-5">
<a href="#" onclick="changeCode()"><img id="code" src="{% url 'blog:code' %}" alt="验证码" title="点击刷新"></a>
</div>
<div class="col-md-3" style="margin-top: 10px;">
<a href="#" onclick="changeCode()" style="align-content: center">刷新</a>
</div>
</div>
<script>
function changeCode() {
// document.getElementById("code").src = "/blog/code?id="+ new Date().getTime()
document.getElementById("code").src = "/blog/code?id="+ Math.random()
}
</script>