验证码:
views.py:
# 随机生成rgb数字的函数 from PIL import Image, ImageDraw, ImageFont from io import BytesIO ## 图片保存(写到内存中) import random def get_rgb(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) def get_valid(request): # img = Image.new('RGB', (450, 30), get_rgb()) # 生成一张图片(Image模块下的new函数,返回一个Image对象)数字是宽,高 img = Image.new('RGB', (450, 30), (255, 255, 255)) img_draw = ImageDraw.Draw(img) # 把图片放到画板上 img_font = ImageFont.truetype('./static/font/ss.TTF', 25) # 随机生成5个大写字母,小写字母,数字,文件需要是ttf格式,25是大小 valid_code = '' for i in range(5): low_char = chr(random.randint(97, 122)) num_char = random.randint(0, 9) upper_char = chr(random.randint(65, 90)) res = random.choice([low_char, num_char, upper_char]) valid_code += str(res) img_draw.text((i * 63 + 50, 0), str(res), get_rgb(), img_font) print(valid_code) # 把验证码存到session中 request.session['valid_code'] = valid_code # 画线和点圈 width = 450 height = 30 for i in range(10): x1 = random.randint(0, width) x2 = random.randint(0, width) y1 = random.randint(0, height) y2 = random.randint(0, height) # 在图片上画线 img_draw.line((x1, y1, x2, y2), fill=get_rgb()) for i in range(50): # 画点 img_draw.point([random.randint(0, width), random.randint(0, height)], fill=get_rgb()) x = random.randint(0, width) y = random.randint(0, height) # 画弧形 img_draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_rgb()) f = BytesIO() img.save(f, 'png') data = f.getvalue() return HttpResponse(data)
随机验证码点击更换:
html:
<script> $("#id_valid_code").click(function () { var url = $("#id_valid_code")[0].src $("#id_valid_code")[0].src = url + '?' }) $("#id_submit").click(function () { //不建议在js中写模板语法 $.ajax({ url: '/login/', method: 'post', data: { 'username': $('[name="username"]').val(), 'password': $('[name="password"]').val(), 'valid_code': $('[name="valid_code"]').val(), 'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val() }, success:function (data) { if(data.code==100){ location.href=data.url }else { $('.error').html(data.msg) } } }) }) </script>
# 生成一张图片(Image模块下的new函数,返回一个Image对象)标签:code,img,randint,random,验证码,rgb,valid From: https://www.cnblogs.com/97zs/p/17931579.html