django生成验证码
验证码生成依赖于PIL库。
生成验证码的代码如下:
def captcha(request):
width = 100
height = 40
bg_color = (255, 255, 255)
image = Image.new('RGB', (width, height), bg_color)
font = ImageFont.truetype('Arial.ttf', 30)
font_color = (0, 0, 0)
draw = ImageDraw.Draw(image)
captcha = ''
alphabet = []
for i in range(48, 58):
alphabet.append(chr(i))
for i in range(97, 123):
alphabet.append(chr(i))
for i in range(65, 91):
alphabet.append(chr(i))
for i in range(4):
captcha += random.choice(alphabet)
draw.text((random.randint(0, 30), random.randint(0, 15)), captcha, font=font, fill=font_color)
del draw
new_image = image.transform((width + 20, height + 10), Image.AFFINE,
(1, -0.3, random.randint(0, 10), -0.1, 1, random.randint(0, 10)))
new_draw = ImageDraw.Draw(new_image)
line_color = (0, 0, 0)
for i in range(0, 15):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
new_draw.line([(x1, y1), (x2, y2)], line_color)
del new_draw
buffer = StringIO.StringIO()
new_image.save(buffer, 'png')
request.session['captcha'] = captcha
return HttpResponse(content=buffer.getvalue(), content_type="image/png")
那么,生成的验证码如何才能能显示在网页的img标签里?首先添加url:url(r'^captcha', 'login.captcha'),然后将img的src指向改url就行了($('#img_captcha').attr('src', 'captcha/' + Math.random()))。
注意,通常我们在url后面加上随机数或者时间戳,来避免的浏览器缓存导致点击验证码时验证码不更新的问题。