验证码

1 pillow模块手撸实现

pip install pillow


def get_rgb():
  return (random.randint(0,255),
random.randint(0,255),random.randint(0,255))

def get_valid_code(request): # 生成一张图片(Image模块下的new函数,返回一个Image对象) img = Image.new('RGB', (450,30),(255,255,255)) # 把图片放到画板上 img_draw = ImageDraw.Draw(img) # 验证码字体从下载的ttf文件中获取 img_font = ImageFont.truetype('./static/font/ss/TTF', 25) # 随机生成5个验证码,包含数字,字母大小写 valid_code = '' for i in range(5): low_char = chr(random.randint(97,122)) num_char = random.randint(0,9) up_char = chr(random.randint(65,90)) res = random.choice([low_char, num_char, up_char]) valide_code+=str(res) img_draw.text((i*63+50, 0), str(res), get_rgb(), img_font) # 把验证码存到session中 request.session['valide_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)

 

2 gvcode和captcha实现

1 gvcode

pip install graphic-verification-code
import gvcode
​
#序列解包
s, v = gvcode.generate()    
​
#显示生成的验证码图片
s.show()    
​
#打印验证码字符串
print(v)    

 

2 captcha

pip install captcha
from captcha.image import ImageCaptcha
from random import randint
list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
chars = ''
for i in range(4):
    chars += list[randint(0, 62)]
image = ImageCaptcha().generate_image(chars)
​
image.show()

3 图片验证码刷新

1 从前端拿到验证码控件src

$("id_valid_ code")
=>w.fn.init[img#id_valid_code]

$("id_valid_ code")[0]
=><img src="/get_valid/" height="30" width="450" id="id_valid_code">

$("#id_valid_code")[0].src
=>"http://127.0.0.1:8000/get_valid/"

2 图片路径发生变化时就会像后端发送请求,

$("#id_valid_code").click(function(){
    var url = $("id_valid_code")[0].src
    $("#id_valid_code")[0].src += url+'?'
})

 

原文地址:https://www.cnblogs.com/xupengjun/p/14225817.html