Python-web开发验证码的制作

一、安装依赖包Pillow

pip install Pillow

二、验证码一般是放在一个项目的工具方法中

Python-web开发验证码的制作

三、验证码的代码

#!/usr/bin/env python
# encoding: utf-8
from random import randint,choice
from PIL import Image,ImageDraw,ImageFont
from cStringIO import StringIO
from string import printable

def pillow_test():
    #设置选用的字体
    font_path = "utils/captcha/font/Arial.ttf"
    font_color = (randint(150, 200), randint(0, 150), randint(0, 150))
    line_color = (randint(0, 150), randint(0, 150), randint(150, 200))
    point_color = (randint(0, 150), randint(50, 150), randint(150, 200))

    #设置验证码的宽与高
    width, height = 100, 34
    image = Image.new("RGB",(width, height),(200,200,200))
    font = ImageFont.truetype(font_path,height - 10)
    draw = ImageDraw.Draw(image)

    #生成验证码
    text = "".join([choice(printable[:62]) for i in xrange(4)])
    font_width, font_height = font.getsize(text)
    #把验证码写在画布上
    draw.text((10, 10), text, font=font, fill=font_color)
    #绘制干扰线
    for i in xrange(0, 5):
        draw.line(((randint(0, width), randint(0, height)),
                   (randint(0, width), randint(0, height))),
                  fill=line_color, width=2)

    # 绘制点
    for i in xrange(randint(100, 1000)):
        draw.point((randint(0, width), randint(0, height)), fill=point_color)
    #输出
    out = StringIO()
    image.save(out, format='jpeg')
    content = out.getvalue()
    out.close()
    return text, content

四、创建一个视图返回验证码(基于tornado)

#获取图像验证码
class TestHandler(BaseHandler):
    def get(self):
        text, img = pillow_test()
        #设置头信息
        self.set_header("Content-Type", "image/jpg")
        self.write(img)

五、直接在前端页面中的img中使用这个视图

上一篇:560. Subarray Sum Equals K


下一篇:滴滴敏捷数据中台实践